text
stringlengths
2
1.05M
var test = require('tap').test, createGraph = require('..'); test('forEachLinkedNode respects orientation', function(t) { t.plan(3); var graph = createGraph(); graph.addLink(1, 2); graph.addLink(2, 3); var oriented = true; graph.forEachLinkedNode(2, function(node, link) { t.ok(link.toId === 3, 'Only 3 is connected to node 2, when traversal is oriented'); }, oriented); graph.forEachLinkedNode(2, function(node, link) { t.ok(link.toId === 3 || link.toId === 2, 'both incoming and outgoing links are visited'); }, !oriented); t.end(); }); test('forEachLinkedNode handles self-loops', function(t) { t.plan(1); var graph = createGraph(); graph.addLink(1, 1); // we should visit exactly one time graph.forEachLinkedNode(1, function(node, link) { t.ok(link.fromId === 1 && link.toId === 1, 'Link 1 is visited once'); }); t.end(); }); test('forEachLinkedNode will not crash on invalid node id', function(t) { t.plan(0); var graph = createGraph(); graph.addLink(1, 2); graph.forEachLinkedNode(3, function() { t.notOk(true, 'This code will never be executed'); }); }); test('forEachLinkedNode can quit fast for oriented graphs', function(t) { t.plan(1); var graph = createGraph(); var oriented = true; graph.addLink(1, 2); graph.addLink(1, 3); graph.forEachLinkedNode(1, function() { t.ok(true, 'Visited first link'); return true; // We want to stop right now! }, oriented); }); test('forEachLinkedNode can quit fast for non-oriented graphs', function(t) { t.plan(1); var graph = createGraph(); var oriented = false; graph.addLink(1, 2); graph.addLink(1, 3); graph.forEachLinkedNode(1, function() { t.ok(true, 'Visited first link'); return true; // We want to stop right now! }, oriented); }); test('forEachLinkedNode returns quitFast flag', function(t) { var graph = createGraph(); graph.addLink(1, 2); graph.addLink(1, 3); var fastQuit = graph.forEachLinkedNode(1, function() { return true; // Stop right now. }); t.ok(fastQuit, 'Fast quit triggered when callback opted out'); var notSoFast = graph.forEachLinkedNode(1, function() { }); t.notOk(notSoFast, 'Fast quit is not triggered when all elements visited'); t.end(); }); test('forEachLink visits each link', function(t) { t.plan(1); var graph = createGraph(); graph.addLink(1, 2); graph.forEachLink(function(link) { t.ok(link.fromId === 1 && link.toId === 2, 'Link is here'); }); t.end(); }); test('forEachLink will not crash on empty callback', function(t) { var graph = createGraph(); graph.addLink(1, 2); graph.forEachLink(); // didn't pass callback, no worries. t.end(); }); test('forEachNode will stop when requested', function(t) { t.plan(1); var graph = createGraph(); graph.addLink(1, 2); graph.forEachNode(function(node) { t.equal(node.id, 1, 'We visit only one node'); return true; // we want to stop now! }); t.end(); }); test('forEachNode returns fastQuit', function(t) { var graph = createGraph(); graph.addLink(1, 2); var fastQuit = graph.forEachNode(function(node) { t.equal(node.id, 1, 'We visit only one node'); return true; // we want to stop now! }); // no callback? No worries t.ok(fastQuit, 'fastQuit is set when callback opted out'); var notSoFast = graph.forEachNode(function() { }); t.notOk(notSoFast, 'fastQuit is not set when all nodes visited'); t.end(); });
// 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _fs = require('fs'); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _module2 = require('module'); var _module3 = _interopRequireDefault(_module2); // var _which = require('which'); var _which2 = _interopRequireDefault(_which); var _mkdirp = require('mkdirp'); var _mkdirp2 = _interopRequireDefault(_mkdirp); var _lodashPartial = require('lodash.partial'); var _lodashPartial2 = _interopRequireDefault(_lodashPartial); var _nomnom = require('nomnom'); var _nomnom2 = _interopRequireDefault(_nomnom); var _istanbul = require('istanbul'); var _instrumenter = require('./instrumenter'); // // _nomnom2['default'].command('cover').help("transparently adds coverage information to a node command. Saves coverage.json and reports at the end of execution").option('cmd', { required: true, position: 1, help: 'ES6 js files to cover (using babel)' }).option('config', { metavar: '<path-to-config>', help: 'the configuration file to use, defaults to .istanbul.yml' }).option('report', { 'default': 'lcv', metavar: '<format>', list: true, help: 'report format, defaults to [\'lcv\']' }).option('root', { metavar: '<path>', help: 'the root path to look for files to instrument, defaults to .' }).option('include', { 'default': ['**/*.js'], metavar: '<include-pattern>', list: true, abbr: 'i', help: 'one or more fileset patterns e.g. \'**/*.js\'' }).option('verbose', { flag: true, abbr: 'v', help: 'verbose mode' }).callback(function (opts) { var args = opts._, files = [], cmdArgs = []; args.forEach(function (arg) { var file = lookupFiles(arg); if (file) files = files.concat(file); }); opts.include = opts.include.concat(files); coverCmd(opts); }); ; _nomnom2['default'].nom(); function lookupFiles(path) { if ((0, _fs.existsSync)(path)) { var stat = (0, _fs.statSync)(path); if (stat.isFile()) return path; } } function callback(err) { if (err) { console.error(err); process.exit(1); } process.exit(0); } function coverCmd(opts) { var config = overrideConfigWith(opts); var reporter = new _istanbul.Reporter(config); var cmd = opts.cmd; var cmdArgs = opts['--'] || []; if (!(0, _fs.existsSync)(cmd)) { try { cmd = _which2['default'].sync(cmd); } catch (ex) { return callback('Unable to resolve file [' + cmd + ']'); } } else { cmd = _path2['default'].resolve(cmd); } if (opts.verbose) console.error('Isparta options : \n ', opts); var excludes = config.instrumentation.excludes(true); enableHooks(); //// function overrideConfigWith(opts) { var overrides = { verbose: opts.verbose, instrumentation: { root: opts.root, 'default-excludes': opts['default-excludes'], excludes: opts.x, 'include-all-sources': opts['include-all-sources'], 'preload-sources': opts['preload-sources'] }, reporting: { reports: opts.report, print: opts.print, dir: opts.dir }, hooks: { 'hook-run-in-context': opts['hook-run-in-context'], 'post-require-hook': opts['post-require-hook'], 'handle-sigint': opts['handle-sigint'] } }; return _istanbul.config.loadFile(opts.config, overrides); } function enableHooks() { opts.reportingDir = _path2['default'].resolve(config.reporting.dir()); _mkdirp2['default'].sync(opts.reportingDir); reporter.addAll(config.reporting.reports()); if (config.reporting.print() !== 'none') { switch (config.reporting.print()) { case 'detail': reporter.add('text'); break; case 'both': reporter.add('text'); reporter.add('text-summary'); break; default: reporter.add('text-summary'); break; } } excludes.push(_path2['default'].relative(process.cwd(), _path2['default'].join(opts.reportingDir, '**', '*'))); (0, _istanbul.matcherFor)({ root: config.instrumentation.root() || process.cwd(), includes: opts.include, excludes: excludes }, function (err, matchFn) { if (err) { return callback(err); } prepareCoverage(matchFn); runCommandFn(); }); } function prepareCoverage(matchFn) { var coverageVar = '$$cov_' + Date.now() + '$$'; var instrumenter = new _instrumenter.Instrumenter({ coverageVariable: coverageVar }); var transformer = instrumenter.instrumentSync.bind(instrumenter); _istanbul.hook.hookRequire(matchFn, transformer, Object.assign({ verbose: opts.verbose }, config.instrumentation.config)); global[coverageVar] = {}; if (config.hooks.handleSigint()) { process.once('SIGINT', process.exit); } process.once('exit', function (code) { if (code) { process.exit(code); } var file = _path2['default'].resolve(opts.reportingDir, 'coverage.json'); var cov = undefined, collector = undefined; if (typeof global[coverageVar] === 'undefined' || Object.keys(global[coverageVar]).length === 0) { console.error('No coverage information was collected, exit without writing coverage information'); return; } else { cov = global[coverageVar]; } _mkdirp2['default'].sync(opts.reportingDir); if (config.reporting.print() !== 'none') { console.error(Array(80 + 1).join('=')); console.error('Writing coverage object [' + file + ']'); } (0, _fs.writeFileSync)(file, JSON.stringify(cov), 'utf8'); collector = new _istanbul.Collector(); collector.add(cov); if (config.reporting.print() !== 'none') { console.error('Writing coverage reports at [' + opts.reportingDir + ']'); console.error(Array(80 + 1).join('=')); } reporter.write(collector, true, callback); }); if (config.instrumentation.includeAllSources()) { matchFn.files.forEach(function (file) { if (opts.verbose) { console.error('Preload ' + file); } try { require(file); } catch (ex) { if (opts.verbose) { console.error('Unable to preload ' + file); } // swallow } }); } } function runCommandFn() { process.argv = ["node", cmd].concat(cmdArgs); if (opts.verbose) { console.log('Running: ' + process.argv.join(' ')); } process.env.running_under_istanbul = 1; _module3['default'].runMain(cmd, null, true); } }
/** * @copyright Copyright (c)2021 Maxim Khorin <maksimovichu@gmail.com> */ Club.FormGames = class FormGames extends Club.FormRadioList { init () { super.init(); this.renderItems(); this.$list.find('input').first().click(); } renderItems () { const items = this.club.games.map(({name, label}) => { label = Jam.t(label, name); return this.resolveTemplate('game', {name, label}) }); this.find('.form-game-list').append(items.join('')); } };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.icon = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var _react = _interopRequireDefault(require("react")); var EuiIconEditorAlignCenter = function EuiIconEditorAlignCenter(_ref) { var title = _ref.title, titleId = _ref.titleId, props = (0, _objectWithoutProperties2.default)(_ref, ["title", "titleId"]); return _react.default.createElement("svg", (0, _extends2.default)({ width: 16, height: 16, viewBox: "0 0 16 16", xmlns: "http://www.w3.org/2000/svg", "aria-labelledby": titleId }, props), title ? _react.default.createElement("title", { id: titleId }, title) : null, _react.default.createElement("path", { d: "M5 4V3h6v1H5zM3 7V6h10v1H3zm2 3V9h6v1H5zm-2 3v-1h10v1H3z" })); }; var icon = EuiIconEditorAlignCenter; exports.icon = icon; EuiIconEditorAlignCenter.__docgenInfo = { "description": "", "methods": [], "displayName": "EuiIconEditorAlignCenter" };
load("201224b0d1c296b45befd2285e95dd42.js"); function f() { function g() { eval(""); gc(); Math.abs(4); NaN; } g(); } function h() { var x, y; x = Math.floor(-0); y = parseInt("1"); } f(); h();
require("../../../common/manifest.js"); require("../../../common/vendor.js"); global.webpackJsonp([1],{ /***/ 121: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_selector_type_script_index_0_node_modules_mpvue_config_loader_0_1_2_mpvue_config_loader_index_js_index_vue__ = __webpack_require__(124); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_template_compiler_index_id_data_v_acdfce46_hasScoped_true_transformToRequire_video_src_source_src_img_src_image_xlink_href_node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_selector_type_template_index_0_node_modules_mpvue_config_loader_0_1_2_mpvue_config_loader_index_js_index_vue__ = __webpack_require__(136); var disposed = false function injectStyle (ssrContext) { if (disposed) return __webpack_require__(122) __webpack_require__(123) } var normalizeComponent = __webpack_require__(0) /* script */ /* template */ /* styles */ var __vue_styles__ = injectStyle /* scopeId */ var __vue_scopeId__ = "data-v-acdfce46" /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = normalizeComponent( __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_selector_type_script_index_0_node_modules_mpvue_config_loader_0_1_2_mpvue_config_loader_index_js_index_vue__["a" /* default */], __WEBPACK_IMPORTED_MODULE_1__node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_template_compiler_index_id_data_v_acdfce46_hasScoped_true_transformToRequire_video_src_source_src_img_src_image_xlink_href_node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_selector_type_template_index_0_node_modules_mpvue_config_loader_0_1_2_mpvue_config_loader_index_js_index_vue__["a" /* default */], __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "src\\pages\\shop\\index\\index.vue" if (Component.esModule && Object.keys(Component.esModule).some(function (key) {return key !== "default" && key.substr(0, 2) !== "__"})) {console.error("named exports are not supported in *.vue files.")} if (Component.options.functional) {console.error("[vue-loader] index.vue: functional components are not supported with templates, they should use render functions.")} /* hot reload */ if (false) {(function () { var hotAPI = require("vue-loader/node_modules/vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-acdfce46", Component.options) } else { hotAPI.reload("data-v-acdfce46", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} /* harmony default export */ __webpack_exports__["a"] = (Component.exports); /***/ }), /***/ 122: /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /***/ 123: /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /***/ 124: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_babel_runtime_core_js_json_stringify__ = __webpack_require__(65); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_babel_runtime_core_js_json_stringify___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_babel_runtime_core_js_json_stringify__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__components_shop_search__ = __webpack_require__(84); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__components_slide__ = __webpack_require__(129); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__components_shop_goodsList__ = __webpack_require__(85); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils__ = __webpack_require__(8); // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["a"] = ({ data: function data() { return { motto: 'Hello World', slides: [], categorys: [], goods: [] }; }, components: { search: __WEBPACK_IMPORTED_MODULE_1__components_shop_search__["a" /* default */], slide: __WEBPACK_IMPORTED_MODULE_2__components_slide__["a" /* default */], goodsList: __WEBPACK_IMPORTED_MODULE_3__components_shop_goodsList__["a" /* default */] }, computed: { // 处理分类 categoryList: function categoryList() { var arr = JSON.parse(__WEBPACK_IMPORTED_MODULE_0_babel_runtime_core_js_json_stringify___default()(this.categorys)); var len = 0; var arr2 = []; arr.length % 8 == 0 ? len = arr.length / 8 : len = parseInt(arr.length / 8) + 1; for (var i = 0; i < len; i++) { arr2.push(arr.slice(i * 8, (i + 1) * 8)); } return arr2; } }, methods: { goToUrl: function goToUrl(pid, id) { this.GLOBAL.app.pid = pid; this.GLOBAL.app.id = id; wx.switchTab({ url: '/pages/shop/lists/index' }); } }, onLoad: function onLoad() { var _this = this; console.log('首页加载了'); Object(__WEBPACK_IMPORTED_MODULE_4__utils__["b" /* get */])('shop/api/index').then(function (res) { console.log(res); _this.slides = res.slideshow; _this.categorys = res.category; _this.goods = res.goods; }); Object(__WEBPACK_IMPORTED_MODULE_4__utils__["b" /* get */])("shop/api/cart/PHPSESSID/" + wx.getStorageSync("PHPSESSID")).then(function (res) { var num = res.lists.length; _this.$store.commit("getCartShopNum", { num: num }); }).catch(function (err) { console.log("失败:" + err); }); }, onShareAppMessage: function onShareAppMessage() { // 分享 return { title: '易商城首页', path: '/pages/index/index' }; } }); /***/ }), /***/ 129: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_selector_type_script_index_0_slide_vue__ = __webpack_require__(131); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_template_compiler_index_id_data_v_1357d9ae_hasScoped_false_transformToRequire_video_src_source_src_img_src_image_xlink_href_node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_selector_type_template_index_0_slide_vue__ = __webpack_require__(132); var disposed = false function injectStyle (ssrContext) { if (disposed) return __webpack_require__(130) } var normalizeComponent = __webpack_require__(0) /* script */ /* template */ /* styles */ var __vue_styles__ = injectStyle /* scopeId */ var __vue_scopeId__ = null /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = normalizeComponent( __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_selector_type_script_index_0_slide_vue__["a" /* default */], __WEBPACK_IMPORTED_MODULE_1__node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_template_compiler_index_id_data_v_1357d9ae_hasScoped_false_transformToRequire_video_src_source_src_img_src_image_xlink_href_node_modules_mpvue_loader_1_1_2_mpvue_loader_lib_selector_type_template_index_0_slide_vue__["a" /* default */], __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "src\\components\\slide.vue" if (Component.esModule && Object.keys(Component.esModule).some(function (key) {return key !== "default" && key.substr(0, 2) !== "__"})) {console.error("named exports are not supported in *.vue files.")} if (Component.options.functional) {console.error("[vue-loader] slide.vue: functional components are not supported with templates, they should use render functions.")} /* hot reload */ if (false) {(function () { var hotAPI = require("vue-loader/node_modules/vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-1357d9ae", Component.options) } else { hotAPI.reload("data-v-1357d9ae", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} /* harmony default export */ __webpack_exports__["a"] = (Component.exports); /***/ }), /***/ 130: /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /***/ 131: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["a"] = ({ props: { autoplay: '', interval: { type: Number, default: 3000 }, slides: Array, isDot: { type: Boolean, default: true } }, methods: { goUrl: function goUrl(url) { if (!url) { return false; } wx.navigateTo({ url: '/pages/shop/web_view/index?url=' + url }); } } }); /***/ }), /***/ 132: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', { staticClass: "slide" }, [_c('swiper', { staticClass: "swiper", attrs: { "indicator-dots": _vm.isDot, "autoplay": _vm.autoplay, "interval": _vm.interval, "indicator-active-color": "#ff0204", "indicator-color": "rgba(255,255,255,.3)" } }, _vm._l((_vm.slides), function(item, index) { return _c('swiper-item', { key: index, attrs: { "mpcomid": '0-' + index } }, [_c('div', { staticClass: "slide-url", attrs: { "eventid": '0-' + index }, on: { "click": function($event) { _vm.goUrl(item.url) } } }, [_c('image', { staticClass: "slide-image", attrs: { "src": item.img, "mode": "aspectFill" } })])]) }))], 1) } var staticRenderFns = [] render._withStripped = true var esExports = { render: render, staticRenderFns: staticRenderFns } /* harmony default export */ __webpack_exports__["a"] = (esExports); if (false) { module.hot.accept() if (module.hot.data) { require("vue-loader/node_modules/vue-hot-reload-api").rerender("data-v-1357d9ae", esExports) } } /***/ }), /***/ 136: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', { staticClass: "index" }, [_c('search', { attrs: { "mpcomid": '0' } }), _vm._v(" "), (_vm.slides) ? _c('slide', { attrs: { "slides": _vm.slides, "autoplay": true, "mpcomid": '1' } }) : _vm._e(), _vm._v(" "), _c('div', { staticClass: "categorys" }, [_c('swiper', { attrs: { "indicator-dots": "true", "indicator-color": "#eee", "indicator-active-color": "#ff0204" } }, _vm._l((_vm.categoryList), function(item, index) { return _c('swiper-item', { key: index, staticClass: "category-block", attrs: { "mpcomid": '2-' + index } }, _vm._l((item), function(category, idx) { return _c('div', { key: category.id, staticClass: "category-block__item", attrs: { "eventid": '0-' + index + '-' + idx }, on: { "click": function($event) { _vm.goToUrl(category.pid, category.id) } } }, [_c('img', { staticClass: "category-block__img", attrs: { "lazy-load": "", "src": category.icon, "mode": "aspectFill" } }), _vm._v(" "), _c('p', { staticClass: "category-block__txt overflow-dot_row" }, [_vm._v(_vm._s(category.title))])], 1) })) }))], 1), _vm._v(" "), _c('p', { staticClass: "page-title" }, [_vm._v("猜你喜欢")]), _vm._v(" "), (_vm.goods) ? _c('goodsList', { attrs: { "goodsData": _vm.goods, "mpcomid": '3' } }) : _vm._e()], 1) } var staticRenderFns = [] render._withStripped = true var esExports = { render: render, staticRenderFns: staticRenderFns } /* harmony default export */ __webpack_exports__["a"] = (esExports); if (false) { module.hot.accept() if (module.hot.data) { require("vue-loader/node_modules/vue-hot-reload-api").rerender("data-v-acdfce46", esExports) } } /***/ }) },[317]);
import _ from 'lodash' import React, {Component} from 'react' import { Picker, Text, View } from 'react-native' import PropTypes from 'prop-types' import styles from './styles' function renderHelper () { const paydays = [] const FINAL_PAYDAY = 15 for (let i = 0; i < FINAL_PAYDAY; i++) { paydays.push(<Picker.Item key={`paydayItem${i + 1}`} label={(i + 1).toString()} value={(i + 1).toString()} />) } return paydays } function PayDay (props) { return ( <View style={styles.pickerContainer}> <Text style={styles.header}> Wallet payday: </Text> <Picker enabled={props.enabled} style={styles.picker} selectedValue={props.selectedPayCheckDay} style={props.style} onValueChange={props.updateStateFn}> {renderHelper()} </Picker> {props.error && <Text style={styles.errorMessage}>{props.error}</Text>} </View> ) } PayDay.propTypes = { error: PropTypes.object, selectedPayCheckDay: PropTypes.string, style: PropTypes.object, updateStateFn: PropTypes.func.isRequired, } export default PayDay
/** * @license * Copyright 2018 Brigham Young University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ 'use strict'; /** * Toggle the case of a string based on the number value passed in. * @param {string} string * @param {number} number * @param {object} [options={allowOverflow: true}] * @returns {string|boolean} */ module.exports = binaryCase; function binaryCase(string, number, options) { if (!options || typeof options !== 'object') options = {}; if (!options.hasOwnProperty('allowOverflow')) options.allowOverflow = true; if (number > binaryCase.maxNumber(string) && !options.allowOverflow) return false; return getBinaryCase(string, number); } binaryCase.iterator = function(string, options) { const max = binaryCase.maxNumber(string); if (!options || typeof options !== 'object') options = {}; if (!options.hasOwnProperty('startIndex')) options.startIndex = 0; if (typeof options.startIndex !== 'number' || !Number.isInteger(options.startIndex) || options.startIndex < 0) throw Error('Option startIndex must be a non-negative integer.'); let index = options.startIndex; return { next: function() { return index > max ? { done: true } : { done: false, value: getBinaryCase(string, index++) }; } }; }; /** * Get the maximum number that can be used before causing overflow. * @param {string} string * @returns {number} */ binaryCase.maxNumber = function(string) { const pow = string.match(/[a-z]/ig).length; return Math.pow(2, pow) - 1; }; /** * Get an array of all possible variations. * @param {string} string * @returns {string[]} */ binaryCase.variations = function(string) { const results = []; const max = binaryCase.maxNumber(string); for (let i = 0; i <= max; i++) { results.push(binaryCase(string, i)); } return results; }; /** * A performance improved method for acquiring the binary case, provided by Blake Embrey with very minor modification by James Speirs. * @author Blake Embrey | https://github.com/blakeembrey * @author James Speirs | https://github.com/gi60s * @param {string} str * @param {number} val * @returns {string} */ function getBinaryCase (str, val) { let res = ''; for (let i = 0; i < str.length; i++) { const code = str.charCodeAt(i); if (code >= 65 && code <= 90) { res += val & 1 ? String.fromCharCode(code + 32) : String.fromCharCode(code); val >>>= 1; } else if (code >= 97 && code <= 122) { res += val & 1 ? String.fromCharCode(code - 32) : String.fromCharCode(code); val >>>= 1; } else { res += String.fromCharCode(code); } if (val === 0) { return res + str.substr(i + 1); } } return res; }
import React from 'react'; import Items from '../components/Items'; import TechnologyList from '../components/technologies/TechnologyList'; class Technologies extends React.Component { render() { return ( <Items {...this.props} name="Technology" keyName="technologies" list={TechnologyList} /> ); } } export default Technologies;
/* Copyright 2015 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ "use strict"; function fetchMessage() { document.getElementById("demo").innerHTML = "Eat my feet!"; }
function onLogIn() { var logUsername = getInputInfo('username'); var logPassword = getInputInfo('password'); var users = getUsersFromStorage(); var currUser = users.find(user => user.username === logUsername); if (!currUser) { alert('Wrong Username!'); clearInputInfo(); return; } if (currUser.password === logPassword) { onSuccesfullLog(currUser); } else { alert('Wrong Password!'); clearInputInfo(); } } function onLogOut() { renderDisplay(); localStorage.removeItem('currUser'); renderAdminDiv(false); } function onSuccesfullLog(currUser) { saveUserToStorage(currUser); updateUserLogTime(currUser); renderDisplay(); renderUsernameDiv(currUser); renderAdminDiv(currUser.isAdmin); clearInputInfo(); } function updateUserLogTime(currUser) { currUser.lastLoginTime = Date.now(); var users = getUsersFromStorage(); modalUser = users.find(user => user.username === currUser.username); modalUser.lastLoginTime = currUser.lastLoginTime; saveUsersToStorage(users); }
const availableModels = [ { modelName: 'DeepLab 513', modelFile: './model/deeplab_mobilenetv2_513.tflite', labelsFile: './model/labels.txt', inputSize: [513, 513, 3], outputSize: [513, 513, 21], } ]; function main(camera) { const videoElement = document.getElementById('video'); const imageElement = document.getElementById('image'); const inputElement = document.getElementById('input'); const inputGTElement = document.getElementById('inputGT'); const buttonEelement = document.getElementById('button'); const buttonGTEelement = document.getElementById('buttonGT'); const progressContainer = document.getElementById('progressContainer'); const progressBar = document.getElementById('progressBar'); const selectPrefer = document.getElementById('selectPrefer'); const backend = document.getElementById('backend'); const wasm = document.getElementById('wasm'); const webgl = document.getElementById('webgl'); const webml = document.getElementById('webml'); const zoomSlider = document.getElementById('zoomSlider'); const blurSlider = document.getElementById('blurSlider'); const refineEdgeSlider = document.getElementById('refineEdgeSlider'); const colorMapAlphaSlider = document.getElementById('colorMapAlphaSlider'); const selectBackgroundButton = document.getElementById('chooseBackground'); const clearBackgroundButton = document.getElementById('clearBackground'); const outputCanvas = document.getElementById('output'); let clippedSize = []; let currentBackend = ''; let currentModel = ''; let currentPrefer = ''; let streaming = false; let hoverPos = null; let stats; let imgGTDic; const counterN = 20; let counter = 0; let inferTimeAcc = 0; let drawTimeAcc = 0; let renderer = new Renderer(outputCanvas); renderer.setup(); let utils = new Utils(); // register updateProgress function if progressBar element exist utils.progressCallback = updateProgress; let colorPicker = new iro.ColorPicker("#color-picker-container", { width: 200, height: 200, color: { r: renderer.bgColor[0], g: renderer.bgColor[1], b: renderer.bgColor[2] }, markerRadius: 5, sliderMargin: 12, sliderHeight: 20, }); $('.bg-value').html(colorPicker.color.hexString); colorPicker.on('color:change', function(color) { $('.bg-value').html(color.hexString); renderer.bgColor = [color.rgb.r, color.rgb.g, color.rgb.b]; }); zoomSlider.value = renderer.zoom * 100; $('.zoom-value').html(renderer.zoom + 'x'); zoomSlider.oninput = () => { let zoom = zoomSlider.value / 100; $('.zoom-value').html(zoom + 'x'); renderer.zoom = zoom; }; colorMapAlphaSlider.value = renderer.colorMapAlpha * 100; $('.color-map-alpha-value').html(renderer.colorMapAlpha); colorMapAlphaSlider.oninput = () => { let alpha = colorMapAlphaSlider.value / 100; $('.color-map-alpha-value').html(alpha); renderer.colorMapAlpha = alpha; }; blurSlider.value = renderer.blurRadius; $('.blur-radius-value').html(renderer.blurRadius + 'px'); blurSlider.oninput = () => { let blurRadius = parseInt(blurSlider.value); $('.blur-radius-value').html(blurRadius + 'px'); renderer.blurRadius = blurRadius; }; refineEdgeSlider.value = renderer.refineEdgeRadius; if (refineEdgeSlider.value === '0') { $('.refine-edge-value').html('DISABLED'); } else { $('.refine-edge-value').html(refineEdgeSlider.value + 'px'); } refineEdgeSlider.oninput = () => { let refineEdgeRadius = parseInt(refineEdgeSlider.value); if (refineEdgeRadius === 0) { $('.refine-edge-value').html('DISABLED'); } else { $('.refine-edge-value').html(refineEdgeRadius + 'px'); } renderer.refineEdgeRadius = refineEdgeRadius; }; $('.effects-select .btn input').filter(function() { return this.value === renderer.effect; }).parent().toggleClass('active'); $('.controls').attr('data-select', renderer.effect); $('.effects-select .btn').click((e) => { e.preventDefault(); let effect = e.target.children[0].value; $('.controls').attr('data-select', effect); renderer.effect = effect; }); function checkPreferParam() { if (currentOS === 'Mac OS') { let preferValue = getPreferParam(); if (preferValue === 'invalid') { console.log("Invalid prefer, prefer should be 'fast' or 'sustained', try to use WASM."); showPreferAlert(); } } } checkPreferParam(); function showAlert(backend) { let div = document.createElement('div'); div.setAttribute('id', 'backendAlert'); div.setAttribute('class', 'alert alert-warning alert-dismissible fade show'); div.setAttribute('role', 'alert'); div.innerHTML = `<strong>Currently ${backend} backend doesn't support DeepLab Model.</strong>`; div.innerHTML += `<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>`; let container = document.getElementById('container'); container.insertBefore(div, container.firstElementChild); } function showPreferAlert() { let div = document.createElement('div'); div.setAttribute('id', 'preferAlert'); div.setAttribute('class', 'alert alert-danger alert-dismissible fade show'); div.setAttribute('role', 'alert'); div.innerHTML = `<strong>Invalid prefer, prefer should be 'fast' or 'sustained'.</strong>`; div.innerHTML += `<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>`; let container = document.getElementById('container'); container.insertBefore(div, container.firstElementChild); } function removeAlertElement() { let backendAlertElem = document.getElementById('backendAlert'); if (backendAlertElem !== null) { backendAlertElem.remove(); } let preferAlertElem = document.getElementById('preferAlert'); if (preferAlertElem !== null) { preferAlertElem.remove(); } } function updateBackend() { if (getUrlParams('api_info') === 'true') { backend.innerHTML = currentBackend === 'WebML' ? currentBackend + '/' + getNativeAPI(currentPrefer) : currentBackend; } else { backend.innerHTML = currentBackend; } } function changeBackend(newBackend, force) { if (!force && currentBackend === newBackend) { return; } streaming = false; if (newBackend !== "WebML") { selectPrefer.style.display = 'none'; } else { selectPrefer.style.display = 'inline'; } // renderer.deleteAll(); utils.deleteAll(); backend.innerHTML = 'Setting...'; setTimeout(() => { utils.init(newBackend, currentPrefer).then(() => { currentBackend = newBackend; updatePrefer(); updateModel(); updateBackend(); if (!camera) { predictAndDraw(imageElement); } else { streaming = true; startPredict(); } }).catch((e) => { console.warn(`Failed to change backend ${newBackend}, switch back to ${currentBackend}`); console.log(e); showAlert(newBackend); changeBackend(currentBackend, true); updatePrefer(); updateModel(); updateBackend(); }); }, 10); } function updateModel() { selectModel.innerHTML = currentModel; } function changeModel(newModel) { if (currentModel === newModel.modelName) { return; } streaming = false; // renderer.deleteAll(); utils.deleteAll(); removeAlertElement(); utils.changeModelParam(newModel); currentPrefer = "sustained"; progressContainer.style.display = "inline"; selectModel.innerHTML = 'Setting...'; setTimeout(() => { utils.init(currentBackend, currentPrefer).then(() => { currentModel = newModel.modelName; updatePrefer(); updateBackend(); updateModel(); if (!camera) { predictAndDraw(imageElement); } else { let res = utils.getFittedResolution(4 / 3); setCamResolution(res, currentBackend, currentPrefer).then(() => { streaming = true; startPredict(); }); } }); }, 10); } function changePrefer(newPrefer, force) { if (currentPrefer === newPrefer && !force) { return; } streaming = false; // renderer.deleteAll(); utils.deleteAll(); removeAlertElement(); selectPrefer.innerHTML = 'Setting...'; setTimeout(() => { utils.init(currentBackend, newPrefer).then(() => { currentPrefer = newPrefer; updatePrefer(); updateModel(); updateBackend(); if (!camera) { predictAndDraw(imageElement); } else { streaming = true; startPredict(); } }).catch((e) => { let currentBackend = 'WebML/' + getNativeAPI(currentPrefer); let nextBackend = 'WebML/' + getNativeAPI(newPrefer); console.warn(`Failed to change backend ${nextBackend}, switch back to ${currentBackend}`); console.error(e); changePrefer(currentPrefer, true); showAlert(nextBackend); updatePrefer(); updateBackend(); }); }, 10); } function updatePrefer() { selectPrefer.innerHTML = preferMap[currentPrefer]; } function updateProgress(ev) { if (ev.lengthComputable) { let percentComplete = ev.loaded / ev.total * 100; percentComplete = percentComplete.toFixed(0); progressBar.style = `width: ${percentComplete}%`; progressBar.innerHTML = `${percentComplete}%`; if (ev.loaded === ev.total) { progressContainer.style.display = "none"; progressBar.style = `width: 0%`; progressBar.innerHTML = `0%`; } } } async function predictAndDraw(imageSource) { clippedSize = utils.prepareInput(imageSource, renderer); renderer.uploadNewTexture(imageSource, clippedSize); let result = await utils.predict(); let inferTime = result.time; console.log(`Inference time: ${inferTime.toFixed(2)} ms`); inferenceTime.innerHTML = `inference time: <em style="color:green;font-weight:bloder">${inferTime.toFixed(2)} </em>ms`; renderer.drawOutputs(result.segMap) renderer.highlightHoverLabel(hoverPos); } async function getBasedata(url, width=513, height=513) { let image = new Image(width, height); image.src = url; return new Promise((resolve, reject) => { image.crossOrigin = ''; image.onload = () => { let canvas = document.getElementById('canvasGT'); canvas.width = width; canvas.height = height; canvas.setAttribute("width", width); canvas.setAttribute("height", height); let ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0, width, height); const pixels = ctx.getImageData(0, 0, width, height).data; const channels = 3; const imageChannels = 4; let baseData = new Array(); // NHWC layout hidden for (let y = 0; y < height; ++y) { for (let x = 0; x < width; ++x) { let value = pixels[y*width*imageChannels + x*imageChannels]; if (value === 255) { baseData.push(15); } else { baseData.push(0); } } } resolve(baseData); }; }); } function doCompare(dist, src, rows=513, cols=513) { let TP = 0; let FN = 0; let FP = 0; for (let j=0; j<cols; j++) { for (let i=0; i<rows; i++) { if (src[j*513 + i] === 15){ if (dist[j*513 + i] === src[j*513 + i]) { TP += 1; } else { FN += 1; } } else { if (dist[j*513 + i] === 15) { FP += 1; } } } } dist.length = 0; src.length = 0; return TP * 1.0 / (TP + FN + FP); } async function getAccuracy(imageSource, gtDic) { let clippedSize = utils.prepareInput(imageSource, renderer); let result = await utils.predict(); let inferTime = result.time; console.log(`Inference time: ${inferTime.toFixed(2)} ms`); inferenceTime.innerHTML = `inference time: <em style="color:green;font-weight:bloder">${inferTime.toFixed(2)} </em>ms`; renderer.drawOutputs(result.segMap); return new Promise((resolve, reject) => { let predictions = renderer._argmaxClippedSegMap(result.segMap); getBasedata(gtDic[imageSource.name]).then(function(data) { let acc = doCompare(predictions, data); console.log(imageSource.name, acc); resolve(acc); }); }); } // register backends if (nnNative) { webml.setAttribute('class', 'dropdown-item'); webml.onclick = function (e) { removeAlertElement(); checkPreferParam(); changeBackend('WebML'); }; } if (nnPolyfill.supportWebGL) { webgl.setAttribute('class', 'dropdown-item'); webgl.onclick = function (e) { removeAlertElement(); changeBackend('WebGL'); }; } if (nnPolyfill.supportWasm) { wasm.setAttribute('class', 'dropdown-item'); wasm.onclick = function (e) { removeAlertElement(); changeBackend('WASM'); }; } if (currentBackend === '') { if (nnNative) { currentBackend = 'WebML'; } else { currentBackend = 'WebGL'; } } function setCamResolution(resolution, currentBackend, currentPrefer) { return navigator.mediaDevices.getUserMedia({ audio: false, video: { facingMode: 'user' } }).then((stream) => { videoElement.srcObject = stream; return new Promise((resolve) => { // video cannot be uploaded to texture until being loaded videoElement.onloadeddata = resolve; }); }).catch((error) => { //console.log('getUserMedia error: ' + error.name, error); video.oncanplaythrough = function() { if (streaming) return; utils.init(currentBackend, currentPrefer).then(() => { updateBackend(); updateModel(); updatePrefer(); streaming = true; startPredict(); }); }; video.src = "";//TODO }); } // register models for (let model of availableModels) { let dropdownBtn = $('<button class="dropdown-item d-flex"/>') .append( $('<div class="model-link"/>') .text(model.modelName) .click(_ => changeModel(model)) ).append( $('<div class="netron-link ml-auto pl-2">') .text('▶') .click(_ => { let modelUrl = new URL(model.modelFile, window.location.href).href; window.open(`https://lutzroeder.github.io/netron/?url=${modelUrl}`); }) ); $('.available-models').append(dropdownBtn); if (!currentModel) { utils.changeModelParam(model); currentModel = model.modelName; } } function getMousePos(canvas, evt) { let rect = canvas.getBoundingClientRect(); return { x: Math.ceil(evt.clientX - rect.left), y: Math.ceil(evt.clientY - rect.top) }; } outputCanvas.addEventListener('mousemove', (e) => { hoverPos = getMousePos(outputCanvas, e); renderer.highlightHoverLabel(hoverPos); }); outputCanvas.addEventListener('mouseleave', (e) => { hoverPos = null; renderer.highlightHoverLabel(hoverPos); }); // register prefers if (currentBackend === 'WebML') { $('.prefer').css("display","inline"); let sustained = $('<button class="dropdown-item"/>') .text('SUSTAINED_SPEED') .click(_ => changePrefer('sustained')); $('.preference').append(sustained); if (currentOS === 'Android') { let fast = $('<button class="dropdown-item"/>') .text('FAST_SINGLE_ANSWER') .click(_ => changePrefer('fast')); $('.preference').append(fast); let low = $('<button class="dropdown-item"/>') .text('LOW_POWER') .click(_ => changePrefer('low')); $('.preference').append(low); } else if (currentOS === 'Windows' || currentOS === 'Linux') { let fast = $('<button class="dropdown-item" disabled />') .text('FAST_SINGLE_ANSWER') .click(_ => changePrefer('fast')); $('.preference').append(fast); let low = $('<button class="dropdown-item" disabled />') .text('LOW_POWER') .click(_ => changePrefer('low')); $('.preference').append(low); } else if (currentOS === 'Mac OS') { let fast = $('<button class="dropdown-item"/>') .text('FAST_SINGLE_ANSWER') .click(_ => changePrefer('fast')); $('.preference').append(fast); let low = $('<button class="dropdown-item" disabled />') .text('LOW_POWER') .click(_ => changePrefer('low')); $('.preference').append(low); } if (!currentPrefer) { currentPrefer = "sustained"; } } selectBackgroundButton.addEventListener('change', (e) => { let files = e.target.files; if (files.length > 0) { let img = new Image(); img.onload = function () { renderer.backgroundImageSource = img; }; img.src = URL.createObjectURL(files[0]); } }, false); clearBackgroundButton.addEventListener('click', (e) => { renderer.backgroundImageSource = null; }, false); async function loadImage(file, gtDic, width=513, height=513) { let image = new Image(width, height); return new Promise((resolve, reject) => { image.src = URL.createObjectURL(file); image.name = file.name; image.crossOrigin = ''; image.onload = () => { getAccuracy(image, gtDic).then(function(value) { resolve(value); }); }; }); } async function loadImages(files, gtDic) { let accArray = new Array(files.length); for (let i=0; i<files.length; i++) { await loadImage(files[i], gtDic).then(function(value) { accArray[i] = value; }); } let score = accArray.reduce(getSum)/accArray.length; console.log("Average Accuracy:", score); let scoreE = document.getElementById('avgAccuracy'); scoreE.innerHTML = `average accuracy: <em style="color:green;font-weight:bloder">${(score*100).toFixed(2)}</em>%`; } function getSum(total, num) { return total + num; } // image or camera if (!camera) { inputGTElement.addEventListener('change', (e) => { let files = e.target.files; if (this.imgGTDic !== undefined) { this.imgGTDic.length = 0; } this.imgGTDic = new Array(); for (let i=0; i<files.length; i++){ this.imgGTDic[files[i].name] = URL.createObjectURL(files[i]); } }, false); inputElement.addEventListener('change', (e) => { imageElement.src = null; let files = e.target.files; loadImages(files, this.imgGTDic); }, false); let imageWrapper = document.getElementsByClassName('image-wrapper')[0]; imageWrapper.ondragover = (e) => { e.preventDefault(); }; imageWrapper.ondragenter = (e) => { e.preventDefault(); $('.image-wrapper').addClass('show'); }; imageWrapper.ondragleave = (e) => { e.preventDefault(); $('.image-wrapper').removeClass('show'); }; imageWrapper.ondrop = (e) => { e.preventDefault(); $('.image-wrapper').removeClass('show'); let files = e.dataTransfer.files; if (files.length > 0 && files[0].type.split('/')[0] === 'image') { imageElement.src = URL.createObjectURL(files[0]); } }; utils.init(currentBackend, currentPrefer).then(() => { updateBackend(); updateModel(); updatePrefer(); predictAndDraw(imageElement); buttonEelement.setAttribute('class', 'btn btn-primary'); buttonGTEelement.setAttribute('class', 'btn btn-primary'); inputElement.removeAttribute('disabled'); inputGTElement.removeAttribute('disabled'); }).catch((e) => { console.warn(`Failed to init ${utils.model._backend}, try to use WASM`); console.error(e); showAlert(utils.model._backend); changeBackend('WASM'); }); } else { stats = new Stats(); stats.dom.style.cssText = 'position:fixed;top:60px;left:10px;cursor:pointer;opacity:0.9;z-index:10000'; stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom document.body.appendChild(stats.dom); let res = utils.getFittedResolution(4 / 3); setCamResolution(res, currentBackend, currentPrefer).then(() => { utils.init(currentBackend, currentPrefer).then(() => { updateBackend(); updateModel(); updatePrefer(); streaming = true; startPredict(); }).catch((e) => { console.warn(`Failed to init ${utils.model._backend}, try to use WASM`); console.error(e); showAlert(utils.model._backend); changeBackend('WASM'); }); }) } function startPredict() { if (streaming) { stats.begin(); predictAndDraw(videoElement).then(_ => { stats.end(); setTimeout(startPredict, 0); }); } } }
/* eslint-disable */ /** * @file autorun * @author yucong02 */ import { invokedWithArgs } from '../utils/index' import autorun from './core' const keyMap = { initKey: 'componentWillMount', updateKey: 'componentWillReceiveProps', exitKey: 'componentWillUnmount' } export default (...args) => { if (invokedWithArgs(args)) { console.warn('`autorun` 不需要传参') return autorun.bind(null, null) } else { return autorun(keyMap, ...args) } }
/*********************************************************************** * app-src/js/yopcontext.js * YeAPF 0.8.58-39 built on 2017-06-12 17:18 (-3 DST) * Copyright (C) 2004-2017 Esteban Daniel Dortta - dortta@yahoo.com * 2017-06-12 15:27:01 (-3 DST) * First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com * * This is a set of function that helps to recognize operational context **********************************************************************/ //# sourceURL=app-src/js/yopcontext.js function getInternetExplorerVersion() { /* http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx * Returns the version of Internet Explorer or a -1 * (indicating the use of another browser). */ var rv = -1; // Return value assumes failure. if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat( RegExp.$1 ); } return rv; } function isInternetExplorer() { return (getInternetExplorerVersion() >= 0); }; function getAndroidVersion(ua) { ua = (ua || navigator.userAgent).toLowerCase(); var match = ua.match(/android\s([0-9\.]*)/); return match ? match[1] : false; }; function isOnMobile() { var ret=false; if (typeof mosync != 'undefined') { ret = mosync.isAndroid || mosync.isIOS || mosync.isWindowsPhone; } else ret=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); return ret; };
NDSearch.OnPrefixDataLoaded("war",["Class","Property"],[["WarningFactor",,[["SCSSdkClient.Object.SCSTelemetry.Truck.Constants",,,,0,"File:Object/SCSTelemetry.Truck.Constants.cs:SCSSdkClient.Object.SCSTelemetry.Truck.Constants.WarningFactor","CSharpClass:SCSSdkClient.Object.SCSTelemetry.Truck.Constants.WarningFactor"]]],["WarningFactorValues",,[["SCSSdkClient.Object.SCSTelemetry.Truck.Constants",,,,1,"File:Object/SCSTelemetry.Truck.Constants.cs:SCSSdkClient.Object.SCSTelemetry.Truck.Constants.WarningFactorValues","CSharpClass:SCSSdkClient.Object.SCSTelemetry.Truck.Constants:WarningFactorValues"]]],["Warnings",,[["SCSSdkClient.Object.SCSTelemetry.Truck.Current.Dashboard",,,,0,"File:Object/SCSTelemetry.Truck.Current.cs:SCSSdkClient.Object.SCSTelemetry.Truck.Current.Dashboard.Warnings","CSharpClass:SCSSdkClient.Object.SCSTelemetry.Truck.Current.Dashboard.Warnings"]]],["WarningValues",,[["SCSSdkClient.Object.SCSTelemetry.Truck.Current.Dashboard",,,,1,"File:Object/SCSTelemetry.Truck.Current.cs:SCSSdkClient.Object.SCSTelemetry.Truck.Current.Dashboard.WarningValues","CSharpClass:SCSSdkClient.Object.SCSTelemetry.Truck.Current.Dashboard:WarningValues"]]]]);
'use strict' const src = '../../../../../../src' const Test = require('tapes')(require('tape')) const Sinon = require('sinon') const DnsServer = require(`${src}/services/query/dns/server`) const TcpServer = require(`${src}/services/query/dns/server/tcp`) const UdpServer = require(`${src}/services/query/dns/server/udp`) Test('DnsServer', dnsServerTest => { let sandbox dnsServerTest.beforeEach(t => { sandbox = Sinon.createSandbox() sandbox.stub(TcpServer, 'createServer') sandbox.stub(UdpServer, 'createServer') t.end() }) dnsServerTest.afterEach(t => { sandbox.restore() t.end() }) dnsServerTest.test('createServer should', createServerTest => { createServerTest.test('create default server', test => { let opts = {} DnsServer.createServer(opts) test.ok(UdpServer.createServer.calledOnce) test.ok(UdpServer.createServer.calledWith(opts)) test.end() }) createServerTest.end() }) dnsServerTest.test('createTcpServer should', createTcpServerTest => { createTcpServerTest.test('create TCP server', test => { let opts = {} DnsServer.createTcpServer(opts) test.ok(TcpServer.createServer.calledOnce) test.ok(TcpServer.createServer.calledWith(opts)) test.end() }) createTcpServerTest.end() }) dnsServerTest.test('createUdpServer should', createUdpServerTest => { createUdpServerTest.test('create UDP server', test => { let opts = {} DnsServer.createUdpServer(opts) test.ok(UdpServer.createServer.calledOnce) test.ok(UdpServer.createServer.calledWith(opts)) test.end() }) createUdpServerTest.end() }) dnsServerTest.end() })
const jwt = require('jsonwebtoken'); var ObjectId = require('mongodb').ObjectID; module.exports = (req, res, next) => { const token = req.headers['x-access-token'] || req.body.token || req.query.token if(token){ jwt.verify(token, req.app.get('api_secret_key'), (err, decoded) => { if (err){ res.json({ status: false, message: 'Failed to authenticate token.' }) } else { decoded._id = ObjectId(decoded._id); req.session = decoded; next(); } }); }else{ res.json({ status: false, message: 'No token provided.' }) } };
const RESET = document.getElementById('reset'); const START = document.getElementById('start'); const STOP = document.getElementById('stop'); const minutesViewer = document.getElementById('minutes'); const milisecondsViewer = document.getElementById('miliseconds'); const secondsViewer = document.getElementById('seconds'); let stop = false; let stopCounter = 0; let miliseconds = 0; let seconds = 0; let minutes = 0; let clicked = false; function startChronometer() { RESET.setAttribute('onclick', 'reset()'); STOP.setAttribute('onclick', 'stopChronometer()'); if(clicked == true) { START.removeAttribute('onclick'); } if(stop == false) { miliseconds += 1; milisecondsViewer.innerHTML = '0' + miliseconds.toString(); if(miliseconds > 9 ){ milisecondsViewer.innerHTML = miliseconds.toString(); if(miliseconds > 98) { milisecondsViewer.innerHTML = miliseconds.toString(); seconds += 1; miliseconds = 0; } } secondsViewer.innerHTML = '0' + seconds.toString() if(seconds > 9) { secondsViewer.innerHTML = seconds.toString(); } if(seconds > 59) { seconds = 0; minutes += 1; minutesViewer.innerHTML = '0' + minutes.toString(); if(minutes > 9) { minutesViewer.innerHTML = minutes.toString(); } } setTimeout(startChronometer, 10 * 1); } clicked = true; stop = false; stopCounter = 1; } function stopChronometer() { stopCounter = 1; clicked = false; START.setAttribute('onclick', 'startChronometer()'); if(stopCounter == 1){ stop = true; } } function reset() { clicked = false; START.setAttribute('onclick', 'startChronometer()'); miliseconds = 0; seconds = 0; minutes = 0; stop = true; milisecondsViewer.innerHTML = '0' + miliseconds; secondsViewer.innerHTML = '0' + seconds; minutesViewer.innerHTML = '0' + minutes; }
export const FETCHING_BOOKS_STARTED = 'FETCHING_BOOKS_STARTED'; export const FETCHING_BOOKS_COMPLETED = 'FETCHING_BOOKS_COMPLETED'; export const FETCHING_BOOKS_FAILED = 'FETCHING_BOOKS_FAILED'; export const LOAN_A_BOOK_STARTED = 'LOAN_A_BOOK_STARTED'; export const LOAN_A_BOOK_COMPLETED= 'LOAN_A_BOOK_COMPLETED'; export const LOAN_A_BOOK_FAILED = 'LOAN_A_BOOK_FAILED'; export const RETURN_A_BOOK_STARTED = 'RETURN_A_BOOK_STARTED'; export const RETURN_A_BOOK_COMPLETED = 'RETURN_A_BOOK_COMPLETED'; export const RETURN_A_BOOK_FAILED = 'RETURN_A_BOOK_FAILED'; export const FETCHING_LOAN_COLLECTION_STARTED = 'FETCHING_LOAN_COLLECTION_STARTED'; export const FETCHING_LOAN_COLLECTION_COMPLETED = 'FETCHING_LOAN_COLLECTION_COMPLETED'; export const FECTHING_LOAN_COLLECTION_FAILED = 'FECTHING_LOAN_COLLECTION_FAILED';
import autodux from 'autodux'; import cuid from 'cuid'; import { Scoring } from '../../../config/config'; export const { reducer, slice, actions: { addQuestion, removeQuestion, updateQuestion, setQuestions, }, selectors: { getQuestions, getScore, isLoaded, } } = autodux({ slice: 'questions', initial: { loaded: false, questions: [], }, actions: { addQuestion: { create: payload => ({ id: cuid(), timestamp: Date.now(), ...payload, }), reducer: (state, payload) => ({ ...state, questions: state.questions.concat([payload]), }) }, removeQuestion: (state, payload) => ({ ...state, questions: state.questions.filter(question => question.id !== payload), }), updateQuestion: (state, payload) => ({ ...state, questions: state.questions.map(question => question.id === payload.id ? { ...question, ...payload.fields } : question), }), setQuestions: (state, payload) => ({ ...state, loaded: true, questions: payload, }), }, selectors: { getScore: state => state.questions.reduce((score, question) => score + Scoring[question.status] , 0), isLoaded: state => state.loaded, } });
import React from 'react' import Layout from '../components/layout' const ServicesPage = () => { return ( <Layout><div> <h1>Services</h1> </div></Layout> ) } export default ServicesPage;
import styles from './template.css'; import template from './template'; import AoflElement from '@aofl/web-components/aofl-element'; /** * @summary IconRoundAirlineSeatFlatElement * @class IconRoundAirlineSeatFlatElement * @extends {AoflElement} */ class IconRoundAirlineSeatFlatElement extends AoflElement { /** * Creates an instance of IconRoundAirlineSeatFlatElement. */ constructor() { super(); } /** * @readonly */ static get is() { return 'icon-round-airline-seat-flat'; } /** * * @return {Object} */ render() { return super.render(template, [styles]); } } window.customElements.define(IconRoundAirlineSeatFlatElement.is, IconRoundAirlineSeatFlatElement); export default IconRoundAirlineSeatFlatElement;
/// <reference path="../typings/jquery/jquery.d.ts"/> function fetch() { return $.ajax({ url: '/scheduler.json', method: 'POST' }); } exports.fetch = fetch;
const app = require('./src/app'); const server = require('http').Server(app); const io = require('./src/io'); const PORT = 8000; io.listen(server); server.listen(PORT, () => console.log('server started on port:', PORT));
[{"Owner":"oschakravarthi","Date":"2018-11-19T08:06:50Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\tHi_co_ I want to highlight walls and floors in my model so that the separation of walls and floors will be very realistic. So_co_ I am using HighlightLayer for this. \n_lt_/p_gt_\n\n_lt_p_gt_\n\tThe problem I am facing is_co_ in my model_co_ all the four walls of my room are defined as a single mesh. So_co_ the joints of two walls are not highlighted. \n_lt_/p_gt_\n\n_lt_p_gt_\n\t \n_lt_/p_gt_\n\n_lt_p_gt_\n\tWhat I need is_co_ the edges should be highlighted if the angle between these edges is 90 degrees.  \n_lt_/p_gt_\n\n_lt_p_gt_\n\t \n_lt_/p_gt_\n\n_lt_p_gt_\n\tIt looks like_co_  mesh.enableEdgesRendering is the solution for this problem. So what is the argument I need to supply for epsilon? I could not understand this concept clearly. how to convert my 90 degrees to epsilon?\n_lt_/p_gt_\n\n_lt_p_gt_\n\tWhat other settings I need to set to achieve highlight effect?\n_lt_/p_gt_\n\n_lt_p_gt_\n\t \n_lt_/p_gt_\n\n_lt_p_gt_\n\tThanks in advance\n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Sebavan","Date":"2018-11-19T10:26:52Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\tepsilon is the value compared against the dot product between vectors of both faces -&gt_sm_ cosine of the angle. \n_lt_/p_gt_\n\n_lt_p_gt_\n\tThe default value should work with floor and walls so you do not even need to set it.\n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Wingnut","Date":"2018-11-19T10:53:53Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\tHi guys!  Also_co_ you might wish perform_dd_  _lt_strong_gt_yourmesh.convertToFlatShadedMesh()_sm__lt_/strong_gt_\n_lt_/p_gt_\n\n_lt_p_gt_\n\tThen_co_ play-around with a few directional lights.  You might see different coloring/lighting on walls... enough for user eyes to _qt_feel_qt_ wall delineation/separation.\n_lt_/p_gt_\n\n_lt_p_gt_\n\t._lt_em_gt_convertToFlatShadedMesh()_lt_/em_gt_ tends to add quite a few extra vertices to your mesh_co_ but the wall-shading goodness... might be worth it.\n_lt_/p_gt_\n\n_lt_p_gt_\n\tRemember... after the convert... play with lighting angles.  Use the handy directionLight/spotlight ._lt_em_gt_setDirectionToTarget_lt_/em_gt_(anytarget.position)... for help aiming directional lights.\n_lt_/p_gt_\n\n_lt_p_gt_\n\tThe actual .position of directional lights... is not important_co_ UNLESS you want to cast shadows with them.  In that case_co_ the light_t_s .position is used in creating the shadowMap_co_ and so_co_ it_t_s very important_co_ then.  (at least I THINK that_t_s how it all works).  _lt_span_gt__lt_img alt_eq__qt__dd_)_qt_ data-emoticon_eq__qt__qt_ height_eq__qt_20_qt_ src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_smile.png_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/smile@2x.png 2x_qt_ title_eq__qt__dd_)_qt_ width_eq__qt_20_qt_ /_gt__lt_/span_gt_\n_lt_/p_gt_\n\n_lt_p_gt_\n\t_lt_span_gt_Also_co_ I have seen folks use a linesMesh... to simply draw lines where walls/floors intersect.  Might work_co_ might not._lt_/span_gt_\n_lt_/p_gt_\n\n_lt_p_gt_\n\t_lt_span_gt_This is a common problem.  Lack of _qt_definition_qt_ for smooth-shaded mesh.  _lt_/span_gt_\n_lt_/p_gt_\n\n_lt_p_gt_\n\t_lt_span_gt_Keep us posted and/or mark as solved when satisfied.  Meantime... stay tuned... more comments coming_co_ likely. _lt_/span_gt_\n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"oschakravarthi","Date":"2018-11-19T13:57:06Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_blockquote class_eq__qt_ipsQuote_qt_ data-ipsquote_eq__qt__qt_ data-ipsquote-contentapp_eq__qt_forums_qt_ data-ipsquote-contentclass_eq__qt_forums_Topic_qt_ data-ipsquote-contentcommentid_eq__qt_235379_qt_ data-ipsquote-contentid_eq__qt_41368_qt_ data-ipsquote-contenttype_eq__qt_forums_qt_ data-ipsquote-timestamp_eq__qt_1542624833_qt_ data-ipsquote-userid_eq__qt_5733_qt_ data-ipsquote-username_eq__qt_Wingnut_qt__gt_\n\t_lt_div class_eq__qt_ipsQuote_citation_qt__gt_\n\t\t3 hours ago_co_ Wingnut said_dd_\n\t_lt_/div_gt_\n\n\t_lt_div class_eq__qt_ipsQuote_contents_qt__gt_\n\t\t_lt_p_gt_\n\t\t\tHi guys!  Also_co_ you might wish perform_dd_  _lt_strong_gt_yourmesh.convertToFlatShadedMesh()_sm__lt_/strong_gt_\n\t\t_lt_/p_gt_\n\n\t\t_lt_p_gt_\n\t\t\tThen_co_ play-around with a few directional lights.  You might see different coloring/lighting on walls... enough for user eyes to _qt_feel_qt_ wall delineation/separation.\n\t\t_lt_/p_gt_\n\n\t\t_lt_p_gt_\n\t\t\t._lt_em_gt_convertToFlatShadedMesh()_lt_/em_gt_ tends to add quite a few extra vertices to your mesh_co_ but the wall-shading goodness... might be worth it.\n\t\t_lt_/p_gt_\n\n\t\t_lt_p_gt_\n\t\t\tRemember... after the convert... play with lighting angles.  Use the handy directionLight/spotlight ._lt_em_gt_setDirectionToTarget_lt_/em_gt_(anytarget.position)... for help aiming directional lights.\n\t\t_lt_/p_gt_\n\n\t\t_lt_p_gt_\n\t\t\tThe actual .position of directional lights... is not important_co_ UNLESS you want to cast shadows with them.  In that case_co_ the light_t_s .position is used in creating the shadowMap_co_ and so_co_ it_t_s very important_co_ then.  (at least I THINK that_t_s how it all works).  _lt_span_gt__lt_img alt_eq__qt__dd_)_qt_ data-emoticon_eq__qt__qt_ height_eq__qt_20_qt_ src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_smile.png_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/smile@2x.png 2x_qt_ title_eq__qt__dd_)_qt_ width_eq__qt_20_qt_ /_gt__lt_/span_gt_\n\t\t_lt_/p_gt_\n\n\t\t_lt_p_gt_\n\t\t\t_lt_span_gt_Also_co_ I have seen folks use a linesMesh... to simply draw lines where walls/floors intersect.  Might work_co_ might not._lt_/span_gt_\n\t\t_lt_/p_gt_\n\n\t\t_lt_p_gt_\n\t\t\t_lt_span_gt_This is a common problem.  Lack of _qt_definition_qt_ for smooth-shaded mesh.  _lt_/span_gt_\n\t\t_lt_/p_gt_\n\n\t\t_lt_p_gt_\n\t\t\t_lt_span_gt_Keep us posted and/or mark as solved when satisfied.  Meantime... stay tuned... more comments coming_co_ likely. _lt_/span_gt_\n\t\t_lt_/p_gt_\n\t_lt_/div_gt_\n_lt_/blockquote_gt_\n\n_lt_p_gt_\n\tHi_co_ Thanks for the suggestion. Unfortunately_co_ I cannot use _lt_strong_gt_convertToFlatShadedMesh _lt_/strong_gt_because_co_ all my textures are emisive textures and all those meshes are excluded from existing lights. When I use _lt_strong_gt_convertToFlatShadedMesh _lt_/strong_gt__co_ it appears like this (screenshot attached)\n_lt_/p_gt_\n\n_lt_p_gt__lt_a href_eq__qt_http_dd_//www.html5gamedevs.com/uploads/monthly_2018_11/Untitled.png.30fdd0492ef17919614fbf4d385fa80c.png_qt_ class_eq__qt_ipsAttachLink ipsAttachLink_image_qt__gt__lt_img data-fileid_eq__qt_21079_qt_ src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/monthly_2018_11/Untitled.png.30fdd0492ef17919614fbf4d385fa80c.png_qt_ class_eq__qt_ipsImage ipsImage_thumbnailed_qt_ alt_eq__qt_Untitled.png_qt__gt__lt_/a_gt__lt_/p_gt_\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"oschakravarthi","Date":"2018-11-20T17:08:04Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_blockquote class_eq__qt_ipsQuote_qt_ data-ipsquote_eq__qt__qt_ data-ipsquote-contentapp_eq__qt_forums_qt_ data-ipsquote-contentclass_eq__qt_forums_Topic_qt_ data-ipsquote-contentcommentid_eq__qt_235373_qt_ data-ipsquote-contentid_eq__qt_41368_qt_ data-ipsquote-contenttype_eq__qt_forums_qt_ data-ipsquote-timestamp_eq__qt_1542623212_qt_ data-ipsquote-userid_eq__qt_20193_qt_ data-ipsquote-username_eq__qt_Sebavan_qt__gt_\n\t_lt_div class_eq__qt_ipsQuote_citation_qt__gt_\n\t\tOn 11/19/2018 at 3_dd_56 PM_co_ Sebavan said_dd_\n\t_lt_/div_gt_\n\n\t_lt_div class_eq__qt_ipsQuote_contents_qt__gt_\n\t\t_lt_p_gt_\n\t\t\tepsilon _lt_span_gt__lt_/span_gt_is the value compared against the dot product between vectors of both faces -&gt_sm_ cosine of the angle. \n\t\t_lt_/p_gt_\n\n\t\t_lt_p_gt_\n\t\t\tThe default value should work with floor and walls so you do not even need to set it.\n\t\t_lt_/p_gt_\n\t_lt_/div_gt_\n_lt_/blockquote_gt_\n\n_lt_p_gt_\n\tThank you _lt_a contenteditable_eq__qt_false_qt_ data-ipshover_eq__qt__qt_ data-ipshover-target_eq__qt_http_dd_//www.html5gamedevs.com/profile/20193-sebavan/?do_eq_hovercard_qt_ data-mentionid_eq__qt_20193_qt_ href_eq__qt_http_dd_//www.html5gamedevs.com/profile/20193-sebavan/_qt_ rel_eq__qt__qt__gt_@Sebavan_lt_/a_gt_\n_lt_/p_gt_\n\n_lt_p_gt_\n\twhat should be the value of epsilon if the angle between two edges is 90 degrees?\n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Sebavan","Date":"2018-11-20T18:01:35Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\tThe default one will work_co_ so _lt_span style_eq__qt_background-color_dd_#ffffff_sm_color_dd_#353c41_sm_font-size_dd_14px_sm__qt__gt_mesh_lt_/span_gt__lt_span style_eq__qt_background-color_dd_#ffffff_sm_color_dd_#353c41_sm_font-size_dd_14px_sm__qt__gt__lt_/span_gt__lt_span style_eq__qt_background-color_dd_#ffffff_sm_color_dd_#353c41_sm_font-size_dd_14px_sm__qt__gt_.enableEdgesRenderi_lt_/span_gt__lt_span style_eq__qt_background-color_dd_#ffffff_sm_color_dd_#353c41_sm_font-size_dd_14px_sm__qt__gt__lt_/span_gt__lt_span style_eq__qt_background-color_dd_#ffffff_sm_color_dd_#353c41_sm_font-size_dd_14px_sm__qt__gt_ng_lt_/span_gt__lt_span style_eq__qt_background-color_dd_#ffffff_sm_color_dd_#353c41_sm_font-size_dd_14px_sm__qt__gt__lt_/span_gt_() will be sufficient.\n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"}]
const _ = require('lodash'); const collectionData = require('./collectionData.json'); const scrapeWeaponPage = require('./webScraper').scrapeWeaponPage; /** * Unbox a CS: GO collection. * @param {string} collectionName - name of collection to unbox * @returns {Promise<import('../typedefs/container').ContainerWeapon>} */ async function unboxCollection(collectionName) { const data = collectionData.collections[collectionName]; const collectionWeaponData = data.weapons; const tier = _collectionTier(collectionWeaponData); console.log(`Unboxing: ${data.name}`); // Randomised weapon data const colour = _weaponColour(tier, collectionName); const souvenirStatus = _souvenir(); const weaponWearStatus = _weaponWear(); // Static weapon data const weaponData = _weapon(collectionWeaponData[colour]); const weaponDetails = await scrapeWeaponPage(weaponData.url, weaponWearStatus, { souvenir: souvenirStatus, }); const collectionWeapon = { ...weaponData, ...weaponDetails, colour: colour, wear: weaponWearStatus, souvenir: souvenirStatus, containerName: data.name, }; return collectionWeapon; } /** * Determine if the collection is 6, 5, 4 or 3 tier * @param {Object} weaponData - weapon data for collection * @returns {string} */ function _collectionTier(weaponData) { if (weaponData.red.length) return 'sixTier'; if (weaponData.pink.length) return 'fiveTier'; if (weaponData.purple.length) return 'fourTier'; else return 'threeTier'; } /** * Generate a weapon colour based on the grade odds. * @param {string} tier - collection tier * @param {string} collectionName - name of collection (for edge cases) * @returns {string} */ function _weaponColour(tier, collectionName) { let colour; const randomNumber = Math.random(); // Edge cases // Single tier - purple if (collectionName === 'blacksite') { return 'purple'; } // Three tier - light blue, blue, purple else if (['dust', 'cache'].includes(collectionName)) { const lightBlueThresholdEdge = collectionData.gradeOdds.threeTier.white; const blueThresholdEdge = lightBlueThresholdEdge + collectionData.gradeOdds.threeTier.lightBlue; if (randomNumber <= lightBlueThresholdEdge) colour = 'lightBlue'; else if (randomNumber <= blueThresholdEdge) colour = 'blue'; else colour = 'purple'; return colour; } // Four tier - blue, purple, pink, red else if (['train2021'].includes(collectionName)) { const blueThresholdEdge = collectionData.gradeOdds.fourTier.white; const purpleThresholdEdge = blueThresholdEdge + collectionData.gradeOdds.fourTier.lightBlue; const pinkThresholdEdge = purpleThresholdEdge + collectionData.gradeOdds.fourTier.blue; if (randomNumber <= blueThresholdEdge) colour = 'blue'; else if (randomNumber <= purpleThresholdEdge) colour = 'purple'; else if (randomNumber <= pinkThresholdEdge) colour = 'pink'; else colour = 'red'; return colour; } // Standard tiers switch (tier) { // 6 tier case 'sixTier': const whiteThreshold6 = collectionData.gradeOdds.sixTier.white; const lightBlueThreshold6 = whiteThreshold6 + collectionData.gradeOdds.sixTier.lightBlue; const blueThreshold6 = lightBlueThreshold6 + collectionData.gradeOdds.sixTier.blue; const purpleThreshold6 = blueThreshold6 + collectionData.gradeOdds.sixTier.purple; const pinkThreshold6 = purpleThreshold6 + collectionData.gradeOdds.sixTier.pink; if (randomNumber <= whiteThreshold6) colour = 'white'; else if (randomNumber <= lightBlueThreshold6) colour = 'lightBlue'; else if (randomNumber <= blueThreshold6) colour = 'blue'; else if (randomNumber <= purpleThreshold6) colour = 'purple'; else if (randomNumber <= pinkThreshold6) colour = 'pink'; else colour = 'red'; break; // 5 tier case 'fiveTier': const whiteThreshold5 = collectionData.gradeOdds.fiveTier.white; const lightBlueThreshold5 = whiteThreshold5 + collectionData.gradeOdds.fiveTier.lightBlue; const blueThreshold5 = lightBlueThreshold5 + collectionData.gradeOdds.fiveTier.blue; const purpleThreshold5 = blueThreshold5 + collectionData.gradeOdds.fiveTier.purple; if (randomNumber <= whiteThreshold5) colour = 'white'; else if (randomNumber <= lightBlueThreshold5) colour = 'lightBlue'; else if (randomNumber <= blueThreshold5) colour = 'blue'; else if (randomNumber <= purpleThreshold5) colour = 'purple'; else colour = 'pink'; break; // 4 tier case 'fourTier': const whiteThreshold4 = collectionData.gradeOdds.fourTier.white; const lightBlueThreshold4 = whiteThreshold4 + collectionData.gradeOdds.fourTier.lightBlue; const blueThreshold4 = lightBlueThreshold4 + collectionData.gradeOdds.fourTier.blue; if (randomNumber <= whiteThreshold4) colour = 'white'; else if (randomNumber <= lightBlueThreshold4) colour = 'lightBlue'; else if (randomNumber <= blueThreshold4) colour = 'blue'; else colour = 'purple'; break; // 3 tier case 'threeTier': const whiteThreshold3 = collectionData.gradeOdds.threeTier.white; const lightBlueThreshold3 = whiteThreshold3 + collectionData.gradeOdds.threeTier.lightBlue; if (randomNumber <= whiteThreshold3) colour = 'white'; else if (randomNumber <= lightBlueThreshold3) colour = 'lightBlue'; else colour = 'blue'; break; } return colour; } /** * Pick a random weapon from the provided weapon list. * @param {import('../typedefs/container').WeaponData[]} possibleWeapons * @returns {import('../typedefs/container').WeaponData} */ function _weapon(possibleWeapons) { return _.sample(possibleWeapons); } /** * Generate a weapon wear based on the wear odds. * @returns {string} */ function _weaponWear() { const randomNumber = Math.random(); const wellWornThreshold = collectionData.wearOdds.wellWorn; const battleScarredThreshold = wellWornThreshold + collectionData.wearOdds.battleScarred; const fieldTestedThreshold = battleScarredThreshold + collectionData.wearOdds.fieldTested; const minimalWearThreshold = fieldTestedThreshold + collectionData.wearOdds.minimalWear; let wear = 'Factory New'; if (randomNumber <= wellWornThreshold) wear = 'Well-Worn'; else if (randomNumber <= battleScarredThreshold) wear = 'Battle-Scarred'; else if (randomNumber <= fieldTestedThreshold) wear = 'Field-Tested'; else if (randomNumber <= minimalWearThreshold) wear = 'Minimal Wear'; return wear; } /** * Generate a souvenir true or false flag based on the souvenir threshold. * @returns {boolean} */ function _souvenir() { return Math.random() <= collectionData.souvenirThreshold ? true : false; } module.exports = { unboxCollection };
const encrypt = require('./crypto') const axios = require('axios') const PacProxyAgent = require('pac-proxy-agent') const http = require('http') const https = require('https') const tunnel = require('tunnel') const { URLSearchParams, URL } = require('url') // request.debug = true // 开启可看到更详细信息 const chooseUserAgent = (ua = false) => { const userAgentList = { mobile: [ // iOS 13.5.1 14.0 beta with safari 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1', 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.', // iOS with qq micromsg 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML like Gecko) Mobile/14A456 QQ/6.5.7.408 V1_IPH_SQ_6.5.7_1_APP_A Pixel/750 Core/UIWebView NetType/4G Mem/103', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f27) NetType/WIFI Language/zh', // Android -> Huawei Xiaomi 'Mozilla/5.0 (Linux; Android 9; PCT-AL10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.64 HuaweiBrowser/10.0.3.311 Mobile Safari/537.36', 'Mozilla/5.0 (Linux; U; Android 9; zh-cn; Redmi Note 8 Build/PKQ1.190616.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/12.5.22', // Android + qq micromsg 'Mozilla/5.0 (Linux; Android 10; YAL-AL00 Build/HUAWEIYAL-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/78.0.3904.62 XWEB/2581 MMWEBSDK/200801 Mobile Safari/537.36 MMWEBID/3027 MicroMessenger/7.0.18.1740(0x27001235) Process/toolsmp WeChat/arm64 NetType/WIFI Language/zh_CN ABI/arm64', 'Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BKK-AL10 Build/HONORBKK-AL10) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/10.6 Mobile Safari/537.36', ], pc: [ // macOS 10.15.6 Firefox / Chrome / Safari 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:80.0) Gecko/20100101 Firefox/80.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.30 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Safari/605.1.15', // Windows 10 Firefox / Chrome / Edge 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.30 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/13.10586', // Linux 就算了 ], } let realUserAgentList = userAgentList[ua] || userAgentList.mobile.concat(userAgentList.pc) return ['mobile', 'pc', false].indexOf(ua) > -1 ? realUserAgentList[Math.floor(Math.random() * realUserAgentList.length)] : ua } const createRequest = (method, url, data, options) => { return new Promise((resolve, reject) => { let headers = { 'User-Agent': chooseUserAgent(options.ua) } if (method.toUpperCase() === 'POST') headers['Content-Type'] = 'application/x-www-form-urlencoded' if (url.includes('music.163.com')) headers['Referer'] = 'https://music.163.com' if (options.realIP) headers['X-Real-IP'] = options.realIP headers['X-Real-IP'] = '183.160.213.218' if (typeof options.cookie === 'object') headers['Cookie'] = Object.keys(options.cookie) .map( (key) => encodeURIComponent(key) + '=' + encodeURIComponent(options.cookie[key]), ) .join('; ') else if (options.cookie) headers['Cookie'] = options.cookie if (!headers['Cookie']) { headers['Cookie'] = options.token || '' } if (options.crypto === 'weapi') { let csrfToken = (headers['Cookie'] || '').match(/_csrf=([^(;|$)]+)/) data.csrf_token = csrfToken ? csrfToken[1] : '' data = encrypt.weapi(data) url = url.replace(/\w*api/, 'weapi') } else if (options.crypto === 'linuxapi') { data = encrypt.linuxapi({ method: method, url: url.replace(/\w*api/, 'api'), params: data, }) headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36' url = 'https://music.163.com/api/linux/forward' } else if (options.crypto === 'eapi') { const cookie = options.cookie || {} const csrfToken = cookie['__csrf'] || '' const header = { osver: cookie.osver, //系统版本 deviceId: cookie.deviceId, //encrypt.base64.encode(imei + '\t02:00:00:00:00:00\t5106025eb79a5247\t70ffbaac7') appver: cookie.appver || '8.7.01', // app版本 versioncode: cookie.versioncode || '140', //版本号 mobilename: cookie.mobilename, //设备model buildver: cookie.buildver || Date.now().toString().substr(0, 10), resolution: cookie.resolution || '1920x1080', //设备分辨率 __csrf: csrfToken, os: cookie.os || 'android', channel: cookie.channel, requestId: `${Date.now()}_${Math.floor(Math.random() * 1000) .toString() .padStart(4, '0')}`, } if (cookie.MUSIC_U) header['MUSIC_U'] = cookie.MUSIC_U if (cookie.MUSIC_A) header['MUSIC_A'] = cookie.MUSIC_A headers['Cookie'] = Object.keys(header) .map( (key) => encodeURIComponent(key) + '=' + encodeURIComponent(header[key]), ) .join('; ') data.header = header data = encrypt.eapi(options.url, data) url = url.replace(/\w*api/, 'eapi') } const answer = { status: 500, body: {}, cookie: [] } let settings = { method: method, url: url, headers: headers, data: new URLSearchParams(data).toString(), httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), } if (options.crypto === 'eapi') settings.encoding = null if (options.proxy) { if (options.proxy.indexOf('pac') > -1) { settings.httpAgent = new PacProxyAgent(options.proxy) settings.httpsAgent = new PacProxyAgent(options.proxy) } else { const purl = new URL(options.proxy) if (purl.hostname) { const agent = tunnel.httpsOverHttp({ proxy: { host: purl.hostname, port: purl.port || 80, }, }) settings.httpsAgent = agent settings.httpAgent = agent settings.proxy = false } else { console.error('代理配置无效,不使用代理') } } } else { settings.proxy = false } if (options.crypto === 'eapi') { settings = { ...settings, responseType: 'arraybuffer', } } axios(settings) .then((res) => { const body = res.data answer.cookie = (res.headers['set-cookie'] || []).map((x) => x.replace(/\s*Domain=[^(;|$)]+;*/, ''), ) try { if (options.crypto === 'eapi') { answer.body = JSON.parse(encrypt.decrypt(body).toString()) } else { answer.body = body } answer.status = answer.body.code || res.status if ( [201, 302, 400, 502, 800, 801, 802, 803].indexOf(answer.body.code) > -1 ) { // 特殊状态码 answer.status = 200 } } catch (e) { // console.log(e) try { answer.body = JSON.parse(body.toString()) } catch (err) { // console.log(err) // can't decrypt and can't parse directly answer.body = body } answer.status = res.status } answer.status = 100 < answer.status && answer.status < 600 ? answer.status : 400 if (answer.status === 200) resolve(answer) else reject(answer) }) .catch((err) => { answer.status = 502 answer.body = { code: 502, msg: err } reject(answer) }) }) } module.exports = createRequest
const paths = require('../paths'); const config = require(paths.config); function overwrite(param, callback) { if (param) { callback(param); } } class ScriptOptions { constructor(configs) { this.compilation = new CompilationOptions(configs.compilation); this.download = new DownloadOptions(configs.download); } } class CompilationOptions { constructor(configs) { this.icon = 'assets/app-icon.ico'; this.assets = []; this.pfxFile = ''; this.pfxPwd = ''; this.mainProcess = new MainProcessOptions(configs.mainProcess); this.rendererProcess = new RendererProcess(configs.rendererProcess); this.product = new ProductOptions(configs.product); overwrite(configs.icon, (value) => { this.icon = value; }); overwrite(configs.assets, (value) => { this.assets = value; }); overwrite(configs.pfxFile, (value) => { this.pfxFile = value; }); overwrite(configs.pfxPwd, (value) => { this.pfxPwd = value; }); const asarOptions = configs.asar; if (typeof asarOptions === 'boolean') { this.asar = asarOptions; } else { this.asar = new AsarOptions(configs.asar); } } } class AsarOptions { constructor(configs) { this.unpack = ''; this.unpackDir = ''; if (!configs) { return; } overwrite(configs.unpack, (value) => { this.unpack = value; }); overwrite(configs.unpackDir, (value) => { this.unpackDir = value; }); } } class ProductOptions { constructor(configs) { this.appId = ''; this.dirName = ''; this.arch = 'x64'; this.platform = 'win32'; this.publisher = ''; this.copyright = ''; this.privileges = ''; if (!configs) { return; } overwrite(configs.appId, (value) => { this.appId = value; }); overwrite(configs.dirName, (value) => { this.dirName = value; }); overwrite(configs.platform, (value) => { this.platform = value; }); overwrite(configs.arch, (value) => { this.arch = value; }); overwrite(configs.publisher, (value) => { this.publisher = value; }); overwrite(configs.copyright, (value) => { this.copyright = value; }); overwrite(configs.privileges, (value) => { this.privileges = value; }); } } class MainProcessOptions { constructor(configs) { this.main = 'src/main.ts'; this.preload = ''; this.tsConfig = 'tsconfig.json'; this.tslint = 'tslint.json'; this.externals = {}; if (!configs) { return; } overwrite(configs.main, (value) => { this.main = value; }); overwrite(configs.preload, (value) => { this.preload = value; }); overwrite(configs.tsConfig, (value) => { this.tsConfig = value; }); overwrite(configs.tslint, (value) => { this.tslint = value; }); overwrite(configs.externals, (value) => { this.externals = value; }); } } class RendererProcess { constructor(configs) { this.projects = 'renderer'; if (!configs) { return; } overwrite(configs.projects, (value) => { this.projects = value; }); } } class DownloadOptions { constructor(configs) { this.mirror = ''; if (!configs) { return; } overwrite(configs.mirror, (value) => { this.mirror = value; }); } } module.exports = new ScriptOptions(config);
/** * AskTags JS * * @author Zix <zix2002@gmail.com> * @version 2.0 , 2017-07-25 */ var Tags = { config : {} , init : function () { //重新设置菜单 if ( !empty( Param.uri.menu ) ) { Layout.setSidebarMenuActiveLink('set' , 'a[data-uri="'+ Param.uri.menu +'"]'); } //初始化ajax 提示框 loading.initAjax(); //初始化页面按钮 this.initBtn(); //初始化查询form this.initSearchForm(); //初始化数据表 this.initGrid(); } , //初始化查询form initSearchForm : function () { var $searchForm = $('#searchForm'); $searchForm.reloadForm(Param.query); //查询按钮 $('#searchBtn').on('click' , function (e) { e.preventDefault(); var $dataGrid = $('#dataGrid'); var param = $dataGrid.TableGrid('getParam'); param = $.extend({} , param , $('#searchForm').serializeObject() ); param.page = 1; $dataGrid.TableGrid('setParam' , param); $dataGrid.TableGrid('reload'); }); } , //显示 portlet setPortletShow : function ( type ) { var $tablePortlet = $('#tablePortlet') ; var $addEditPortlet = $('#addEditPortlet'); $tablePortlet.slideUp('fast'); if ( type == 'add' ) { if ( !$addEditPortlet.hasClass('blue') ) { $addEditPortlet.removeClass('green-meadow').addClass('blue'); } $addEditPortlet.find('.caption-subject').html('新增 ' + Param.pageTitle ); } else if ( type == 'edit' ) { if ( !$addEditPortlet.hasClass('green-meadow') ) { $addEditPortlet.removeClass('blue').addClass('green-meadow'); } $addEditPortlet.find('.caption-subject').html('编辑 ' + Param.pageTitle ); } //$('#data-table-portlet').slideUp('fast'); $addEditPortlet.show(); }, //关闭 portlet setPortletHide : function () { $('#tablePortlet').slideDown('fast') ; $('#addEditPortlet').slideUp('fast'); }, //初始化各种按钮 initBtn : function () { var self = this; //打开添加框 $('#addNewBtn').on('click' , function (e) { e.preventDefault(); self.setPortletShow('add'); var $form = $('#addEditForm'); $form.reloadForm( Param.defaultRow ); $form.attr('action' , Param.uri.insert ); }); //编辑按钮 $(document).on('click' , '.editBtn' , function (e) { e.preventDefault(); self.setPortletShow('edit'); var id = $(this).data('id'); var row = $('#dataGrid').TableGrid('getRow' , id); var $form = $('#addEditForm'); $form.reloadForm( row ); $form.attr('action' , Param.uri.update + row.id ); }); //删除一行 $(document).on('click' , '.destroyBtn' , function (e) { e.preventDefault(); var id = $(this).data('id'); self.delData( id ); }); $('#destroySelectBtn').on('click' , function (e) { e.preventDefault(); var ids = $('.checker:checked').serializeJSON().selectChecker; if ( empty( ids ) ) { tips.error('请选择要删除的记录'); return ; } self.delData( ids ); }); //提交添加编辑窗 $('#submitFormBtn').on('click' , function (e) { e.preventDefault(); var $form = $('#addEditForm'); if( $form.validForm() ) { var data = $form.serializeObject(); $.post( $form.attr('action') , data ) .fail( function(res){ tips.error( res.responseText ); }) .done( function( res ){ if ( res.code == 1001 ) { //需要登录 tips.error('请先登录'); } else if( res.code != 0 ){ tips.error( res.msg ); } else { tips.success( res.msg ); $('#dataGrid').TableGrid('reload'); self.setPortletHide(); } }); } }); //关闭添加编辑窗 $('#closePortletBtn').on('click' , function (e) { e.preventDefault(); self.setPortletHide(); }); } , delData : function ( ids ) { var self = this ; var data = { ids : ids }; sure.init('是否删除?' , function () { $.post( Param.uri.destroy , data ) .fail( function(res){ tips.error( res.responseText ); }) .done(function (res) { if ( res.code == 1001 ) { //需要登录 tips.error('请先登录'); } else if( res.code != 0 ){ tips.error( res.msg ); } else { tips.success( res.msg ); $('#dataGrid').TableGrid('reload'); } }); }); }, //初始化grid initGrid : function () { var self = this; var uri = Param.uri.this + '?' + $.param(Param.query); history.replaceState(Param.query , '' , uri); $('#dataGrid').TableGrid({ uri : Param.uri.read , selectAll : true , param : Param.query , rowStyle : function (row) { if ( row.status == 0 ) { return 'warning'; } } , loadSuccess : function ( rows , settings ) { var oldUri = window.location.href; var uri = Param.uri.this + '?' + $.param(settings.param); if ( oldUri == uri) { return false ; } var params = $.getUrlParams(window.location.href); history.pushState(params , '' , oldUri); history.replaceState(settings.param , '' , uri); } }); } }; //pop state 事件 window.onpopstate = function (event) { if ( event && event.state ) { $('#searchForm').reloadForm( event.state ); var $dataGrid = $('#dataGrid'); $dataGrid.TableGrid('setParam' , event.state); $dataGrid.TableGrid('reload'); } };
/*!-------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ (function(){ var e=["require","exports","vs/platform/instantiation/common/instantiation","vs/base/common/types","vs/nls!vs/code/node/cliProcessMain","path","vs/base/common/objects","vs/platform/log/common/log","vs/nls","vs/base/common/event","vs/base/common/strings","vs/base/common/lifecycle","vs/base/node/pfs","vs/platform/configuration/common/configuration","vs/platform/registry/common/platform","vs/platform/configuration/common/configurationRegistry","vs/base/common/platform","vs/platform/environment/common/environment","vs/platform/extensionManagement/common/extensionManagementUtil","vs/base/common/arrays","vs/platform/node/package","vs/base/common/async","vs/base/common/uri","vs/base/common/errors","fs","vs/base/common/paths","os","vs/platform/telemetry/common/telemetry","vs/platform/extensionManagement/common/extensionManagement","vs/platform/instantiation/common/serviceCollection","vs/base/common/network","vs/base/common/errorMessage","vs/platform/extensions/node/extensionValidator","vs/base/common/map","vs/base/node/request","vs/base/common/amd","vs/platform/node/product","vs/base/common/json","vs/platform/instantiation/common/descriptors","vs/base/node/extfs","vs/platform/configuration/common/configurationModels","vs/platform/request/node/request","vs/platform/extensionManagement/node/extensionManagementUtil","vs/base/common/uuid","vs/platform/node/zip","semver","vs/platform/extensions/common/extensions","vs/base/common/collections","vs/base/node/config","vs/platform/extensionManagement/node/extensionsManifestCache","vs/base/common/mime","vs/platform/instantiation/common/graph","vs/platform/download/common/download","vs/base/common/labels","vs/base/common/glob","vs/base/common/decorators","vs/base/common/assert","vs/platform/instantiation/common/instantiationService","vs/platform/request/node/requestService","vs/nls!vs/base/common/errorMessage","vs/platform/log/node/spdlogService","vs/base/node/paths","vs/base/common/date","vs/platform/environment/node/environmentService","vs/base/node/proxy","vs/nls!vs/platform/configuration/common/configurationRegistry","vs/nls!vs/platform/extensionManagement/common/extensionManagement","vs/nls!vs/platform/extensionManagement/node/extensionManagementService","vs/platform/jsonschemas/common/jsonContributionRegistry","vs/nls!vs/platform/extensionManagement/node/extensionManagementUtil","vs/nls!vs/platform/extensions/node/extensionValidator","vs/nls!vs/platform/node/zip","vs/platform/configuration/node/configuration","vs/platform/configuration/node/configurationService","vs/nls!vs/platform/request/node/request","vs/platform/state/common/state","vs/platform/state/node/stateService","vs/nls!vs/platform/telemetry/common/telemetryService","vs/platform/telemetry/common/telemetryService","vs/platform/telemetry/common/telemetryUtils","vs/platform/telemetry/node/appInsightsAppender","vs/platform/extensionManagement/node/extensionManagementService","vs/platform/telemetry/node/commonProperties","url","vs/platform/extensionManagement/common/extensionNls","vs/platform/extensionManagement/node/extensionLifecycle","vs/platform/extensionManagement/node/extensionGalleryService","yazl","yauzl","applicationinsights","crypto","zlib","child_process","vs/base/common/cancellation","vs/base/common/resources","vs/code/node/cliProcessMain"],t=function(t){ for(var n=[],r=0,i=t.length;r<i;r++)n[r]=e[t[r]];return n};define(e[56],t([0,1]),function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ok=function(e,t){if(!e||null===e)throw new Error(t?"Assertion failed ("+t+")":"Assertion Failed")}}),define(e[47],t([0,1]),function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.prototype.hasOwnProperty;t.values=function(e){var t=[];for(var r in e)n.call(e,r)&&t.push(e[r]);return t},t.size=function(e){var t=0;for(var r in e)n.call(e,r)&&(t+=1);return t},t.first=function(e){for(var t in e)if(n.call(e,t))return e[t]},t.forEach=function(e,t){var r=function(r){if(n.call(e,r)&&!1===t({key:r,value:e[r]},function(){delete e[r]}))return{value:void 0}};for(var i in e){var o=r(i);if("object"==typeof o)return o.value}},t.groupBy=function(e,t){for(var n=Object.create(null),r=0,i=e;r<i.length;r++){var o=i[r],s=t(o),a=n[s];a||(a=n[s]=[]),a.push(o)}return n},t.fromMap=function(e){var t=Object.create(null) ;return e&&e.forEach(function(e,n){t[n]=e}),t}}),define(e[55],t([0,1]),function(e,t){"use strict";function n(e){return function(t,n,r){var i=null,o=null;if("function"==typeof r.value?(i="value",o=r.value):"function"==typeof r.get&&(i="get",o=r.get),!o)throw new Error("not supported");r[i]=e(o,n)}}Object.defineProperty(t,"__esModule",{value:!0}),t.createDecorator=n,t.memoize=function(e,t,n){var r=null,i=null;if("function"==typeof n.value?(r="value",0!==(i=n.value).length&&console.warn("Memoize should only be used in functions with zero parameters")):"function"==typeof n.get&&(r="get",i=n.get),!i)throw new Error("not supported");var o="$memoize$"+t;n[r]=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[o]}},t.debounce=function(e,t,r){return n(function(n,i){var o="$debounce$"+i,s="$debounce$result$"+i;return function(){ for(var i=this,a=[],u=0;u<arguments.length;u++)a[u]=arguments[u];this[s]||(this[s]=r?r():void 0),clearTimeout(this[o]),t&&(this[s]=t.apply(void 0,[this[s]].concat(a)),a=[this[s]]),this[o]=setTimeout(function(){n.apply(i,a),i[s]=r?r():void 0},e)}})}}),define(e[37],t([0,1]),function(e,t){"use strict";function n(e,t){function n(t,n){for(var r=0,i=0;r<t||!n;){var o=e.charCodeAt(a);if(o>=48&&o<=57)i=16*i+o-48;else if(o>=65&&o<=70)i=16*i+o-65+10;else{if(!(o>=97&&o<=102))break;i=16*i+o-97+10}a++,r++}return r<t&&(i=-1),i}function s(){if(c="",p=0,l=a,a>=u)return l=u,f=17;var t=e.charCodeAt(a);if(r(t)){do{a++,c+=String.fromCharCode(t),t=e.charCodeAt(a)}while(r(t));return f=15}if(i(t))return a++,c+=String.fromCharCode(t),13===t&&10===e.charCodeAt(a)&&(a++,c+="\n"),f=14;switch(t){case 123:return a++,f=1;case 125:return a++,f=2;case 91:return a++,f=3;case 93:return a++,f=4;case 58:return a++,f=6;case 44:return a++,f=5;case 34:return a++,c=function(){for(var t="",r=a;;){if(a>=u){t+=e.substring(r,a),p=2;break} var o=e.charCodeAt(a);if(34===o){t+=e.substring(r,a),a++;break}if(92!==o){if(o>=0&&o<=31){if(i(o)){t+=e.substring(r,a),p=2;break}p=6}a++}else{if(t+=e.substring(r,a),++a>=u){p=2;break}switch(o=e.charCodeAt(a++)){case 34:t+='"';break;case 92:t+="\\";break;case 47:t+="/";break;case 98:t+="\b";break;case 102:t+="\f";break;case 110:t+="\n";break;case 114:t+="\r";break;case 116:t+="\t";break;case 117:var s=n(4,!0);s>=0?t+=String.fromCharCode(s):p=4;break;default:p=5}r=a}}return t}(),f=10;case 47:var s=a-1;if(47===e.charCodeAt(a+1)){for(a+=2;a<u&&!i(e.charCodeAt(a));)a++;return c=e.substring(s,a),f=12}if(42===e.charCodeAt(a+1)){a+=2;for(var d=u-1,h=!1;a<d;){if(42===e.charCodeAt(a)&&47===e.charCodeAt(a+1)){a+=2,h=!0;break}a++}return h||(a++,p=1),c=e.substring(s,a),f=13}return c+=String.fromCharCode(t),a++,f=16;case 45:if(c+=String.fromCharCode(t),++a===u||!o(e.charCodeAt(a)))return f=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return c+=function(){var t=a ;if(48===e.charCodeAt(a))a++;else for(a++;a<e.length&&o(e.charCodeAt(a));)a++;if(a<e.length&&46===e.charCodeAt(a)){if(!(++a<e.length&&o(e.charCodeAt(a))))return p=3,e.substring(t,a);for(a++;a<e.length&&o(e.charCodeAt(a));)a++}var n=a;if(a<e.length&&(69===e.charCodeAt(a)||101===e.charCodeAt(a)))if((++a<e.length&&43===e.charCodeAt(a)||45===e.charCodeAt(a))&&a++,a<e.length&&o(e.charCodeAt(a))){for(a++;a<e.length&&o(e.charCodeAt(a));)a++;n=a}else p=3;return e.substring(t,n)}(),f=11;default:for(;a<u&&function(e){if(r(e)||i(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}(t);)a++,t=e.charCodeAt(a);if(l!==a){switch(c=e.substring(l,a)){case"true":return f=8;case"false":return f=9;case"null":return f=7}return f=16}return c+=String.fromCharCode(t),a++,f=16}}void 0===t&&(t=!1);var a=0,u=e.length,c="",l=0,f=16,p=0;return{setPosition:function(e){a=e,c="",l=0,f=16,p=0},getPosition:function(){return a},scan:t?function(){var e;do{e=s()}while(e>=12&&e<=15);return e}:s, getToken:function(){return f},getTokenValue:function(){return c},getTokenOffset:function(){return l},getTokenLength:function(){return a-l},getTokenError:function(){return p}}}function r(e){return 32===e||9===e||11===e||12===e||160===e||5760===e||e>=8192&&e<=8203||8239===e||8287===e||12288===e||65279===e}function i(e){return 10===e||13===e||8232===e||8233===e}function o(e){return e>=48&&e<=57}function s(e){if(!e.parent||!e.parent.children)return[];var t=s(e.parent);if("property"===e.parent.type){var n=e.parent.children[0].value;t.push(n)}else if("array"===e.parent.type){var r=e.parent.children.indexOf(e);-1!==r&&t.push(r)}return t}function a(e){switch(e.type){case"array":return e.children.map(a);case"object":for(var t=Object.create(null),n=0,r=e.children;n<r.length;n++){var i=r[n],o=i.children[1];o&&(t[i.children[0].value]=a(o))}return t;case"null":case"string":case"number":case"boolean":return e.value;default:return}}function u(e,t,n){return void 0===n&&(n=!1), t>=e.offset&&t<e.offset+e.length||n&&t===e.offset+e.length}function c(e,t,n){if(void 0===n&&(n=!1),u(e,t,n)){var r=e.children;if(Array.isArray(r))for(var i=0;i<r.length&&r[i].offset<=t;i++){var o=c(r[i],t,n);if(o)return o}return e}}function l(e,t,r){function i(e){return e?function(){return e(f.getTokenOffset(),f.getTokenLength())}:function(){return!0}}function o(e){return e?function(t){return e(t,f.getTokenOffset(),f.getTokenLength())}:function(){return!0}}function s(){for(;;){var e=f.scan();switch(f.getTokenError()){case 4:a(14);break;case 5:a(15);break;case 3:a(13);break;case 1:x||a(11);break;case 2:a(12);break;case 6:a(16)}switch(e){case 12:case 13:x?a(10):E();break;case 16:a(1);break;case 15:case 14:break;default:return e}}}function a(e,t,n){if(void 0===t&&(t=[]),void 0===n&&(n=[]),S(e),t.length+n.length>0)for(var r=f.getToken();17!==r;){if(-1!==t.indexOf(r)){s();break}if(-1!==n.indexOf(r))break;r=s()}}function u(e){var t=f.getTokenValue();return e?y(t):h(t),s(),!0}function c(){ return 10!==f.getToken()?(a(3,[],[2,5]),!1):(u(!1),6===f.getToken()?(b(":"),s(),l()||a(4,[],[2,5])):a(5,[],[2,5]),!0)}function l(){switch(f.getToken()){case 3:return function(){v(),s();for(var e=!1;4!==f.getToken()&&17!==f.getToken();){if(5===f.getToken()){if(e||a(4,[],[]),b(","),s(),4===f.getToken()&&C)break}else e&&a(6,[],[]);l()||a(4,[],[4,5]),e=!0}return m(),4!==f.getToken()?a(8,[4],[]):s(),!0}();case 1:return function(){d(),s();for(var e=!1;2!==f.getToken()&&17!==f.getToken();){if(5===f.getToken()){if(e||a(4,[],[]),b(","),s(),2===f.getToken()&&C)break}else e&&a(6,[],[]);c()||a(4,[],[2,5]),e=!0}return g(),2!==f.getToken()?a(7,[2],[]):s(),!0}();case 10:return u(!0);default:return function(){switch(f.getToken()){case 11:var e=0;try{"number"!=typeof(e=JSON.parse(f.getTokenValue()))&&(a(2),e=0)}catch(e){a(2)}y(e);break;case 7:y(null);break;case 8:y(!0);break;case 9:y(!1);break;default:return!1}return s(),!0}()}}void 0===r&&(r=p.DEFAULT) ;var f=n(e,!1),d=i(t.onObjectBegin),h=o(t.onObjectProperty),g=i(t.onObjectEnd),v=i(t.onArrayBegin),m=i(t.onArrayEnd),y=o(t.onLiteralValue),b=o(t.onSeparator),E=i(t.onComment),S=o(t.onError),x=r&&r.disallowComments,C=r&&r.allowTrailingComma;return s(),17===f.getToken()||(l()?(17!==f.getToken()&&a(9,[],[]),!0):(a(4,[],[]),!1))}function f(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string";default:return"null"}}Object.defineProperty(t,"__esModule",{value:!0});!function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"}(t.ScanError||(t.ScanError={}));!function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken", e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"}(t.SyntaxKind||(t.SyntaxKind={}));!function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken", e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"}(t.ParseErrorCode||(t.ParseErrorCode={}));var p;!function(e){e.DEFAULT={allowTrailingComma:!0}}(p=t.ParseOptions||(t.ParseOptions={})),t.createScanner=n;var d;!function(e){e[e.nullCharacter=0]="nullCharacter",e[e.maxAsciiCharacter=127]="maxAsciiCharacter",e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.lineSeparator=8232]="lineSeparator",e[e.paragraphSeparator=8233]="paragraphSeparator",e[e.nextLine=133]="nextLine",e[e.space=32]="space",e[e.nonBreakingSpace=160]="nonBreakingSpace",e[e.enQuad=8192]="enQuad",e[e.emQuad=8193]="emQuad",e[e.enSpace=8194]="enSpace",e[e.emSpace=8195]="emSpace",e[e.threePerEmSpace=8196]="threePerEmSpace",e[e.fourPerEmSpace=8197]="fourPerEmSpace", e[e.sixPerEmSpace=8198]="sixPerEmSpace",e[e.figureSpace=8199]="figureSpace",e[e.punctuationSpace=8200]="punctuationSpace",e[e.thinSpace=8201]="thinSpace",e[e.hairSpace=8202]="hairSpace",e[e.zeroWidthSpace=8203]="zeroWidthSpace",e[e.narrowNoBreakSpace=8239]="narrowNoBreakSpace",e[e.ideographicSpace=12288]="ideographicSpace",e[e.mathematicalSpace=8287]="mathematicalSpace",e[e.ogham=5760]="ogham",e[e._=95]="_",e[e.$=36]="$",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C", e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.ampersand=38]="ampersand",e[e.asterisk=42]="asterisk",e[e.at=64]="at",e[e.backslash=92]="backslash",e[e.bar=124]="bar",e[e.caret=94]="caret",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.closeParen=41]="closeParen",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.equals=61]="equals",e[e.exclamation=33]="exclamation",e[e.greaterThan=62]="greaterThan",e[e.lessThan=60]="lessThan",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.openParen=40]="openParen",e[e.percent=37]="percent",e[e.plus=43]="plus",e[e.question=63]="question",e[e.semicolon=59]="semicolon", e[e.singleQuote=39]="singleQuote",e[e.slash=47]="slash",e[e.tilde=126]="tilde",e[e.backspace=8]="backspace",e[e.formFeed=12]="formFeed",e[e.byteOrderMark=65279]="byteOrderMark",e[e.tab=9]="tab",e[e.verticalTab=11]="verticalTab"}(d||(d={})),t.getLocation=function(e,t){function n(e,t,n,r){s.value=e,s.offset=t,s.length=n,s.type=r,s.colonOffset=void 0,o=s}var r=[],i=new Object,o=void 0,s={value:{},offset:0,length:0,type:"object",parent:void 0},a=!1;try{l(e,{onObjectBegin:function(e,n){if(t<=e)throw i;o=void 0,a=t>e,r.push("")},onObjectProperty:function(e,o,s){if(t<o)throw i;if(n(e,o,s,"property"),r[r.length-1]=e,t<=o+s)throw i},onObjectEnd:function(e,n){if(t<=e)throw i;o=void 0,r.pop()},onArrayBegin:function(e,n){if(t<=e)throw i;o=void 0,r.push(0)},onArrayEnd:function(e,n){if(t<=e)throw i;o=void 0,r.pop()},onLiteralValue:function(e,r,o){if(t<r)throw i;if(n(e,r,o,f(e)),t<=r+o)throw i},onSeparator:function(e,n,s){if(t<=n)throw i;if(":"===e&&o&&"property"===o.type)o.colonOffset=n,a=!1,o=void 0;else if(","===e){ var u=r[r.length-1];"number"==typeof u?r[r.length-1]=u+1:(a=!0,r[r.length-1]=""),o=void 0}}})}catch(e){if(e!==i)throw e}return{path:r,previousNode:o,isAtPropertyKey:a,matches:function(e){for(var t=0,n=0;t<e.length&&n<r.length;n++)if(e[t]===r[n]||"*"===e[t])t++;else if("**"!==e[t])return!1;return t===e.length}}},t.parse=function(e,t,n){function r(e){Array.isArray(o)?o.push(e):i&&(o[i]=e)}void 0===t&&(t=[]),void 0===n&&(n=p.DEFAULT);var i=null,o=[],s=[];return l(e,{onObjectBegin:function(){var e={};r(e),s.push(o),o=e,i=null},onObjectProperty:function(e){i=e},onObjectEnd:function(){o=s.pop()},onArrayBegin:function(){var e=[];r(e),s.push(o),o=e,i=null},onArrayEnd:function(){o=s.pop()},onLiteralValue:r,onError:function(e,n,r){t.push({error:e,offset:n,length:r})}},n),o[0]},t.parseTree=function(e,t,n){function r(e){"property"===o.type&&(o.length=e-o.offset,o=o.parent)}function i(e){return o.children.push(e),e}void 0===t&&(t=[]),void 0===n&&(n=p.DEFAULT);var o={type:"array",offset:-1,length:-1,children:[], parent:void 0};l(e,{onObjectBegin:function(e){o=i({type:"object",offset:e,length:-1,parent:o,children:[]})},onObjectProperty:function(e,t,n){(o=i({type:"property",offset:t,length:-1,parent:o,children:[]})).children.push({type:"string",value:e,offset:t,length:n,parent:o})},onObjectEnd:function(e,t){o.length=e+t-o.offset,o=o.parent,r(e+t)},onArrayBegin:function(e,t){o=i({type:"array",offset:e,length:-1,parent:o,children:[]})},onArrayEnd:function(e,t){o.length=e+t-o.offset,o=o.parent,r(e+t)},onLiteralValue:function(e,t,n){i({type:f(e),offset:t,length:n,parent:o,value:e}),r(t+n)},onSeparator:function(e,t,n){"property"===o.type&&(":"===e?o.colonOffset=t:","===e&&r(t))},onError:function(e,n,r){t.push({error:e,offset:n,length:r})}},n);var s=o.children[0];return s&&delete s.parent,s},t.findNodeAtLocation=function(e,t){if(e){for(var n=e,r=0,i=t;r<i.length;r++){var o=i[r];if("string"==typeof o){if("object"!==n.type||!Array.isArray(n.children))return;for(var s=!1,a=0,u=n.children;a<u.length;a++){var c=u[a] ;if(Array.isArray(c.children)&&c.children[0].value===o){n=c.children[1],s=!0;break}}if(!s)return}else{var l=o;if("array"!==n.type||l<0||!Array.isArray(n.children)||l>=n.children.length)return;n=n.children[l]}}return n}},t.getNodePath=s,t.getNodeValue=a,t.contains=u,t.findNodeAtOffset=c,t.visit=l,t.stripComments=function(e,t){var r,i,o=n(e),s=[],a=0;do{switch(i=o.getPosition(),r=o.scan()){case 12:case 13:case 17:a!==i&&s.push(e.substring(a,i)),void 0!==t&&s.push(o.getTokenValue().replace(/[^\r\n]/g,t)),a=o.getPosition()}}while(17!==r);return s.join("")}}),define(e[62],t([0,1,10]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toLocalISOString=function(e){return e.getFullYear()+"-"+n.pad(e.getMonth()+1,2)+"-"+n.pad(e.getDate(),2)+"T"+n.pad(e.getHours(),2)+":"+n.pad(e.getMinutes(),2)+":"+n.pad(e.getSeconds(),2)+"."+(e.getMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"}}),define(e[54],t([0,1,19,10,25,33,21]),function(e,t,n,r,i,o,s){"use strict";function a(e){switch(e){case 0: return"";case 1:return S+"*?";default:return"(?:"+E+"|"+S+"+"+E+"|"+E+S+"+)*?"}}function u(e,t){if(!e)return[];for(var n,r=[],i=!1,o=!1,s="",a=0;a<e.length;a++){switch(n=e[a]){case t:if(!i&&!o){r.push(s),s="";continue}break;case"{":i=!0;break;case"}":i=!1;break;case"[":o=!0;break;case"]":o=!1}s+=n}return s&&r.push(s),r}function c(e){if(!e)return"";var t="",n=u(e,b);if(n.every(function(e){return e===y}))t=".*";else{var i=!1;n.forEach(function(e,o){if(e!==y){for(var s,l=!1,f="",p=!1,d="",h=0;h<e.length;h++)if("}"!==(s=e[h])&&l)f+=s;else if(!p||"]"===s&&d)switch(s){case"{":l=!0;continue;case"[":p=!0;continue;case"}":var g="(?:"+u(f,",").map(function(e){return c(e)}).join("|")+")";t+=g,l=!1,f="";break;case"]":t+="["+d+"]",p=!1,d="";break;case"?":t+=S;continue;case"*":t+=a(1);continue;default:t+=r.escapeRegExpCharacters(s)}else{d+="-"===s?s:"^"!==s&&"!"!==s||d?s===b?"":r.escapeRegExpCharacters(s):"^"}o<n.length-1&&(n[o+1]!==y||o+2<n.length)&&(t+=E),i=!1}else i||(t+=a(2),i=!0)})}return t}function l(e,t){ if(!e)return T;var i;i="string"!=typeof e?e.pattern:e;var o=(i=i.trim())+"_"+!!t.trimForExclusions,s=k.get(o);if(s)return f(s,e);var a;if(C.test(i)){var u=i.substr(4);s=function(e,t){return e&&r.endsWith(e,u)?i:null}}else s=(a=P.exec(p(i,t)))?function(e,t){var n="/"+e,i="\\"+e,o=function(o,s){return o?s?s===e?t:null:o===e||r.endsWith(o,n)||r.endsWith(o,i)?t:null:null},s=[e];return o.basenames=s,o.patterns=[t],o.allBasenames=s,o}(a[1],i):(t.trimForExclusions?w:_).test(i)?function(e,t){var r=m(e.slice(1,-1).split(",").map(function(e){return l(e,t)}).filter(function(e){return e!==T}),e),i=r.length;if(!i)return T;if(1===i)return r[0];var o=function(t,n){for(var i=0,o=r.length;i<o;i++)if(r[i](t,n))return e;return null},s=n.first(r,function(e){return!!e.allBasenames});s&&(o.allBasenames=s.allBasenames);var a=r.reduce(function(e,t){return t.allPaths?e.concat(t.allPaths):e},[]);a.length&&(o.allPaths=a);return o}(i,t):(a=I.exec(p(i,t)))?d(a[1].substr(1),i,!0):(a=O.exec(p(i,t)))?d(a[1],i,!1):function(e){try{ var t=new RegExp("^"+c(e)+"$");return function(n,r){return t.lastIndex=0,n&&t.test(n)?e:null}}catch(e){return T}}(i);return k.set(o,s),f(s,e)}function f(e,t){return"string"==typeof t?e:function(n,r){return i.isEqualOrParent(n,t.base)?e(t.pathToRelative(t.base,n),r):null}}function p(e,t){return t.trimForExclusions&&r.endsWith(e,"/**")?e.substr(0,e.length-2):e}function d(e,t,n){var o=i.nativeSep!==i.sep?e.replace(x,i.nativeSep):e,s=i.nativeSep+o,a=n?function(e,n){return e&&(e===o||r.endsWith(e,s))?t:null}:function(e,n){return e&&e===o?t:null};return a.allPaths=[(n?"*/":"./")+e],a}function h(e,t){if(void 0===t&&(t={}),!e)return j;if("string"==typeof e||v(e)){var r=l(e,t);if(r===T)return j;var o=function(e,t){return!!r(e,t)};return r.allBasenames&&(o.allBasenames=r.allBasenames),r.allPaths&&(o.allPaths=r.allPaths),o}return function(e,t){var r=m(Object.getOwnPropertyNames(e).map(function(n){return function(e,t,n){if(!1===t)return T;var r=l(e,n);if(r===T)return T;if("boolean"==typeof t)return r;if(t){var i=t.when ;if("string"==typeof i){var o=function(t,n,o,a){if(!a||!r(t,n))return null;var u=i.replace("$(basename)",o),c=a(u);return s.isThenable(c)?c.then(function(t){return t?e:null}):c?e:null};return o.requiresSiblings=!0,o}}return r}(n,e[n],t)}).filter(function(e){return e!==T})),o=r.length;if(!o)return T;if(!r.some(function(e){return!!e.requiresSiblings})){if(1===o)return r[0];var a=function(e,t){for(var n=0,i=r.length;n<i;n++){var o=r[n](e,t);if(o)return o}return null},u=n.first(r,function(e){return!!e.allBasenames});u&&(a.allBasenames=u.allBasenames);var c=r.reduce(function(e,t){return t.allPaths?e.concat(t.allPaths):e},[]);return c.length&&(a.allPaths=c),a}var f=function(e,t,n){for(var o=void 0,s=0,a=r.length;s<a;s++){var u=r[s];u.requiresSiblings&&n&&(t||(t=i.basename(e)),o||(o=t.substr(0,t.length-i.extname(e).length)));var c=u(e,t,o,n);if(c)return c}return null},p=n.first(r,function(e){return!!e.allBasenames});p&&(f.allBasenames=p.allBasenames);var d=r.reduce(function(e,t){ return t.allPaths?e.concat(t.allPaths):e},[]);d.length&&(f.allPaths=d);return f}(e,t)}function g(e){for(var t={},n=0,r=e;n<r.length;n++){t[r[n]]=!0}return t}function v(e){var t=e;return t&&"string"==typeof t.base&&"string"==typeof t.pattern&&"function"==typeof t.pathToRelative}function m(e,t){var n=e.filter(function(e){return!!e.basenames});if(n.length<2)return e;var r,i=n.reduce(function(e,t){var n=t.basenames;return n?e.concat(n):e},[]);if(t){r=[];for(var o=0,s=i.length;o<s;o++)r.push(t)}else r=n.reduce(function(e,t){var n=t.patterns;return n?e.concat(n):e},[]);var a=function(e,t){if(!e)return null;if(!t){var n=void 0;for(n=e.length;n>0;n--){var o=e.charCodeAt(n-1);if(47===o||92===o)break}t=e.substr(n)}var s=i.indexOf(t);return-1!==s?r[s]:null};a.basenames=i,a.patterns=r,a.allBasenames=i;var u=e.filter(function(e){return!e.basenames});return u.push(a),u}Object.defineProperty(t,"__esModule",{value:!0}),t.getEmptyExpression=function(){return Object.create(null)} ;var y="**",b="/",E="[/\\\\]",S="[^/\\\\]",x=/\//g;t.splitGlobAware=u;var C=/^\*\*\/\*\.[\w\.-]+$/,P=/^\*\*\/([\w\.-]+)\/?$/,_=/^{\*\*\/[\*\.]?[\w\.-]+\/?(,\*\*\/[\*\.]?[\w\.-]+\/?)*}$/,w=/^{\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?(,\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?)*}$/,I=/^\*\*((\/[\w\.-]+)+)\/?$/,O=/^([\w\.-]+(\/[\w\.-]+)*)\/?$/,k=new o.LRUCache(1e4),j=function(){return!1},T=function(){return null};t.match=function(e,t,n){return!(!e||!t)&&h(e)(t,void 0,n)},t.parse=h,t.hasSiblingPromiseFn=function(e){if(e){var t;return function(n){return t||(t=(e()||Promise.resolve([])).then(function(e){return e?g(e):{}})),t.then(function(e){return!!e[n]})}}},t.hasSiblingFn=function(e){if(e){var t;return function(n){if(!t){var r=e();t=r?g(r):{}}return!!t[n]}}},t.isRelativePattern=v,t.parseToAsync=function(e,t){var n=h(e,t);return function(e,t,r){var i=n(e,t,r);return s.isThenable(i)?i:Promise.resolve(i)}},t.getBasenameTerms=function(e){return e.allBasenames||[]},t.getPathTerms=function(e){return e.allPaths||[]}}), define(e[50],t([0,1,25,10,19,54]),function(e,t,n,r,i,o){"use strict";function s(e,t){void 0===t&&(t=!1);var r=function(e){return{id:e.id,mime:e.mime,filename:e.filename,extension:e.extension,filepattern:e.filepattern,firstline:e.firstline,userConfigured:e.userConfigured,filenameLowercase:e.filename?e.filename.toLowerCase():void 0,extensionLowercase:e.extension?e.extension.toLowerCase():void 0,filepatternLowercase:e.filepattern?e.filepattern.toLowerCase():void 0,filepatternOnPath:!!e.filepattern&&e.filepattern.indexOf(n.sep)>=0}}(e);l.push(r),r.userConfigured?p.push(r):f.push(r),t&&!r.userConfigured&&l.forEach(function(e){e.mime===r.mime||e.userConfigured||(r.extension&&e.extension===r.extension&&console.warn("Overwriting extension <<"+r.extension+">> to now point to mime <<"+r.mime+">>"),r.filename&&e.filename===r.filename&&console.warn("Overwriting filename <<"+r.filename+">> to now point to mime <<"+r.mime+">>"), r.filepattern&&e.filepattern===r.filepattern&&console.warn("Overwriting filepattern <<"+r.filepattern+">> to now point to mime <<"+r.mime+">>"),r.firstline&&e.firstline===r.firstline&&console.warn("Overwriting firstline <<"+r.firstline+">> to now point to mime <<"+r.mime+">>"))})}function a(e,i){if(!e)return[t.MIME_UNKNOWN];e=e.toLowerCase();var o=n.basename(e),s=u(e,o,p);if(s)return[s,t.MIME_TEXT];var a=u(e,o,f);if(a)return[a,t.MIME_TEXT];if(i){var c=function(e){r.startsWithUTF8BOM(e)&&(e=e.substr(1));if(e.length>0)for(var t=0;t<l.length;++t){var n=l[t];if(n.firstline){var i=e.match(n.firstline);if(i&&i.length>0)return n.mime}}return null}(i);if(c)return[c,t.MIME_TEXT]}return[t.MIME_UNKNOWN]}function u(e,t,n){for(var i=null,s=null,a=null,u=n.length-1;u>=0;u--){var c=n[u];if(t===c.filenameLowercase){i=c;break}if(c.filepattern&&(!s||c.filepattern.length>s.filepattern.length)){var l=c.filepatternOnPath?e:t;o.match(c.filepatternLowercase,l)&&(s=c)} c.extension&&(!a||c.extension.length>a.extension.length)&&r.endsWith(t,c.extensionLowercase)&&(a=c)}return i?i.mime:s?s.mime:a?a.mime:null}function c(e){return!e||("string"==typeof e?e===t.MIME_BINARY||e===t.MIME_TEXT||e===t.MIME_UNKNOWN:1===e.length&&c(e[0]))}Object.defineProperty(t,"__esModule",{value:!0}),t.MIME_TEXT="text/plain",t.MIME_BINARY="application/octet-stream",t.MIME_UNKNOWN="application/unknown";var l=[],f=[],p=[];t.registerTextMime=s,t.clearTextMimes=function(e){e?(l=l.filter(function(e){return!e.userConfigured}),p=[]):(l=[],f=[],p=[])},t.guessMimeTypes=a,t.isUnspecific=c,t.suggestFilename=function(e,t){var n=l.filter(function(t){return!t.userConfigured&&t.extension&&t.id===e}).map(function(e){return e.extension}),o=i.coalesce(n).filter(function(e){return r.startsWith(e,".")});return o.length>0?t+o[0]:n[0]||t};var d={".bmp":"image/bmp",".gif":"image/gif",".jpg":"image/jpg",".jpeg":"image/jpg",".jpe":"image/jpg",".png":"image/png",".tiff":"image/tiff",".tif":"image/tiff",".ico":"image/x-icon", ".tga":"image/x-tga",".psd":"image/vnd.adobe.photoshop",".webp":"image/webp",".mid":"audio/midi",".midi":"audio/midi",".mp4a":"audio/mp4",".mpga":"audio/mpeg",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".m2a":"audio/mpeg",".m3a":"audio/mpeg",".oga":"audio/ogg",".ogg":"audio/ogg",".spx":"audio/ogg",".aac":"audio/x-aac",".wav":"audio/x-wav",".wma":"audio/x-ms-wma",".mp4":"video/mp4",".mp4v":"video/mp4",".mpg4":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpe":"video/mpeg",".m1v":"video/mpeg",".m2v":"video/mpeg",".ogv":"video/ogg",".qt":"video/quicktime",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".mk3d":"video/x-matroska",".mks":"video/x-matroska",".wmv":"video/x-ms-wmv",".flv":"video/x-flv",".avi":"video/x-msvideo",".movie":"video/x-sgi-movie"};t.getMediaMime=function(e){var t=n.extname(e);return d[t.toLowerCase()]}}),define(e[53],t([0,1,22,25,10,30,16,94]),function(e,t,n,r,i,o,s,a){"use strict";function u(e){return!(!s.isWindows||!e||":"!==e[1])} function c(e){return u(e)?e.charAt(0).toUpperCase()+e.slice(1):e}function l(e,t){if(s.isWindows||!e||!t)return e;var n=f.original===t?f.normalized:void 0;return n||(n=""+i.rtrim(t,r.sep)+r.sep,f={original:t,normalized:n}),(s.isLinux?i.startsWith(e,n):i.startsWithIgnoreCase(e,n))&&(e="~/"+e.substr(n.length)),e}Object.defineProperty(t,"__esModule",{value:!0}),t.getPathLabel=function(e,t,f){if("string"==typeof e&&(e=n.URI.file(e)),f){var p=f.getWorkspaceFolder(e);if(p){var d=f.getWorkspace().folders.length>1,h=void 0;if(h=a.isEqual(p.uri,e,!s.isLinux)?"":r.normalize(i.ltrim(e.path.substr(p.uri.path.length),r.sep),!0),d){var g=p&&p.name?p.name:r.basename(p.uri.fsPath);h=h?g+" • "+h:g}return h}}if(e.scheme!==o.Schemas.file&&e.scheme!==o.Schemas.untitled)return e.with({query:null,fragment:null}).toString(!0);if(u(e.fsPath))return r.normalize(c(e.fsPath),!0);var v=r.normalize(e.fsPath,!0);return!s.isWindows&&t&&(v=l(v,t.userHome)),v},t.getBaseLabel=function(e){if(e){"string"==typeof e&&(e=n.URI.file(e)) ;var t=r.basename(e.path)||(e.scheme===o.Schemas.file?e.fsPath:e.path);return u(t)?c(t):t}},t.normalizeDriveLetter=c;var f=Object.create(null);t.tildify=l,t.untildify=function(e,t){return e.replace(/^~($|\/|\\)/,t+"$1")};var p="…",d="\\\\",h="~";t.shorten=function(e){for(var t=new Array(e.length),n=!1,o=0;o<e.length;o++){var s=e[o];if(""!==s)if(s){n=!0;var a="";0===s.indexOf(d)?(a=s.substr(0,s.indexOf(d)+d.length),s=s.substr(s.indexOf(d)+d.length)):0===s.indexOf(r.nativeSep)?(a=s.substr(0,s.indexOf(r.nativeSep)+r.nativeSep.length),s=s.substr(s.indexOf(r.nativeSep)+r.nativeSep.length)):0===s.indexOf(h)&&(a=s.substr(0,s.indexOf(h)+h.length),s=s.substr(s.indexOf(h)+h.length));for(var u=s.split(r.nativeSep),c=1;n&&c<=u.length;c++)for(var l=u.length-c;n&&l>=0;l--){n=!1;for(var f=u.slice(l,l+c).join(r.nativeSep),g=0;!n&&g<e.length;g++)if(g!==o&&e[g]&&e[g].indexOf(f)>-1){var v=l+c===u.length,m=l>0&&e[g].indexOf(r.nativeSep)>-1?r.nativeSep+f:f,y=i.endsWith(e[g],m);n=!v||y}if(!n){var b="" ;(i.endsWith(u[0],":")||""!==a)&&(1===l&&(l=0,c++,f=u[0]+r.nativeSep+f),l>0&&(b=u[0]+r.nativeSep),b=a+b),l>0&&(b=b+p+r.nativeSep),b+=f,l+c<u.length&&(b=b+r.nativeSep+p),t[o]=b}}n&&(t[o]=s)}else t[o]=s;else t[o]="."+r.nativeSep}return t};var g;!function(e){e[e.TEXT=0]="TEXT",e[e.VARIABLE=1]="VARIABLE",e[e.SEPARATOR=2]="SEPARATOR"}(g||(g={})),t.template=function(e,t){void 0===t&&(t=Object.create(null));for(var n,r=[],i=!1,o="",s=0;s<e.length;s++)if("$"===(n=e[s])||i&&"{"===n)o&&r.push({value:o,type:g.TEXT}),o="",i=!0;else if("}"===n&&i){var a=t[o];if("string"==typeof a)a.length&&r.push({value:a,type:g.VARIABLE});else if(a){var u=r[r.length-1];u&&u.type===g.SEPARATOR||r.push({value:a.label,type:g.SEPARATOR})}o="",i=!1}else o+=n;return o&&!i&&r.push({value:o,type:g.TEXT}),r.filter(function(e,t){return e.type!==g.SEPARATOR||[r[t-1],r[t+1]].every(function(e){return e&&(e.type===g.VARIABLE||e.type===g.TEXT)&&e.value.length>0})}).map(function(e){return e.value}).join("")},t.mnemonicMenuLabel=function(e,t){ return s.isMacintosh||t?e.replace(/\(&&\w\)|&&/g,""):e.replace(/&&/g,"&")},t.mnemonicButtonLabel=function(e){return s.isMacintosh?e.replace(/\(&&\w\)|&&/g,""):s.isWindows?e.replace(/&&|&/g,function(e){return"&"===e?"&&":"&"}):e.replace(/&&/g,"_")},t.unmnemonicLabel=function(e){return e.replace(/&/g,"&&")}}),define(e[61],t([0,1,35]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n.getPathFromAmdModule(e,"paths"),i=e.__$__nodeRequire(r);t.getAppDataPath=i.getAppDataPath,t.getDefaultUserDataPath=i.getDefaultUserDataPath});var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{u(r.next(e))}catch(e){o(e)}}function a(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}u((r=r.apply(e,t||[])).next())})},r=this&&this.__generator||function(e,t){function n(n){return function(s){return function(n){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1, i&&(o=2&n[0]?i.return:n[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,n[1])).done)return o;switch(i=0,o&&(n=[2&n[0],o.value]),n[0]){case 0:case 1:o=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,i=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(o=a.trys,!(o=o.length>0&&o[o.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!o||n[1]>o[0]&&n[1]<o[3])){a.label=n[1];break}if(6===n[0]&&a.label<o[1]){a.label=o[1],o=n;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(n);break}o[2]&&a.ops.pop(),a.trys.pop();continue}n=t.call(e,a)}catch(e){n=[6,e],i=0}finally{r=o=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,s])}}var r,i,o,s,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s};define(e[64],t([0,1,83,3]),function(e,t,i,o){"use strict";function s(t,s){return void 0===s&&(s={}), n(this,void 0,void 0,function(){var n,a,u,c,l,f;return r(this,function(r){switch(r.label){case 0:return n=i.parse(t),(a=s.proxyUrl||function(e){return"http:"===e.protocol?process.env.HTTP_PROXY||process.env.http_proxy||null:"https:"===e.protocol?process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy||null:null}(n))?(u=i.parse(a),/^https?:$/.test(u.protocol||"")?(c={host:u.hostname||"",port:Number(u.port),auth:u.auth,rejectUnauthorized:!o.isBoolean(s.strictSSL)||s.strictSSL},"http:"!==n.protocol?[3,2]:[4,new Promise(function(t,n){e(["http-proxy-agent"],t,n)})]):[2,null]):[2,null];case 1:return f=r.sent(),[3,4];case 2:return[4,new Promise(function(t,n){e(["https-proxy-agent"],t,n)})];case 3:f=r.sent(),r.label=4;case 4:return l=f,[2,new l(c)]}})})}Object.defineProperty(t,"__esModule",{value:!0}),t.getProxyAgent=s}),define(e[48],t([0,1,24,5,6,11,9,37,39,16]),function(e,t,n,r,i,o,s,a,u,c){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var l=function(){ function e(e,t){void 0===t&&(t={defaultConfig:Object.create(null),onError:function(e){return console.error(e)}}),this._path=e,this.options=t,this.disposables=[],this.configName=r.basename(this._path),this._onDidUpdateConfiguration=new s.Emitter,this.disposables.push(this._onDidUpdateConfiguration),this.registerWatcher(),this.initAsync()}return Object.defineProperty(e.prototype,"path",{get:function(){return this._path},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasParseErrors",{get:function(){return this.parseErrors&&this.parseErrors.length>0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onDidUpdateConfiguration",{get:function(){return this._onDidUpdateConfiguration.event},enumerable:!0,configurable:!0}),e.prototype.initAsync=function(){var e=this;this.loadAsync(function(t){e.loaded||e.updateCache(t),e.options.initCallback&&e.options.initCallback(e.getConfig())})},e.prototype.updateCache=function(e){this.cache=e,this.loaded=!0},e.prototype.loadSync=function(){try{ return this.parse(n.readFileSync(this._path).toString())}catch(e){return this.options.defaultConfig}},e.prototype.loadAsync=function(e){var t=this;n.readFile(this._path,function(n,r){return e(n?t.options.defaultConfig:t.parse(r.toString()))})},e.prototype.parse=function(e){try{return this.parseErrors=[],(this.options.parse?this.options.parse(e,this.parseErrors):a.parse(e,this.parseErrors))||this.options.defaultConfig}catch(e){return this.options.defaultConfig}},e.prototype.registerWatcher=function(){var e=this,t=r.dirname(this._path);this.watch(t,!0),n.lstat(this._path,function(t,r){t||r.isDirectory()||r.isSymbolicLink()&&n.readlink(e._path,function(t,n){t||e.watch(n,!1)})})},e.prototype.watch=function(e,t){var n=this;this.disposed||this.disposables.push(u.watch(e,function(e,r){return n.onConfigFileChange(e,r,t)},function(e){return n.options.onError(e)}))},e.prototype.onConfigFileChange=function(e,t,n){var i=this;n&&(c.isWindows&&t&&t!==this.configName&&(t=r.basename(t)), t!==this.configName)||(this.timeoutHandle&&(global.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.timeoutHandle=global.setTimeout(function(){return i.reload()},this.options.changeBufferDelay||0))},e.prototype.reload=function(e){var t=this;this.loadAsync(function(n){if(i.equals(n,t.cache)||(t.updateCache(n),t._onDidUpdateConfiguration.fire({config:t.cache})),e)return e(n)})},e.prototype.getConfig=function(){return this.ensureLoaded(),this.cache},e.prototype.ensureLoaded=function(){this.loaded||this.updateCache(this.loadSync())},e.prototype.dispose=function(){this.disposed=!0,this.disposables=o.dispose(this.disposables)},e}();t.ConfigWatcher=l}),define(e[59],t([8,4]),function(e,t){return e.create("vs/base/common/errorMessage",t)}),define(e[31],t([0,1,59,3,19]),function(e,t,n,r,i){"use strict";function o(e,t){return e.message?t&&(e.stack||e.stacktrace)?n.localize(0,null,s(e),e.stack||e.stacktrace):s(e):n.localize(1,null)}function s(e){ return"string"==typeof e.code&&"number"==typeof e.errno&&"string"==typeof e.syscall?n.localize(2,null,e.message):e.message}function a(e,t){if(void 0===e&&(e=null),void 0===t&&(t=!1),!e)return n.localize(3,null);if(Array.isArray(e)){var s=i.coalesce(e),u=a(s[0],t);return s.length>1?n.localize(4,null,u,s.length):u}if(r.isString(e))return e;if(e.detail){var c=e.detail;if(c.error)return o(c.error,t);if(c.exception)return o(c.exception,t)}return e.stack?o(e,t):e.message?e.message:n.localize(5,null)}Object.defineProperty(t,"__esModule",{value:!0}),t.toErrorMessage=a}),define(e[65],t([8,4]),function(e,t){return e.create("vs/platform/configuration/common/configurationRegistry",t)}),define(e[66],t([8,4]),function(e,t){return e.create("vs/platform/extensionManagement/common/extensionManagement",t)}),define(e[67],t([8,4]),function(e,t){return e.create("vs/platform/extensionManagement/node/extensionManagementService",t)}),define(e[69],t([8,4]),function(e,t){ return e.create("vs/platform/extensionManagement/node/extensionManagementUtil",t)}),define(e[70],t([8,4]),function(e,t){return e.create("vs/platform/extensions/node/extensionValidator",t)}),define(e[71],t([8,4]),function(e,t){return e.create("vs/platform/node/zip",t)}),define(e[74],t([8,4]),function(e,t){return e.create("vs/platform/request/node/request",t)}),define(e[77],t([8,4]),function(e,t){return e.create("vs/platform/telemetry/common/telemetryService",t)});var i=this&&this.__assign||function(){return(i=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e}).apply(this,arguments)};define(e[18],t([0,1,10]),function(e,t,n){"use strict";function r(e,t){return e.uuid&&t.uuid?e.uuid===t.uuid:e.id===t.id||0===n.compareIgnoreCase(e.id,t.id)}function o(e){return e.toLocaleLowerCase()}function s(e,t){return e.toLocaleLowerCase()+"."+t.toLocaleLowerCase()}function a(e){ return e.manifest?s(e.manifest.publisher,e.manifest.name):e.identifier.id}Object.defineProperty(t,"__esModule",{value:!0}),t.areSameExtensions=r,t.adoptToGalleryExtensionId=o,t.getGalleryExtensionId=s,t.getGalleryExtensionIdFromLocal=a,t.LOCAL_EXTENSION_ID_REGEX=/^([^.]+\..+)-(\d+\.\d+\.\d+(-.*)?)$/,t.getIdFromLocalExtensionId=function(e){var n=t.LOCAL_EXTENSION_ID_REGEX.exec(e);return o(n&&n[1]?n[1]:e)},t.getLocalExtensionId=function(e,t){return e+"-"+t},t.groupByExtension=function(e,t){for(var n=[],i=function(e){for(var i=0,o=n;i<o.length;i++){var s=o[i];if(s.some(function(n){return r(t(n),t(e))}))return s}return null},o=0,s=e;o<s.length;o++){var a=s[o],u=i(a);u?u.push(a):n.push([a])}return n},t.getLocalExtensionTelemetryData=function(e){return{id:a(e),name:e.manifest.name,galleryId:null,publisherId:e.metadata?e.metadata.publisherId:null,publisherName:e.manifest.publisher,publisherDisplayName:e.metadata?e.metadata.publisherDisplayName:null, dependencies:e.manifest.extensionDependencies&&e.manifest.extensionDependencies.length>0}},t.getGalleryExtensionTelemetryData=function(e){return i({id:e.identifier.id,name:e.name,galleryId:e.identifier.uuid,publisherId:e.publisherId,publisherName:e.publisher,publisherDisplayName:e.publisherDisplayName,dependencies:!!(e.properties.dependencies&&e.properties.dependencies.length>0)},e.telemetryData)},t.BetterMergeId="pprice.better-merge",t.getMaliciousExtensionsSet=function(e){for(var t=new Set,n=0,r=e;n<r.length;n++){var i=r[n];i.malicious&&t.add(i.id.id)}return t}}),define(e[84],t([0,1,6]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=/^%([\w\d.-]+)%$/i;t.localizeManifest=function(e,t){return n.cloneAndChange(e,function(e){if("string"==typeof e){var n=r.exec(e);if(n)return t[n[1]]||e}})}});var o=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){ for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();define(e[85],t([0,1,11,92,31,5,21,9,30,12]),function(e,t,i,s,a,u,c,l,f,p){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var d=function(e){function t(t,n){var r=e.call(this)||this;return r.environmentService=t,r.logService=n,r.processesLimiter=new c.Limiter(5),r}return o(t,e),t.prototype.postUninstall=function(e){return n(this,void 0,void 0,function(){var t,n=this;return r(this,function(r){switch(r.label){case 0:return(t=this.parseScript(e,"uninstall"))?(this.logService.info(e.identifier.id,"Running post uninstall script"),[4,this.processesLimiter.queue(function(){return n.runLifecycleHook(t.script,"uninstall",t.args,!0,e).then(function(){return n.logService.info(e.identifier.id,"Finished running post uninstall script")},function(t){ return n.logService.error(e.identifier.id,"Failed to run post uninstall script: "+t)})})]):[3,2];case 1:r.sent(),r.label=2;case 2:return[2,p.rimraf(this.getExtensionStoragePath(e)).then(void 0,function(e){return n.logService.error("Error while removing extension storage path",e)})]}})})},t.prototype.parseScript=function(e,t){var n="vscode:"+t;if(e.location.scheme===f.Schemas.file&&e.manifest&&e.manifest.scripts&&"string"==typeof e.manifest.scripts[n]){var r=e.manifest.scripts[n].split(" ");return r.length<2||"node"!==r[0]||!r[1]?(this.logService.warn(e.identifier.id,n+" should be a node script"),null):{script:u.posix.join(e.location.fsPath,r[1]),args:r.slice(2)||[]}}return null},t.prototype.runLifecycleHook=function(e,t,n,r,i){var o=this;return new Promise(function(s,u){var c,l=o.start(e,t,n,i),f=function(e){c&&(clearTimeout(c),c=null),e?u(e):s(void 0)};l.on("error",function(e){f(a.toErrorMessage(e)||"Unknown")}),l.on("exit",function(e,n){f(e?"post-"+t+" process exited with code "+e:void 0)}), r&&(c=setTimeout(function(){c=null,l.kill(),u("timed out")},5e3))})},t.prototype.start=function(e,t,n,r){var i=this,o={silent:!0,execArgv:void 0},a=s.fork(e,["--type=extension-post-"+t].concat(n),o);a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8");var u=l.Event.fromNodeEventEmitter(a.stdout,"data"),c=l.Event.fromNodeEventEmitter(a.stderr,"data");u(function(e){return i.logService.info(r.identifier.id,"post-"+t,e)}),c(function(e){return i.logService.error(r.identifier.id,"post-"+t,e)});var f=l.Event.any(l.Event.map(u,function(e){return{data:"%c"+e,format:[""]}}),l.Event.map(c,function(e){return{data:"%c"+e,format:["color: red"]}}));return l.Event.debounce(f,function(e,t){return e?{data:e.data+t.data,format:e.format.concat(t.format)}:{data:t.data,format:t.format}},100)(function(e){console.group(r.identifier.id),console.log.apply(console,[e.data].concat(e.format)),console.groupEnd()}),a},t.prototype.getExtensionStoragePath=function(e){ return u.posix.join(this.environmentService.globalStorageHome,e.identifier.id.toLocaleLowerCase())},t}(i.Disposable);t.ExtensionsLifecycle=d}),define(e[46],t([0,1,18,10]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MANIFEST_CACHE_FOLDER="CachedExtensions",t.USER_MANIFEST_CACHE_FILE="user",t.BUILTIN_MANIFEST_CACHE_FILE="builtin";var i=new Set;i.add("msjsdiag.debugger-for-chrome"),t.isUIExtension=function(e,t){var r=n.getGalleryExtensionId(e.publisher,e.name),o=t.getValue("_workbench.uiExtensions")||[];if(o.length){if(-1!==o.indexOf(r))return!0;if(-1!==o.indexOf("-"+r))return!1}switch(e.extensionKind){case"ui":return!0;case"workspace":return!1;default:return i.has(r)||!e.main}};var o=function(){function e(e){this.value=e,this._lower=e.toLowerCase()}return e.equals=function(e,t){if(void 0===e||null===e)return void 0===t||null===t;if(void 0===t||null===t)return!1;if("string"==typeof e||"string"==typeof t){var n="string"==typeof e?e:e.value,i="string"==typeof t?t:t.value ;return r.equalsIgnoreCase(n,i)}return e._lower===t._lower},e.toKey=function(e){return"string"==typeof e?e.toLowerCase():e._lower},e}();t.CanonicalExtensionIdentifier=o}),define(e[49],t([0,1,11,5,46,12]),function(e,t,n,r,i,s){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=function(e){function t(t,n){var o=e.call(this)||this;return o.environmentService=t,o.extensionsManifestCache=r.join(o.environmentService.userDataPath,i.MANIFEST_CACHE_FOLDER,i.USER_MANIFEST_CACHE_FILE),o._register(n.onDidInstallExtension(function(e){return o.onDidInstallExtension(e)})),o._register(n.onDidUninstallExtension(function(e){return o.onDidUnInstallExtension(e)})),o}return o(t,e),t.prototype.onDidInstallExtension=function(e){e.error||this.invalidate()},t.prototype.onDidUnInstallExtension=function(e){e.error||this.invalidate()},t.prototype.invalidate=function(){s.del(this.extensionsManifestCache).then(function(){},function(){})},t}(n.Disposable);t.ExtensionsManifestCache=a}),define(e[38],t([0,1]),function(e,t){ "use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){return function(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=!1),this.ctor=e,this.staticArguments=t,this.supportsDelayedInstantiation=n}}();t.SyncDescriptor=n,t.createSyncDescriptor=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return new n(e,t)}}),define(e[51],t([0,1,3,47]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){this._hashFn=e,this._nodes=Object.create(null)}return e.prototype.roots=function(){var e=[];return r.forEach(this._nodes,function(t){n.isEmptyObject(t.value.outgoing)&&e.push(t.value)}),e},e.prototype.insertEdge=function(e,t){var n=this.lookupOrInsertNode(e),r=this.lookupOrInsertNode(t);n.outgoing[this._hashFn(t)]=r,r.incoming[this._hashFn(e)]=n},e.prototype.removeNode=function(e){var t=this._hashFn(e);delete this._nodes[t],r.forEach(this._nodes,function(e){delete e.value.outgoing[t],delete e.value.incoming[t]})}, e.prototype.lookupOrInsertNode=function(e){var t=this._hashFn(e),n=this._nodes[t];return n||(n=function(e){return{data:e,incoming:Object.create(null),outgoing:Object.create(null)}}(e),this._nodes[t]=n),n},e.prototype.lookup=function(e){return this._nodes[this._hashFn(e)]},e.prototype.isEmpty=function(){for(var e in this._nodes)return!1;return!0},e.prototype.toString=function(){var e=[];return r.forEach(this._nodes,function(t){e.push(t.key+", (incoming)["+Object.keys(t.value.incoming).join(", ")+"], (outgoing)["+Object.keys(t.value.outgoing).join(",")+"]")}),e.join("\n")},e}();t.Graph=i}),define(e[52],t([0,1,2]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IDownloadService=n.createDecorator("downloadService")}),define(e[17],t([0,1,2]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IEnvironmentService=n.createDecorator("environmentService")}),define(e[28],t([0,1,66,2]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{ value:!0}),t.EXTENSION_IDENTIFIER_PATTERN="^([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$",t.EXTENSION_IDENTIFIER_REGEX=new RegExp(t.EXTENSION_IDENTIFIER_PATTERN),t.isIExtensionIdentifier=function(e){return e&&"object"==typeof e&&"string"==typeof e.id&&(!e.uuid||"string"==typeof e.uuid)};!function(e){e[e.System=0]="System",e[e.User=1]="User"}(t.LocalExtensionType||(t.LocalExtensionType={})),t.IExtensionManagementService=r.createDecorator("extensionManagementService"),t.IExtensionGalleryService=r.createDecorator("extensionGalleryService");!function(e){e[e.NoneOrRelevance=0]="NoneOrRelevance",e[e.LastUpdatedDate=1]="LastUpdatedDate",e[e.Title=2]="Title",e[e.PublisherName=3]="PublisherName",e[e.InstallCount=4]="InstallCount",e[e.PublishedDate=5]="PublishedDate",e[e.AverageRating=6]="AverageRating",e[e.WeightedRating=12]="WeightedRating"}(t.SortBy||(t.SortBy={}));!function(e){e[e.Default=0]="Default",e[e.Ascending=1]="Ascending",e[e.Descending=2]="Descending"}(t.SortOrder||(t.SortOrder={})) ;!function(e){e.Uninstall="uninstall"}(t.StatisticType||(t.StatisticType={}));!function(e){e[e.None=0]="None",e[e.Install=1]="Install",e[e.Update=2]="Update"}(t.InstallOperation||(t.InstallOperation={})),t.INSTALL_ERROR_MALICIOUS="malicious",t.INSTALL_ERROR_INCOMPATIBLE="incompatible",t.IExtensionManagementServerService=r.createDecorator("extensionManagementServerService");!function(e){e[e.Disabled=0]="Disabled",e[e.WorkspaceDisabled=1]="WorkspaceDisabled",e[e.Enabled=2]="Enabled",e[e.WorkspaceEnabled=3]="WorkspaceEnabled"}(t.EnablementState||(t.EnablementState={})),t.IExtensionEnablementService=r.createDecorator("extensionEnablementService"),t.IExtensionTipsService=r.createDecorator("extensionTipsService");!function(e){e[e.Workspace=0]="Workspace",e[e.File=1]="File",e[e.Executable=2]="Executable",e[e.DynamicWorkspace=3]="DynamicWorkspace",e[e.Experimental=4]="Experimental"}(t.ExtensionRecommendationReason||(t.ExtensionRecommendationReason={})),t.ExtensionsLabel=n.localize(0,null), t.ExtensionsChannelId="extensions",t.PreferencesLabel=n.localize(1,null)}),define(e[29],t([0,1]),function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._entries=new Map;for(var n=0,r=e;n<r.length;n++){var i=r[n],o=i[0],s=i[1];this.set(o,s)}}return e.prototype.set=function(e,t){var n=this._entries.get(e);return this._entries.set(e,t),n},e.prototype.forEach=function(e){this._entries.forEach(function(t,n){return e(n,t)})},e.prototype.has=function(e){return this._entries.has(e)},e.prototype.get=function(e){return this._entries.get(e)},e}();t.ServiceCollection=n}),define(e[57],t([0,1,23,3,51,38,2,29]),function(e,t,n,r,i,s,a,u){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var c=function(){function e(e,t,n){void 0===e&&(e=new u.ServiceCollection),void 0===t&&(t=!1),this._services=e,this._strict=t,this._parent=n,this._services.set(a.IInstantiationService,this)} return e.prototype.createChild=function(t){return new e(t,this._strict,this)},e.prototype.invokeFunction=function(e){for(var t=this,r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];var o=f.traceInvocation(e),s=!1;try{var u={get:function(e,r){if(s)throw n.illegalState("service accessor is only valid during the invocation of its target method");var i=t._getOrCreateServiceInstance(e,o);if(!i&&r!==a.optional)throw new Error("[invokeFunction] unknown service '"+e+"'");return i}};return e.apply(void 0,[u].concat(r))}finally{s=!0,o.stop()}},e.prototype.createInstance=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r,i;return e instanceof s.SyncDescriptor?(r=f.traceCreation(e.ctor),i=this._createInstance(e.ctor,e.staticArguments.concat(t),r)):(r=f.traceCreation(e),i=this._createInstance(e,t,r)),r.stop(),i},e.prototype._createInstance=function(e,t,n){void 0===t&&(t=[]);for(var i=a._util.getServiceDependencies(e).sort(function(e,t){return e.index-t.index}),o=[],s=0,u=i;s<u.length;s++){ var c=u[s],l=this._getOrCreateServiceInstance(c.id,n);if(!l&&this._strict&&!c.optional)throw new Error("[createInstance] "+e.name+" depends on UNKNOWN service "+c.id+".");o.push(l)}var f=i.length>0?i[0].index:t.length;if(t.length!==f){console.warn("[createInstance] First service dependency of "+e.name+" at position "+(f+1)+" conflicts with "+t.length+" static arguments");var p=f-t.length;t=p>0?t.concat(new Array(p)):t.slice(0,f)}return r.create.apply(null,[e].concat(t,o))},e.prototype._setServiceInstance=function(e,t){if(this._services.get(e)instanceof s.SyncDescriptor)this._services.set(e,t);else{if(!this._parent)throw new Error("illegalState - setting UNKNOWN service instance");this._parent._setServiceInstance(e,t)}},e.prototype._getServiceInstanceOrDescriptor=function(e){var t=this._services.get(e);return!t&&this._parent?this._parent._getServiceInstanceOrDescriptor(e):t},e.prototype._getOrCreateServiceInstance=function(e,t){var n=this._getServiceInstanceOrDescriptor(e) ;return n instanceof s.SyncDescriptor?this._createAndCacheServiceInstance(e,n,t.branch(e,!0)):(t.branch(e,!1),n)},e.prototype._createAndCacheServiceInstance=function(e,t,n){function r(){var e=new Error("[createInstance] cyclic dependency between services");throw e.message=o.toString(),e}for(var o=new i.Graph(function(e){return e.id.toString()}),u=0,c=[{id:e,desc:t,_trace:n}];c.length;){var l=c.pop();o.lookupOrInsertNode(l),u++>100&&r();for(var f=0,p=a._util.getServiceDependencies(l.desc.ctor);f<p.length;f++){var d=p[f],h=this._getServiceInstanceOrDescriptor(d.id);if(h||d.optional||console.warn("[createInstance] "+e+" depends on "+d.id+" which is NOT registered."),h instanceof s.SyncDescriptor){var g={id:d.id,desc:h,_trace:l._trace.branch(d.id,!0)};o.insertEdge(l,g),c.push(g)}}}for(;;){var v=o.roots();if(0===v.length){o.isEmpty()||r();break}for(var m=0,y=v;m<y.length;m++){var b=y[m].data,E=this._createServiceInstanceWithOwner(b.id,b.desc.ctor,b.desc.staticArguments,b.desc.supportsDelayedInstantiation,b._trace) ;this._setServiceInstance(b.id,E),o.removeNode(b)}}return this._getServiceInstanceOrDescriptor(e)},e.prototype._createServiceInstanceWithOwner=function(e,t,n,r,i){if(void 0===n&&(n=[]),this._services.get(e)instanceof s.SyncDescriptor)return this._createServiceInstance(t,n,r,i);if(this._parent)return this._parent._createServiceInstanceWithOwner(e,t,n,r,i);throw new Error("illegalState - creating UNKNOWN service instance")},e.prototype._createServiceInstance=function(e,t,n,r){return void 0===t&&(t=[]),this._createInstance(e,t,r)},e}();t.InstantiationService=c;var l;!function(e){e[e.Creation=0]="Creation",e[e.Invocation=1]="Invocation",e[e.Branch=2]="Branch"}(l||(l={}));var f=function(){function e(e,t){this.type=e,this.name=t,this._start=Date.now(),this._dep=[]}return e.traceInvocation=function(t){return e._None},e.traceCreation=function(t){return e._None},e.prototype.branch=function(t,n){var r=new e(2,t.toString());return this._dep.push([t,n,r]),r},e.prototype.stop=function(){function t(e,n){ for(var i=[],o=new Array(e+1).join("\t"),s=0,a=n._dep;s<a.length;s++){var u=a[s],c=u[0],l=u[1],f=u[2];if(l&&f){r=!0,i.push(o+"CREATES -> "+c);var p=t(e+1,f);p&&i.push(p)}else i.push(o+"uses -> "+c)}return i.join("\n")}var n=Date.now()-this._start;e._totals+=n;var r=!1,i=[(0===this.type?"CREATE":"CALL")+" "+this.name,""+t(1,this),"DONE, took "+n.toFixed(2)+"ms (grand total "+e._totals.toFixed(2)+"ms)"];(n>2||r)&&console.log(i.join("\n"))},e._None=new(function(e){function t(){return e.call(this,-1,null)||this}return o(t,e),t.prototype.stop=function(){},t.prototype.branch=function(){return this},t}(e)),e._totals=0,e}()}),define(e[7],t([0,1,2,11,16,9]),function(e,t,n,r,i,s){"use strict";function a(){return(new Date).toISOString()}Object.defineProperty(t,"__esModule",{value:!0}),t.ILogService=n.createDecorator("logService");var u;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.Off=6]="Off" }(u=t.LogLevel||(t.LogLevel={})),t.DEFAULT_LOG_LEVEL=u.Info;var c=function(e){function n(){var n=null!==e&&e.apply(this,arguments)||this;return n.level=t.DEFAULT_LOG_LEVEL,n._onDidChangeLogLevel=n._register(new s.Emitter),n.onDidChangeLogLevel=n._onDidChangeLogLevel.event,n}return o(n,e),n.prototype.setLevel=function(e){this.level!==e&&(this.level=e,this._onDidChangeLogLevel.fire(this.level))},n.prototype.getLevel=function(){return this.level},n}(r.Disposable);t.AbstractLogService=c;var l=function(e){function n(n){void 0===n&&(n=t.DEFAULT_LOG_LEVEL);var r=e.call(this)||this;return r.setLevel(n),r.useColors=!i.isWindows,r}return o(n,e),n.prototype.trace=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Trace&&(this.useColors?console.log.apply(console,["[main "+a()+"]",e].concat(t)):console.log.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.debug=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n] ;this.getLevel()<=u.Debug&&(this.useColors?console.log.apply(console,["[main "+a()+"]",e].concat(t)):console.log.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.info=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Info&&(this.useColors?console.log.apply(console,["[main "+a()+"]",e].concat(t)):console.log.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.warn=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Warning&&(this.useColors?console.warn.apply(console,["[main "+a()+"]",e].concat(t)):console.warn.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.error=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Error&&(this.useColors?console.error.apply(console,["[main "+a()+"]",e].concat(t)):console.error.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.critical=function(e){ for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Critical&&(this.useColors?console.error.apply(console,["[main "+a()+"]",e].concat(t)):console.error.apply(console,["[main "+a()+"]",e].concat(t)))},n.prototype.dispose=function(){},n}(c);t.ConsoleLogMainService=l;var f=function(e){function n(n){void 0===n&&(n=t.DEFAULT_LOG_LEVEL);var r=e.call(this)||this;return r.setLevel(n),r}return o(n,e),n.prototype.trace=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Trace&&console.log.apply(console,["%cTRACE","color: #888",e].concat(t))},n.prototype.debug=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Debug&&console.log.apply(console,["%cDEBUG","background: #eee; color: #888",e].concat(t))},n.prototype.info=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Info&&console.log.apply(console,["%c INFO","color: #33f",e].concat(t))},n.prototype.warn=function(e){ for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Warning&&console.log.apply(console,["%c WARN","color: #993",e].concat(t))},n.prototype.error=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Error&&console.log.apply(console,["%c ERR","color: #f33",e].concat(t))},n.prototype.critical=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.getLevel()<=u.Critical&&console.log.apply(console,["%cCRITI","background: #f33; color: white",e].concat(t))},n.prototype.dispose=function(){},n}(c);t.ConsoleLogService=f;var p=function(e){function t(t){var n=e.call(this)||this;return n.logServices=t,t.length&&n.setLevel(t[0].getLevel()),n}return o(t,e),t.prototype.setLevel=function(t){for(var n=0,r=this.logServices;n<r.length;n++){r[n].setLevel(t)}e.prototype.setLevel.call(this,t)},t.prototype.trace=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r] ;o.trace.apply(o,[e].concat(t))}},t.prototype.debug=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r];o.debug.apply(o,[e].concat(t))}},t.prototype.info=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r];o.info.apply(o,[e].concat(t))}},t.prototype.warn=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r];o.warn.apply(o,[e].concat(t))}},t.prototype.error=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r];o.error.apply(o,[e].concat(t))}},t.prototype.critical=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=this.logServices;r<i.length;r++){var o=i[r];o.critical.apply(o,[e].concat(t))}},t.prototype.dispose=function(){for(var e=0,t=this.logServices;e<t.length;e++){ t[e].dispose()}},t}(c);t.MultiplexLogService=p;var d=function(e){function t(t){var n=e.call(this)||this;return n.logService=t,n._register(t),n}return o(t,e),Object.defineProperty(t.prototype,"onDidChangeLogLevel",{get:function(){return this.logService.onDidChangeLogLevel},enumerable:!0,configurable:!0}),t.prototype.setLevel=function(e){this.logService.setLevel(e)},t.prototype.getLevel=function(){return this.logService.getLevel()},t.prototype.trace=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).trace.apply(r,[e].concat(t))},t.prototype.debug=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).debug.apply(r,[e].concat(t))},t.prototype.info=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).info.apply(r,[e].concat(t))},t.prototype.warn=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).warn.apply(r,[e].concat(t))}, t.prototype.error=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).error.apply(r,[e].concat(t))},t.prototype.critical=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r;(r=this.logService).critical.apply(r,[e].concat(t))},t}(r.Disposable);t.DelegatedLogService=d;var h=function(){function e(){this.onDidChangeLogLevel=(new s.Emitter).event}return e.prototype.setLevel=function(e){},e.prototype.getLevel=function(){return u.Info},e.prototype.trace=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.debug=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.info=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.warn=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.error=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.critical=function(e){ for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n]},e.prototype.dispose=function(){},e}();t.NullLogService=h,t.getLogLevel=function(e){if(e.verbose)return u.Trace;if("string"==typeof e.args.log)switch(e.args.log.toLowerCase()){case"trace":return u.Trace;case"debug":return u.Debug;case"info":return u.Info;case"warn":return u.Warning;case"error":return u.Error;case"critical":return u.Critical;case"off":return u.Off}return t.DEFAULT_LOG_LEVEL}}),define(e[60],t([0,1,5,7]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createSpdLogService=function(t,o,s){try{var a=e.__$__nodeRequire("spdlog");a.setAsyncMode(8192,500);var u=n.join(s,t+".log"),c=new a.RotatingLogger(t,u,5242880,6);return c.setLevel(0),new i(c,o)}catch(e){console.error(e)}return new r.NullLogService},t.createRotatingLogger=function(t,n,r,i){return new(e.__$__nodeRequire("spdlog").RotatingLogger)(t,n,r,i)};var i=function(e){function t(t,n){void 0===n&&(n=r.LogLevel.Error);var i=e.call(this)||this ;return i.logger=t,i.setLevel(n),i}return o(t,e),t.prototype.trace=function(){this.getLevel()<=r.LogLevel.Trace&&this.logger.trace(this.format(arguments))},t.prototype.debug=function(){this.getLevel()<=r.LogLevel.Debug&&this.logger.debug(this.format(arguments))},t.prototype.info=function(){this.getLevel()<=r.LogLevel.Info&&this.logger.info(this.format(arguments))},t.prototype.warn=function(){this.getLevel()<=r.LogLevel.Warning&&this.logger.warn(this.format(arguments))},t.prototype.error=function(){if(this.getLevel()<=r.LogLevel.Error){var e=arguments[0];if(e instanceof Error){var t=Array.prototype.slice.call(arguments);t[0]=e.stack,this.logger.error(this.format(t))}else this.logger.error(this.format(arguments))}},t.prototype.critical=function(){this.getLevel()<=r.LogLevel.Critical&&this.logger.critical(this.format(arguments))},t.prototype.dispose=function(){this.logger.drop()},t.prototype.format=function(e){for(var t="",n=0;n<e.length;n++){var r=e[n];if("object"==typeof r)try{r=JSON.stringify(r)}catch(e){} t+=(n>0?" ":"")+r}return t},t}(r.AbstractLogService)}),define(e[32],t([0,1,70,20]),function(e,t,n,r){"use strict";function i(e){return"*"===(e=e.trim())||c.test(e)}function o(e){if(!i(e))return null;if("*"===(e=e.trim()))return{hasCaret:!1,hasGreaterEquals:!1,majorBase:0,majorMustEqual:!1,minorBase:0,minorMustEqual:!1,patchBase:0,patchMustEqual:!1,preRelease:null};var t=e.match(c);return t?{hasCaret:"^"===t[1],hasGreaterEquals:">="===t[1],majorBase:"x"===t[2]?0:parseInt(t[2],10),majorMustEqual:"x"!==t[2],minorBase:"x"===t[4]?0:parseInt(t[4],10),minorMustEqual:"x"!==t[4],patchBase:"x"===t[6]?0:parseInt(t[6],10),patchMustEqual:"x"!==t[6],preRelease:t[8]||null}:null}function s(e){if(!e)return null;var t=e.majorBase,n=e.majorMustEqual,r=e.minorBase,i=e.minorMustEqual,o=e.patchBase,s=e.patchMustEqual;return e.hasCaret&&(0===t?s=!1:(i=!1,s=!1)),{majorBase:t,majorMustEqual:n,minorBase:r,minorMustEqual:i,patchBase:o,patchMustEqual:s,isMinimum:e.hasGreaterEquals}}function a(e,t){var n;n="string"==typeof e?s(o(e)):e ;var r;if(r="string"==typeof t?s(o(t)):t,!n||!r)return!1;var i=n.majorBase,a=n.minorBase,u=n.patchBase,c=r.majorBase,l=r.minorBase,f=r.patchBase,p=r.majorMustEqual,d=r.minorMustEqual,h=r.patchMustEqual;return r.isMinimum?i>c||!(i<c)&&(a>l||!(a<l)&&u>=f):(1!==i||0!==c||p&&d&&h||(c=1,l=0,f=0,p=!0,d=!1,h=!1),!(i<c)&&(i>c?!p:!(a<l)&&(a>l?!d:!(u<f)&&(!(u>f)||!h))))}function u(e,t,r){void 0===r&&(r=[]);var i=s(o(t));if(!i)return r.push(n.localize(0,null,t)),!1;if(0===i.majorBase){if(!i.majorMustEqual||!i.minorMustEqual)return r.push(n.localize(1,null,t)),!1}else if(!i.majorMustEqual)return r.push(n.localize(2,null,t)),!1;return!!a(e,i)||(r.push(n.localize(3,null,e,t)),!1)}Object.defineProperty(t,"__esModule",{value:!0});var c=/^(\^|>=)?((\d+)|x)\.((\d+)|x)\.((\d+)|x)(\-.*)?$/;t.isValidVersionStr=i,t.parseVersion=o,t.normalizeVersion=s,t.isValidVersion=a,t.isValidExtensionVersion=function(e,t,n){return!(!t.isBuiltin&&void 0!==t.main)||u(e,t.engines.vscode,n)},t.isEngineValid=function(e){ return"*"===e||u(r.default.version,e)},t.isVersionValid=u});var s=this&&this.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};define(e[63],t([0,1,90,61,26,5,55,20,36,62,16,35,22]),function(e,t,n,r,i,o,a,u,c,l,f,p,d){"use strict";function h(e,t){return f.isWindows?function(e,t){return"\\\\.\\pipe\\"+n.createHash("md5").update(e).digest("hex")+"-"+u.default.version+"-"+t+"-sock"}(e,t):function(e,t){if(E){var r=n.createHash("md5").update(e).digest("hex").substr(0,8);return o.join(E,"vscode-"+r+"-"+u.default.version+"-"+t+".sock")}return o.join(e,u.default.version+"-"+t+".sock")}(e,t)}function g(e,t){return m(e.debugPluginHost,e.debugBrkPluginHost,5870,t,e.debugId)}function v(e,t){return m(e.debugSearch,e.debugBrkSearch,5876,t)} function m(e,t,n,r,i){var o=t||e,s=Number(o)||(r?null:n);return{port:s,break:!!s&&Boolean(!!t),debugId:i}}function y(e,t){if(e){var n=o.resolve(e);return o.normalize(e)===n?n:o.resolve(t.env.VSCODE_CWD||t.cwd(),e)}}function b(e,t){return y(e["user-data-dir"],t)||o.resolve(r.getDefaultUserDataPath(t.platform))}Object.defineProperty(t,"__esModule",{value:!0});var E=process.env.XDG_RUNTIME_DIR,S=function(){function t(e,t){if(this._args=e,this._execPath=t,!process.env.VSCODE_LOGS){var n=l.toLocalISOString(new Date).replace(/-|:|\.\d+Z$/g,"");process.env.VSCODE_LOGS=o.join(this.userDataPath,"logs",n)}this.logsPath=process.env.VSCODE_LOGS}return Object.defineProperty(t.prototype,"args",{get:function(){return this._args},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"appRoot",{get:function(){return o.dirname(p.getPathFromAmdModule(e,""))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"execPath",{get:function(){return this._execPath},enumerable:!0,configurable:!0}), Object.defineProperty(t.prototype,"cliPath",{get:function(){return function(e,t,n){return f.isWindows?n?o.join(o.dirname(e),"bin",c.default.applicationName+".cmd"):o.join(t,"scripts","code-cli.bat"):f.isLinux?n?o.join(o.dirname(e),"bin",""+c.default.applicationName):o.join(t,"scripts","code-cli.sh"):n?o.join(t,"bin","code"):o.join(t,"scripts","code-cli.sh")}(this.execPath,this.appRoot,this.isBuilt)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"userHome",{get:function(){return i.homedir()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"userDataPath",{get:function(){var e=process.env.VSCODE_PORTABLE;return e?o.join(e,"user-data"):b(this._args,process)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"appNameLong",{get:function(){return c.default.nameLong},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"appQuality",{get:function(){return c.default.quality},enumerable:!0,configurable:!0}), Object.defineProperty(t.prototype,"appSettingsHome",{get:function(){return o.join(this.userDataPath,"User")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"appSettingsPath",{get:function(){return o.join(this.appSettingsHome,"settings.json")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"globalStorageHome",{get:function(){return o.join(this.appSettingsHome,"globalStorage")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"workspaceStorageHome",{get:function(){return o.join(this.appSettingsHome,"workspaceStorage")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"settingsSearchBuildId",{get:function(){return c.default.settingsSearchBuildId},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"settingsSearchUrl",{get:function(){return c.default.settingsSearchUrl},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"appKeybindingsPath",{get:function(){return o.join(this.appSettingsHome,"keybindings.json")}, enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isExtensionDevelopment",{get:function(){return!!this._args.extensionDevelopmentPath},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"backupHome",{get:function(){return o.join(this.userDataPath,"Backups")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"backupWorkspacesPath",{get:function(){return o.join(this.backupHome,"workspaces.json")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"workspacesHome",{get:function(){return o.join(this.userDataPath,"Workspaces")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"installSourcePath",{get:function(){return o.join(this.userDataPath,"installSource")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"builtinExtensionsPath",{get:function(){var t=y(this._args["builtin-extensions-dir"],process);return t||o.normalize(o.join(p.getPathFromAmdModule(e,""),"..","extensions"))},enumerable:!0,configurable:!0}), Object.defineProperty(t.prototype,"extensionsPath",{get:function(){var e=y(this._args["extensions-dir"],process);if(e)return e;var t=process.env.VSCODE_EXTENSIONS;if(t)return t;var n=process.env.VSCODE_PORTABLE;return n?o.join(n,"extensions"):o.join(this.userHome,c.default.dataFolderName,"extensions")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"extensionDevelopmentLocationURI",{get:function(){var e=this._args.extensionDevelopmentPath;if(e)return/^[^:/?#]+?:\/\//.test(e)?d.URI.parse(e):d.URI.file(o.normalize(e))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"extensionTestsPath",{get:function(){return this._args.extensionTestsPath?o.normalize(this._args.extensionTestsPath):this._args.extensionTestsPath},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"disableExtensions",{get:function(){if(this._args["disable-extensions"])return!0;var e=this._args["disable-extension"];if(e){if("string"==typeof e)return[e];if(Array.isArray(e)&&e.length>0)return e} return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipGettingStarted",{get:function(){return!!this._args["skip-getting-started"]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipReleaseNotes",{get:function(){return!!this._args["skip-release-notes"]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipAddToRecentlyOpened",{get:function(){return!!this._args["skip-add-to-recently-opened"]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"debugExtensionHost",{get:function(){return g(this._args,this.isBuilt)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"debugSearch",{get:function(){return v(this._args,this.isBuilt)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBuilt",{get:function(){return!process.env.VSCODE_DEV},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"verbose",{get:function(){return!!this._args.verbose},enumerable:!0,configurable:!0}), Object.defineProperty(t.prototype,"log",{get:function(){return this._args.log},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wait",{get:function(){return!!this._args.wait},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"logExtensionHostCommunication",{get:function(){return!!this._args.logExtensionHostCommunication},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"performance",{get:function(){return!!this._args.performance},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"status",{get:function(){return!!this._args.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"mainIPCHandle",{get:function(){return h(this.userDataPath,"main")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"sharedIPCHandle",{get:function(){return h(this.userDataPath,"shared")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nodeCachedDataDir",{get:function(){ return process.env.VSCODE_NODE_CACHED_DATA_DIR||void 0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"disableUpdates",{get:function(){return!!this._args["disable-updates"]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"disableCrashReporter",{get:function(){return!!this._args["disable-crash-reporter"]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"driverHandle",{get:function(){return this._args.driver},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"driverVerbose",{get:function(){return!!this._args["driver-verbose"]},enumerable:!0,configurable:!0}),s([a.memoize],t.prototype,"appRoot",null),s([a.memoize],t.prototype,"cliPath",null),s([a.memoize],t.prototype,"userHome",null),s([a.memoize],t.prototype,"userDataPath",null),s([a.memoize],t.prototype,"appSettingsHome",null),s([a.memoize],t.prototype,"appSettingsPath",null),s([a.memoize],t.prototype,"globalStorageHome",null),s([a.memoize],t.prototype,"workspaceStorageHome",null), s([a.memoize],t.prototype,"settingsSearchBuildId",null),s([a.memoize],t.prototype,"settingsSearchUrl",null),s([a.memoize],t.prototype,"appKeybindingsPath",null),s([a.memoize],t.prototype,"isExtensionDevelopment",null),s([a.memoize],t.prototype,"backupHome",null),s([a.memoize],t.prototype,"backupWorkspacesPath",null),s([a.memoize],t.prototype,"workspacesHome",null),s([a.memoize],t.prototype,"installSourcePath",null),s([a.memoize],t.prototype,"builtinExtensionsPath",null),s([a.memoize],t.prototype,"extensionsPath",null),s([a.memoize],t.prototype,"extensionDevelopmentLocationURI",null),s([a.memoize],t.prototype,"extensionTestsPath",null),s([a.memoize],t.prototype,"debugExtensionHost",null),s([a.memoize],t.prototype,"debugSearch",null),s([a.memoize],t.prototype,"mainIPCHandle",null),s([a.memoize],t.prototype,"sharedIPCHandle",null),s([a.memoize],t.prototype,"nodeCachedDataDir",null),t}();t.EnvironmentService=S,t.parseExtensionHostPort=g,t.parseSearchPort=v,t.parseDebugPort=m,t.parseUserDataDir=b}), define(e[14],t([0,1,3,56]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){this.data={}}return e.prototype.add=function(e,t){r.ok(n.isString(e)),r.ok(n.isObject(t)),r.ok(!this.data.hasOwnProperty(e),"There is already an extension with this id"),this.data[e]=t},e.prototype.knows=function(e){return this.data.hasOwnProperty(e)},e.prototype.as=function(e){return this.data[e]||null},e}();t.Registry=new i}),define(e[68],t([0,1,14,9]),function(e,t,n,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Extensions={JSONContribution:"base.contributions.json"};var i=new(function(){function e(){this._onDidChangeSchema=new r.Emitter,this.onDidChangeSchema=this._onDidChangeSchema.event,this.schemasById={}}return e.prototype.registerSchema=function(e,t){this.schemasById[function(e){return e.length>0&&"#"===e.charAt(e.length-1)?e.substring(0,e.length-1):e}(e)]=t,this._onDidChangeSchema.fire(e)},e.prototype.notifySchemaChanged=function(e){ this._onDidChangeSchema.fire(e)},e.prototype.getSchemaContributions=function(){return{schemas:this.schemasById}},e}());n.Registry.add(t.Extensions.JSONContribution,i)}),define(e[15],t([0,1,65,9,14,3,10,68]),function(e,t,n,r,i,o,s,a){"use strict";function u(e){switch(Array.isArray(e)?e[0]:e){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};default:return null}}function c(e){return t.OVERRIDE_PROPERTY_PATTERN.test(e)?n.localize(3,null,e):void 0!==g.getConfigurationProperties()[e]?n.localize(4,null,e):null}Object.defineProperty(t,"__esModule",{value:!0}),t.Extensions={Configuration:"base.contributions.configuration"};!function(e){e[e.APPLICATION=1]="APPLICATION",e[e.WINDOW=2]="WINDOW",e[e.RESOURCE=3]="RESOURCE"}(t.ConfigurationScope||(t.ConfigurationScope={})),t.allSettings={properties:{},patternProperties:{}},t.applicationSettings={properties:{},patternProperties:{}},t.windowSettings={properties:{},patternProperties:{}}, t.resourceSettings={properties:{},patternProperties:{}},t.editorConfigurationSchemaId="vscode://schemas/settings/editor";var l=i.Registry.as(a.Extensions.JSONContribution),f=function(){function e(){this.overrideIdentifiers=[],this._onDidSchemaChange=new r.Emitter,this.onDidSchemaChange=this._onDidSchemaChange.event,this._onDidRegisterConfiguration=new r.Emitter,this.onDidRegisterConfiguration=this._onDidRegisterConfiguration.event,this.configurationContributors=[],this.editorConfigurationSchema={properties:{},patternProperties:{},additionalProperties:!1,errorMessage:"Unknown editor configuration setting"},this.configurationProperties={},this.excludedConfigurationProperties={},this.computeOverridePropertyPattern(),l.registerSchema(t.editorConfigurationSchemaId,this.editorConfigurationSchema)}return e.prototype.registerConfiguration=function(e,t){void 0===t&&(t=!0),this.registerConfigurations([e],[],t)},e.prototype.registerConfigurations=function(e,t,n){var r=this;void 0===n&&(n=!0) ;var i=this.toConfiguration(t);i&&e.push(i);var o=[];e.forEach(function(e){o.push.apply(o,r.validateAndRegisterProperties(e,n)),r.configurationContributors.push(e),r.registerJSONConfiguration(e),r.updateSchemaForOverrideSettingsConfiguration(e)}),this._onDidRegisterConfiguration.fire(o)},e.prototype.notifyConfigurationSchemaUpdated=function(e){l.notifySchemaChanged(t.editorConfigurationSchemaId)},e.prototype.registerOverrideIdentifiers=function(e){var t;(t=this.overrideIdentifiers).push.apply(t,e),this.updateOverridePropertyPatternKey()},e.prototype.toConfiguration=function(e){for(var r={id:"defaultOverrides",title:n.localize(0,null),properties:{}},i=0,o=e;i<o.length;i++){var s=o[i];for(var a in s.defaults){var u=s.defaults[a];t.OVERRIDE_PROPERTY_PATTERN.test(a)&&"object"==typeof u&&(r.properties[a]={type:"object",default:u,description:n.localize(1,null,a),$ref:t.editorConfigurationSchemaId})}}return Object.keys(r.properties).length?r:null},e.prototype.validateAndRegisterProperties=function(e,n,r,i){ void 0===n&&(n=!0),void 0===r&&(r=2),void 0===i&&(i=!1),r=o.isUndefinedOrNull(e.scope)?r:e.scope,i=e.overridable||i;var s=[],a=e.properties;if(a)for(var l in a){var f=void 0;if(n&&(f=c(l)))console.warn(f),delete a[l];else{var p=a[l],d=p.default;o.isUndefined(d)&&(p.default=u(p.type)),i&&(p.overridable=!0),t.OVERRIDE_PROPERTY_PATTERN.test(l)?p.scope=void 0:p.scope=o.isUndefinedOrNull(p.scope)?r:p.scope,!a[l].hasOwnProperty("included")||a[l].included?(this.configurationProperties[l]=a[l],s.push(l)):(this.excludedConfigurationProperties[l]=a[l],delete a[l])}}var h=e.allOf;if(h)for(var g=0,v=h;g<v.length;g++){var m=v[g];s.push.apply(s,this.validateAndRegisterProperties(m,n,r,i))}return s},e.prototype.getConfigurations=function(){return this.configurationContributors},e.prototype.getConfigurationProperties=function(){return this.configurationProperties},e.prototype.getExcludedConfigurationProperties=function(){return this.excludedConfigurationProperties},e.prototype.registerJSONConfiguration=function(e){ function n(e){var r=e.properties;if(r)for(var i in r)switch(t.allSettings.properties[i]=r[i],r[i].scope){case 1:t.applicationSettings.properties[i]=r[i];break;case 2:t.windowSettings.properties[i]=r[i];break;case 3:t.resourceSettings.properties[i]=r[i]}var o=e.allOf;o&&o.forEach(n)}n(e),this._onDidSchemaChange.fire()},e.prototype.updateSchemaForOverrideSettingsConfiguration=function(e){e.id!==p&&(this.update(e),l.registerSchema(t.editorConfigurationSchemaId,this.editorConfigurationSchema))},e.prototype.updateOverridePropertyPatternKey=function(){var e=t.allSettings.patternProperties[this.overridePropertyPattern];e||(e={type:"object",description:n.localize(2,null),errorMessage:"Unknown Identifier. Use language identifiers",$ref:t.editorConfigurationSchemaId}),delete t.allSettings.patternProperties[this.overridePropertyPattern],delete t.applicationSettings.patternProperties[this.overridePropertyPattern],delete t.windowSettings.patternProperties[this.overridePropertyPattern], delete t.resourceSettings.patternProperties[this.overridePropertyPattern],this.computeOverridePropertyPattern(),t.allSettings.patternProperties[this.overridePropertyPattern]=e,t.applicationSettings.patternProperties[this.overridePropertyPattern]=e,t.windowSettings.patternProperties[this.overridePropertyPattern]=e,t.resourceSettings.patternProperties[this.overridePropertyPattern]=e,this._onDidSchemaChange.fire()},e.prototype.update=function(e){var t=this,n=e.properties;if(n)for(var r in n)n[r].overridable&&(this.editorConfigurationSchema.properties[r]=this.getConfigurationProperties()[r]);var i=e.allOf;i&&i.forEach(function(e){return t.update(e)})},e.prototype.computeOverridePropertyPattern=function(){this.overridePropertyPattern=this.overrideIdentifiers.length?h.replace("${0}",this.overrideIdentifiers.map(function(e){return s.createRegExp(e,!1).source}).join("|")):d},e}(),p="override",d="\\[.*\\]$",h="\\[(${0})\\]$";t.OVERRIDE_PROPERTY_PATTERN=new RegExp(d),t.getDefaultValue=u;var g=new f ;i.Registry.add(t.Extensions.Configuration,g),t.validateProperty=c,t.getScopes=function(){for(var e={},t=g.getConfigurationProperties(),n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];e[i]=t[i].scope}return e.launch=3,e.task=3,e}}),define(e[13],t([0,1,6,3,22,14,2,15]),function(e,t,n,r,i,o,s,a){"use strict";function u(e,t){var n=Object.create(null);for(var r in e)c(n,r,e[r],t);return n}function c(e,t,n,r){for(var i=t.split("."),o=i.pop(),s=e,a=0;a<i.length;a++){var u=i[a],c=s[u];switch(typeof c){case"undefined":c=s[u]=Object.create(null);break;case"object":break;default:return void r("Ignoring "+t+" as "+i.slice(0,a+1).join(".")+" is "+JSON.stringify(c))}s=c}"object"==typeof s?s[o]=n:r("Ignoring "+t+" as "+i.join(".")+" is "+JSON.stringify(s))}function l(e,t){var n=t.shift();if(0!==t.length){if(-1!==Object.keys(e).indexOf(n)){var r=e[n];"object"!=typeof r||Array.isArray(r)||(l(r,t),0===Object.keys(r).length&&delete e[n])}}else delete e[n]}function f(e,t,n){var r=function(e,t){for(var n=e,r=0;r<t.length;r++){ if("object"!=typeof n||null===n)return;n=n[t[r]]}return n}(e,t.split("."));return void 0===r?n:r}function p(e,t,n){Object.keys(t).forEach(function(i){i in e?r.isObject(e[i])&&r.isObject(t[i])?p(e[i],t[i],n):n&&(e[i]=t[i]):e[i]=t[i]})}function d(e){return e.substring(1,e.length-1)}Object.defineProperty(t,"__esModule",{value:!0}),t.IConfigurationService=s.createDecorator("configurationService"),t.isConfigurationOverrides=function(e){return e&&"object"==typeof e&&(!e.overrideIdentifier||"string"==typeof e.overrideIdentifier)&&(!e.resource||e.resource instanceof i.URI)};!function(e){e[e.USER=1]="USER",e[e.WORKSPACE=2]="WORKSPACE",e[e.WORKSPACE_FOLDER=3]="WORKSPACE_FOLDER",e[e.DEFAULT=4]="DEFAULT",e[e.MEMORY=5]="MEMORY"}(t.ConfigurationTarget||(t.ConfigurationTarget={})),t.ConfigurationTargetToString=function(e){switch(e){case 1:return"USER";case 2:return"WORKSPACE";case 3:return"WORKSPACE_FOLDER";case 4:return"DEFAULT";case 5:return"MEMORY"}},t.compare=function(e,t){for(var r=t.keys.filter(function(t){ return-1===e.keys.indexOf(t)}),i=e.keys.filter(function(e){return-1===t.keys.indexOf(e)}),o=[],s=0,a=e.keys;s<a.length;s++){var u=a[s],c=f(e.contents,u),l=f(t.contents,u);n.equals(c,l)||o.push(u)}return{added:r,removed:i,updated:o}},t.toOverrides=function(e,t){for(var n=[],r=o.Registry.as(a.Extensions.Configuration).getConfigurationProperties(),i=0,s=Object.keys(e);i<s.length;i++){var c=s[i];if(a.OVERRIDE_PROPERTY_PATTERN.test(c)){var l={};for(var f in e[c])r[f]&&r[f].overridable&&(l[f]=e[c][f]);n.push({identifiers:[d(c).trim()],contents:u(l,t)})}}return n},t.toValuesTree=u,t.addToValueTree=c,t.removeFromValueTree=function(e,t){l(e,t.split("."))},t.getConfigurationValue=f,t.merge=p,t.getConfigurationKeys=function(){var e=o.Registry.as(a.Extensions.Configuration).getConfigurationProperties();return Object.keys(e)},t.getDefaultValues=function(){var e=Object.create(null),t=o.Registry.as(a.Extensions.Configuration).getConfigurationProperties();for(var n in t)c(e,n,t[n].default,function(e){ return console.error("Conflict in default settings: "+e)});return e},t.overrideIdentifierFromKey=d,t.keyFromOverrideIdentifier=function(e){return"["+e+"]"}}),define(e[40],t([0,1,37,33,19,3,6,15,13]),function(e,t,n,r,i,s,a,u,c){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var l=function(){function e(e,t,n){void 0===e&&(e={}),void 0===t&&(t=[]),void 0===n&&(n=[]),this._contents=e,this._keys=t,this._overrides=n,this.isFrozen=!1}return Object.defineProperty(e.prototype,"contents",{get:function(){return this.checkAndFreeze(this._contents)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"overrides",{get:function(){return this.checkAndFreeze(this._overrides)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"keys",{get:function(){return this.checkAndFreeze(this._keys)},enumerable:!0,configurable:!0}),e.prototype.getValue=function(e){return e?c.getConfigurationValue(this.contents,e):this.contents},e.prototype.override=function(t){ var n=this.getContentsForOverrideIdentifer(t);if(!n||"object"!=typeof n||!Object.keys(n).length)return this;for(var r={},o=0,s=i.distinct(Object.keys(this.contents).concat(Object.keys(n)));o<s.length;o++){var u=s[o],c=this.contents[u],l=n[u];l&&("object"==typeof c&&"object"==typeof l?(c=a.deepClone(c),this.mergeContents(c,l)):c=l),r[u]=c}return new e(r)},e.prototype.merge=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var r=a.deepClone(this.contents),o=a.deepClone(this.overrides),s=this.keys.slice(),u=0,c=t;u<c.length;u++){var l=c[u];this.mergeContents(r,l.contents);for(var f=function(e){var t=o.filter(function(t){return i.equals(t.identifiers,e.identifiers)})[0];t?p.mergeContents(t.contents,e.contents):o.push(a.deepClone(e))},p=this,d=0,h=l.overrides;d<h.length;d++){f(h[d])}for(var g=0,v=l.keys;g<v.length;g++){var m=v[g];-1===s.indexOf(m)&&s.push(m)}}return new e(r,s,o)},e.prototype.freeze=function(){return this.isFrozen=!0,this},e.prototype.mergeContents=function(e,t){ for(var n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];i in e&&s.isObject(e[i])&&s.isObject(t[i])?this.mergeContents(e[i],t[i]):e[i]=a.deepClone(t[i])}},e.prototype.checkAndFreeze=function(e){return this.isFrozen&&!Object.isFrozen(e)?a.deepFreeze(e):e},e.prototype.getContentsForOverrideIdentifer=function(e){for(var t=0,n=this.overrides;t<n.length;t++){var r=n[t];if(-1!==r.identifiers.indexOf(e))return r.contents}return null},e.prototype.toJSON=function(){return{contents:this.contents,overrides:this.overrides,keys:this.keys}},e.prototype.setValue=function(e,t){this.addKey(e),c.addToValueTree(this.contents,e,t,function(e){throw new Error(e)})},e.prototype.removeValue=function(e){this.removeKey(e)&&c.removeFromValueTree(this.contents,e)},e.prototype.addKey=function(e){for(var t=this.keys.length,n=0;n<t;n++)0===e.indexOf(this.keys[n])&&(t=n);this.keys.splice(t,1,e)},e.prototype.removeKey=function(e){var t=this.keys.indexOf(e);return-1!==t&&(this.keys.splice(t,1),!0)},e}();t.ConfigurationModel=l ;var f=function(e){function t(){for(var t=c.getDefaultValues(),n=c.getConfigurationKeys(),r=[],i=0,o=Object.keys(t);i<o.length;i++){var s=o[i];u.OVERRIDE_PROPERTY_PATTERN.test(s)&&r.push({identifiers:[c.overrideIdentifierFromKey(s).trim()],contents:c.toValuesTree(t[s],function(e){return console.error("Conflict in default settings file: "+e)})})}return e.call(this,t,n,r)||this}return o(t,e),t}(l);t.DefaultConfigurationModel=f;var p=function(){function e(e){this._name=e,this._configurationModel=null,this._parseErrors=[]}return Object.defineProperty(e.prototype,"configurationModel",{get:function(){return this._configurationModel||new l},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"errors",{get:function(){return this._parseErrors},enumerable:!0,configurable:!0}),e.prototype.parse=function(e){if(e){var t=this.parseContent(e),n=this.parseRaw(t);this._configurationModel=new l(n.contents,n.keys,n.overrides)}},e.prototype.parseContent=function(e){function t(e){ Array.isArray(o)?o.push(e):i&&(o[i]=e)}var r={},i=null,o=[],s=[],a=[],u={onObjectBegin:function(){var e={};t(e),s.push(o),o=e,i=null},onObjectProperty:function(e){i=e},onObjectEnd:function(){o=s.pop()},onArrayBegin:function(){var e=[];t(e),s.push(o),o=e,i=null},onArrayEnd:function(){o=s.pop()},onLiteralValue:t,onError:function(e,t,n){a.push({error:e,offset:t,length:n})}};if(e)try{n.visit(e,u),r=o[0]||{}}catch(e){console.error("Error while parsing settings file "+this._name+": "+e),this._parseErrors=[e]}return r},e.prototype.parseRaw=function(e){var t=this;return{contents:c.toValuesTree(e,function(e){return console.error("Conflict in settings file "+t._name+": "+e)}),keys:Object.keys(e),overrides:c.toOverrides(e,function(e){return console.error("Conflict in settings file "+t._name+": "+e)})}},e}();t.ConfigurationModelParser=p;var d=function(){function e(e,t,n,i,o,s,a){void 0===n&&(n=new l),void 0===i&&(i=new r.ResourceMap),void 0===o&&(o=new l),void 0===s&&(s=new r.ResourceMap),void 0===a&&(a=!0), this._defaultConfiguration=e,this._userConfiguration=t,this._workspaceConfiguration=n,this._folderConfigurations=i,this._memoryConfiguration=o,this._memoryConfigurationByResource=s,this._freeze=a,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations=new r.ResourceMap}return e.prototype.getValue=function(e,t,n){return this.getConsolidateConfigurationModel(t,n).getValue(e)},e.prototype.updateValue=function(e,t,n){void 0===n&&(n={});var r;n.resource?(r=this._memoryConfigurationByResource.get(n.resource))||(r=new l,this._memoryConfigurationByResource.set(n.resource,r)):r=this._memoryConfiguration,void 0===t?r.removeValue(e):r.setValue(e,t),n.resource||(this._workspaceConsolidatedConfiguration=null)},e.prototype.inspect=function(e,t,n){var r=this.getConsolidateConfigurationModel(t,n),i=this.getFolderConfigurationModelForResource(t.resource,n),o=t.resource?this._memoryConfigurationByResource.get(t.resource)||this._memoryConfiguration:this._memoryConfiguration;return{ default:t.overrideIdentifier?this._defaultConfiguration.freeze().override(t.overrideIdentifier).getValue(e):this._defaultConfiguration.freeze().getValue(e),user:t.overrideIdentifier?this._userConfiguration.freeze().override(t.overrideIdentifier).getValue(e):this._userConfiguration.freeze().getValue(e),workspace:n?t.overrideIdentifier?this._workspaceConfiguration.freeze().override(t.overrideIdentifier).getValue(e):this._workspaceConfiguration.freeze().getValue(e):void 0,workspaceFolder:i?t.overrideIdentifier?i.freeze().override(t.overrideIdentifier).getValue(e):i.freeze().getValue(e):void 0,memory:t.overrideIdentifier?o.freeze().override(t.overrideIdentifier).getValue(e):o.freeze().getValue(e),value:r.getValue(e)}},e.prototype.keys=function(e){var t=this.getFolderConfigurationModelForResource(void 0,e);return{default:this._defaultConfiguration.freeze().keys,user:this._userConfiguration.freeze().keys,workspace:this._workspaceConfiguration.freeze().keys,workspaceFolder:t?t.freeze().keys:[]}}, e.prototype.updateDefaultConfiguration=function(e){this._defaultConfiguration=e,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()},e.prototype.updateUserConfiguration=function(e){this._userConfiguration=e,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()},e.prototype.updateWorkspaceConfiguration=function(e){this._workspaceConfiguration=e,this._workspaceConsolidatedConfiguration=null,this._foldersConsolidatedConfigurations.clear()},e.prototype.updateFolderConfiguration=function(e,t){this._folderConfigurations.set(e,t),this._foldersConsolidatedConfigurations.delete(e)},e.prototype.deleteFolderConfiguration=function(e){this.folders.delete(e),this._foldersConsolidatedConfigurations.delete(e)},Object.defineProperty(e.prototype,"defaults",{get:function(){return this._defaultConfiguration},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"user",{get:function(){return this._userConfiguration},enumerable:!0, configurable:!0}),Object.defineProperty(e.prototype,"workspace",{get:function(){return this._workspaceConfiguration},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"folders",{get:function(){return this._folderConfigurations},enumerable:!0,configurable:!0}),e.prototype.getConsolidateConfigurationModel=function(e,t){var n=this.getConsolidatedConfigurationModelForResource(e,t);return e.overrideIdentifier?n.override(e.overrideIdentifier):n},e.prototype.getConsolidatedConfigurationModelForResource=function(e,t){var n=e.resource,r=this.getWorkspaceConsolidatedConfiguration();if(t&&n){var i=t.getFolder(n);i&&(r=this.getFolderConsolidatedConfiguration(i.uri)||r);var o=this._memoryConfigurationByResource.get(n);o&&(r=r.merge(o))}return r},e.prototype.getWorkspaceConsolidatedConfiguration=function(){return this._workspaceConsolidatedConfiguration||(this._workspaceConsolidatedConfiguration=this._defaultConfiguration.merge(this._userConfiguration,this._workspaceConfiguration,this._memoryConfiguration), this._freeze&&(this._workspaceConfiguration=this._workspaceConfiguration.freeze())),this._workspaceConsolidatedConfiguration},e.prototype.getFolderConsolidatedConfiguration=function(e){var t=this._foldersConsolidatedConfigurations.get(e);if(!t){var n=this.getWorkspaceConsolidatedConfiguration(),r=this._folderConfigurations.get(e);r?(t=n.merge(r),this._freeze&&(t=t.freeze()),this._foldersConsolidatedConfigurations.set(e,t)):t=n}return t},e.prototype.getFolderConfigurationModelForResource=function(e,t){if(t&&e){var n=t.getFolder(e);if(n)return this._folderConfigurations.get(n.uri)}return null},e.prototype.toData=function(){var e=this;return{defaults:{contents:this._defaultConfiguration.contents,overrides:this._defaultConfiguration.overrides,keys:this._defaultConfiguration.keys},user:{contents:this._userConfiguration.contents,overrides:this._userConfiguration.overrides,keys:this._userConfiguration.keys},workspace:{contents:this._workspaceConfiguration.contents,overrides:this._workspaceConfiguration.overrides, keys:this._workspaceConfiguration.keys},folders:this._folderConfigurations.keys().reduce(function(t,n){var r=e._folderConfigurations.get(n),i=r.contents,o=r.overrides,s=r.keys;return t[n.toString()]={contents:i,overrides:o,keys:s},t},Object.create({})),isComplete:!0}},e.prototype.allKeys=function(e){var t=this.keys(e),n=t.default.slice(),r=function(e){for(var t=0,r=e;t<r.length;t++){var i=r[t];-1===n.indexOf(i)&&n.push(i)}};r(t.user),r(t.workspace);for(var i=0,o=this.folders.keys();i<o.length;i++){var s=o[i];r(this.folders.get(s).keys)}return n},e}();t.Configuration=d;var h=function(){function e(){}return e.prototype.doesConfigurationContains=function(e,t){for(var n,r,i=e.contents,o=c.toValuesTree((n={},n[t]=!0,n),function(){});"object"==typeof o&&(r=Object.keys(o)[0]);){if(!(i=i[r]))return!1;o=o[r]}return!0},e.prototype.updateKeys=function(e,t,n){for(var r=0,i=t;r<i.length;r++){var o=i[r];e.setValue(o,{})}},e}();t.AbstractConfigurationChangeEvent=h;var g=function(e){function t(t,n){void 0===t&&(t=new l), void 0===n&&(n=new r.ResourceMap);var i=e.call(this)||this;return i._changedConfiguration=t,i._changedConfigurationByResource=n,i}return o(t,e),Object.defineProperty(t.prototype,"changedConfiguration",{get:function(){return this._changedConfiguration},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"changedConfigurationByResource",{get:function(){return this._changedConfigurationByResource},enumerable:!0,configurable:!0}),t.prototype.change=function(e,n){if(e instanceof t){this._changedConfiguration=this._changedConfiguration.merge(e._changedConfiguration);for(var r=0,i=e._changedConfigurationByResource.keys();r<i.length;r++){var o=i[r],s=this.getOrSetChangedConfigurationForResource(o);s=s.merge(e._changedConfigurationByResource.get(o)),this._changedConfigurationByResource.set(o,s)}}else this.changeWithKeys(e,n);return this},t.prototype.telemetryData=function(e,t){return this._source=e,this._sourceConfig=t,this},Object.defineProperty(t.prototype,"affectedKeys",{get:function(){ var e=this._changedConfiguration.keys.slice();return this._changedConfigurationByResource.forEach(function(t){return e.push.apply(e,t.keys)}),i.distinct(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"source",{get:function(){return this._source},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"sourceConfig",{get:function(){return this._sourceConfig},enumerable:!0,configurable:!0}),t.prototype.affectsConfiguration=function(e,t){var n=[this._changedConfiguration];if(t){var r=this._changedConfigurationByResource.get(t);r&&n.push(r)}else n.push.apply(n,this._changedConfigurationByResource.values());for(var i=0,o=n;i<o.length;i++){var s=o[i];if(this.doesConfigurationContains(s,e))return!0}return!1},t.prototype.changeWithKeys=function(e,t){var n=t?this.getOrSetChangedConfigurationForResource(t):this._changedConfiguration;this.updateKeys(n,e)},t.prototype.getOrSetChangedConfigurationForResource=function(e){var t=this._changedConfigurationByResource.get(e);return t||(t=new l, this._changedConfigurationByResource.set(e,t)),t},t}(h);t.ConfigurationChangeEvent=g}),define(e[72],t([0,1,11,23,40,48,9]),function(e,t,n,r,i,s,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var u=function(e){function t(t){var n=e.call(this)||this;return n.settingsPath=t,n._onDidChangeConfiguration=n._register(new a.Emitter),n.onDidChangeConfiguration=n._onDidChangeConfiguration.event,n}return o(t,e),t.prototype.initialize=function(){var e=this;return this.initializePromise||(this.initializePromise=new Promise(function(t,n){e.userConfigModelWatcher=new s.ConfigWatcher(e.settingsPath,{changeBufferDelay:300,onError:function(e){return r.onUnexpectedError(e)},defaultConfig:new i.ConfigurationModelParser(e.settingsPath),parse:function(t,n){var r=new i.ConfigurationModelParser(e.settingsPath);return r.parse(t),r.errors.slice(),r},initCallback:function(){return t(void 0)}}),e._register(e.userConfigModelWatcher),e._register(e.userConfigModelWatcher.onDidUpdateConfiguration(function(){ return e._onDidChangeConfiguration.fire(e.userConfigModelWatcher.getConfig().configurationModel)}))})),this.initializePromise.then(function(){return e.userConfigModelWatcher.getConfig().configurationModel})},t.prototype.initializeSync=function(){return this.initialize(),this.userConfigModelWatcher.getConfig().configurationModel},t.prototype.reload=function(){var e=this;return this.initialize().then(function(){return new Promise(function(t){return e.userConfigModelWatcher.reload(function(e){return t(e.configurationModel)})})})},t}(n.Disposable);t.UserConfiguration=u});var a=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};define(e[73],t([0,1,14,15,11,13,40,9,17,72]),function(e,t,n,r,i,u,c,l,f,p){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var d=function(e){function t(t){var i=e.call(this)||this;i._onDidChangeConfiguration=i._register(new l.Emitter),i.onDidChangeConfiguration=i._onDidChangeConfiguration.event, i.userConfiguration=i._register(new p.UserConfiguration(t.appSettingsPath));var o=new c.DefaultConfigurationModel,s=i.userConfiguration.initializeSync();return i._configuration=new c.Configuration(o,s),i._register(i.userConfiguration.onDidChangeConfiguration(function(e){return i.onDidChangeUserConfiguration(e)})),i._register(n.Registry.as(r.Extensions.Configuration).onDidRegisterConfiguration(function(e){return i.onDidRegisterConfiguration(e)})),i}return o(t,e),Object.defineProperty(t.prototype,"configuration",{get:function(){return this._configuration},enumerable:!0,configurable:!0}),t.prototype.getConfigurationData=function(){return this.configuration.toData()},t.prototype.getValue=function(e,t){var n="string"==typeof e?e:void 0,r=u.isConfigurationOverrides(e)?e:u.isConfigurationOverrides(t)?t:{};return this.configuration.getValue(n,r,null)},t.prototype.updateValue=function(e,t,n,r){return Promise.reject(new Error("not supported"))},t.prototype.inspect=function(e){ return this.configuration.inspect(e,{},null)},t.prototype.keys=function(){return this.configuration.keys(null)},t.prototype.reloadConfiguration=function(e){var t=this;return e?Promise.resolve(void 0):this.userConfiguration.reload().then(function(e){return t.onDidChangeUserConfiguration(e)})},t.prototype.onDidChangeUserConfiguration=function(e){var t=u.compare(this._configuration.user,e),n=t.added,r=t.updated,i=t.removed,o=n.concat(r,i);o.length&&(this._configuration.updateUserConfiguration(e),this.trigger(o,1))},t.prototype.onDidRegisterConfiguration=function(e){this._configuration.updateDefaultConfiguration(new c.DefaultConfigurationModel),this.trigger(e,4)},t.prototype.trigger=function(e,t){this._onDidChangeConfiguration.fire((new c.ConfigurationChangeEvent).change(e).telemetryData(t,this.getTargetConfiguration(t)))},t.prototype.getTargetConfiguration=function(e){switch(e){case 4:return this._configuration.defaults.contents;case 1:return this._configuration.user.contents}return{}}, t=s([a(0,f.IEnvironmentService)],t)}(i.Disposable);t.ConfigurationService=d}),define(e[41],t([0,1,74,2,15,14]),function(e,t,n,r,i,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IRequestService=r.createDecorator("requestService2"),o.Registry.as(i.Extensions.Configuration).registerConfiguration({id:"http",order:15,title:n.localize(0,null),type:"object",properties:{"http.proxy":{type:"string",pattern:"^https?://([^:]*(:[^@]*)?@)?([^:]+)(:\\d+)?/?$|^$",description:n.localize(1,null)},"http.proxyStrictSSL":{type:"boolean",default:!0,description:n.localize(2,null)},"http.proxyAuthorization":{type:["null","string"],default:null,description:n.localize(3,null)},"http.proxySupport":{type:"string",enum:["off","on","override"],enumDescriptions:[n.localize(4,null),n.localize(5,null),n.localize(6,null)],default:"override",description:n.localize(7,null)}}})}),define(e[75],t([0,1,2]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}), t.IStateService=n.createDecorator("stateService")}),define(e[76],t([0,1,5,24,17,39,3,7,12]),function(e,t,n,r,i,o,u,c,l){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var f=function(){function e(e,t){this.dbPath=e,this.onError=t,this._database=null,this.lastFlushedSerializedDatabase=null}return Object.defineProperty(e.prototype,"database",{get:function(){return this._database||(this._database=this.loadSync()),this._database},enumerable:!0,configurable:!0}),e.prototype.init=function(){var e=this;return l.readFile(this.dbPath).then(function(t){try{e.lastFlushedSerializedDatabase=t.toString(),e._database=JSON.parse(e.lastFlushedSerializedDatabase)}catch(t){e._database={}}},function(t){"ENOENT"!==t.code&&e.onError(t),e._database={}})},e.prototype.loadSync=function(){try{return this.lastFlushedSerializedDatabase=r.readFileSync(this.dbPath).toString(),JSON.parse(this.lastFlushedSerializedDatabase)}catch(e){return"ENOENT"!==e.code&&this.onError(e),{}}},e.prototype.getItem=function(e,t){ var n=this.database[e];return u.isUndefinedOrNull(n)?t:n},e.prototype.setItem=function(e,t){if(u.isUndefinedOrNull(t))return this.removeItem(e);("string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t||this.database[e]!==t)&&(this.database[e]=t,this.saveSync())},e.prototype.removeItem=function(e){u.isUndefined(this.database[e])||(this.database[e]=void 0,this.saveSync())},e.prototype.saveSync=function(){var e=JSON.stringify(this.database,null,4);if(e!==this.lastFlushedSerializedDatabase)try{o.writeFileAndFlushSync(this.dbPath,e),this.lastFlushedSerializedDatabase=e}catch(e){this.onError(e)}},e}();t.FileStorage=f;var p=function(){function e(t,r){this.fileStorage=new f(n.join(t.userDataPath,e.STATE_FILE),function(e){return r.error(e)})}return e.prototype.init=function(){return this.fileStorage.init()},e.prototype.getItem=function(e,t){return this.fileStorage.getItem(e,t)},e.prototype.setItem=function(e,t){this.fileStorage.setItem(e,t)},e.prototype.removeItem=function(e){this.fileStorage.removeItem(e)}, e.STATE_FILE="storage.json",e=s([a(0,i.IEnvironmentService),a(1,c.ILogService)],e)}();t.StateService=p}),define(e[27],t([0,1,2]),function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ITelemetryService=n.createDecorator("telemetryService")}),define(e[78],t([0,1,77,10,2,13,15,11,6,14]),function(e,t,n,r,i,o,u,c,l,f){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var p=function(){function e(e,t){this._configurationService=t,this._disposables=[],this._cleanupPatterns=[],this._appender=e.appender,this._commonProperties=e.commonProperties||Promise.resolve({}),this._piiPaths=e.piiPaths||[],this._userOptIn=!0,this._cleanupPatterns=[/file:\/\/\/.*?\/resources\/app\//gi];for(var n=0,i=this._piiPaths;n<i.length;n++){var o=i[n];this._cleanupPatterns.push(new RegExp(r.escapeRegExpCharacters(o),"gi"))}this._configurationService&&(this._updateUserOptIn(),this._configurationService.onDidChangeConfiguration(this._updateUserOptIn,this,this._disposables),this.publicLog("optInStatus",{ optIn:this._userOptIn}))}return e.prototype._updateUserOptIn=function(){var e=this._configurationService.getValue(d);this._userOptIn=e?e.enableTelemetry:this._userOptIn},Object.defineProperty(e.prototype,"isOptedIn",{get:function(){return this._userOptIn},enumerable:!0,configurable:!0}),e.prototype.getTelemetryInfo=function(){return this._commonProperties.then(function(e){return{sessionId:e.sessionID,instanceId:e["common.instanceId"],machineId:e["common.machineId"]}})},e.prototype.dispose=function(){this._disposables=c.dispose(this._disposables)},e.prototype.publicLog=function(e,t,n){var r=this;return this._userOptIn?this._commonProperties.then(function(i){t=l.mixin(t,i),t=l.cloneAndChange(t,function(e){if("string"==typeof e)return r._cleanupInfo(e,n)}),r._appender.log(e,t)},function(e){console.error(e)}):Promise.resolve(void 0)},e.prototype._cleanupInfo=function(e,t){var n=e;if(t){for(var r=[],i=0,o=this._cleanupPatterns;i<o.length;i++)for(d=o[i];;){var s=d.exec(e);if(!s)break;r.push([s.index,d.lastIndex])} var a=/^[\\\/]?(node_modules|node_modules\.asar)[\\\/]/,u=/(file:\/\/)?([a-zA-Z]:(\\\\|\\|\/)|(\\\\|\\|\/))?([\w-\._]+(\\\\|\\|\/))+[\w-\._]*/g,c=0;n="";for(var l=function(){var t=u.exec(e);if(!t)return"break";!a.test(t[0])&&r.every(function(e){var n=e[0],r=e[1];return t.index<n||t.index>=r})&&(n+=e.substring(c,t.index)+"<REDACTED: user-file-path>",c=u.lastIndex)};;){if("break"===l())break}c<e.length&&(n+=e.substr(c))}for(var f=0,p=this._cleanupPatterns;f<p.length;f++){var d=p[f];n=n.replace(d,"")}return n},e.IDLE_START_EVENT_NAME="UserIdleStart",e.IDLE_STOP_EVENT_NAME="UserIdleStop",e=s([a(1,i.optional(o.IConfigurationService))],e)}();t.TelemetryService=p;var d="telemetry";f.Registry.as(u.Extensions.Configuration).registerConfiguration({id:d,order:110,type:"object",title:n.localize(0,null),properties:{"telemetry.enableTelemetry":{type:"boolean",description:n.localize(1,null),default:!0,tags:["usesOnlineServices"]}}})}),define(e[79],t([0,1,50,25,13,7]),function(e,t,n,r,i,o){"use strict";function u(e,t){ return t.onDidChangeConfiguration(function(t){4!==t.source&&(e.publicLog("updateConfiguration",{configurationSource:i.ConfigurationTargetToString(t.source),configurationKeys:function(e){if(!e)return[];var t=[];return c(t,"",e),t}(t.sourceConfig)}),e.publicLog("updateConfigurationValues",{configurationSource:i.ConfigurationTargetToString(t.source),configurationValues:function(e,t){if(!e)return[];return t.reduce(function(t,n){var r,i=n.split(".").reduce(function(e,t){return e&&"object"==typeof e?e[t]:void 0},e);return void 0!==i&&t.push((r={},r[n]=i,r)),t},[])}(t.sourceConfig,f)}))})}function c(e,t,n){n&&"object"==typeof n&&!Array.isArray(n)?Object.keys(n).forEach(function(r){return c(e,t?t+"."+r:r,n[r])}):e.push(t)}Object.defineProperty(t,"__esModule",{value:!0}),t.NullTelemetryService=new(function(){function e(){}return e.prototype.publicLog=function(e,t){return Promise.resolve(void 0)},e.prototype.getTelemetryInfo=function(){return Promise.resolve({instanceId:"someValue.instanceId", sessionId:"someValue.sessionId",machineId:"someValue.machineId"})},e}()),t.combinedAppender=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return{log:function(t,n){return e.forEach(function(e){return e.log(t,n)})},dispose:function(){return Promise.all(e.map(function(e){return e.dispose()}))}}},t.NullAppender={log:function(){return null},dispose:function(){return Promise.resolve(null)}};var l=function(){function e(e){this._logService=e,this.commonPropertiesRegex=/^sessionID$|^version$|^timestamp$|^commitHash$|^common\./}return e.prototype.dispose=function(){return Promise.resolve(void 0)},e.prototype.log=function(e,t){var n=this,r={};Object.keys(t).forEach(function(e){n.commonPropertiesRegex.test(e)||(r[e]=t[e])}),this._logService.trace("telemetry/"+e,r)},e=s([a(0,o.ILogService)],e)}();t.LogAppender=l,t.telemetryURIDescriptor=function(e,t){var i=e&&e.fsPath;return i?{mimeType:n.guessMimeTypes(i).join(", "),scheme:e.scheme,ext:r.extname(i),path:t(i)}:{}} ;var f=["editor.fontFamily","editor.fontWeight","editor.fontSize","editor.lineHeight","editor.letterSpacing","editor.lineNumbers","editor.rulers","editor.wordSeparators","editor.tabSize","editor.insertSpaces","editor.detectIndentation","editor.roundedSelection","editor.scrollBeyondLastLine","editor.minimap.enabled","editor.minimap.side","editor.minimap.renderCharacters","editor.minimap.maxColumn","editor.find.seedSearchStringFromSelection","editor.find.autoFindInSelection","editor.wordWrap","editor.wordWrapColumn","editor.wrappingIndent","editor.mouseWheelScrollSensitivity","editor.multiCursorModifier","editor.quickSuggestions","editor.quickSuggestionsDelay","editor.parameterHints.enabled","editor.parameterHints.cycle","editor.autoClosingBrackets","editor.autoClosingQuotes","editor.autoSurround","editor.autoIndent","editor.formatOnType","editor.formatOnPaste","editor.suggestOnTriggerCharacters","editor.acceptSuggestionOnEnter","editor.acceptSuggestionOnCommitCharacter","editor.snippetSuggestions","editor.emptySelectionClipboard","editor.wordBasedSuggestions","editor.suggestSelection","editor.suggestFontSize","editor.suggestLineHeight","editor.tabCompletion","editor.selectionHighlight","editor.occurrencesHighlight","editor.overviewRulerLanes","editor.overviewRulerBorder","editor.cursorBlinking","editor.cursorSmoothCaretAnimation","editor.cursorStyle","editor.mouseWheelZoom","editor.fontLigatures","editor.hideCursorInOverviewRuler","editor.renderWhitespace","editor.renderControlCharacters","editor.renderIndentGuides","editor.renderLineHighlight","editor.codeLens","editor.folding","editor.showFoldingControls","editor.matchBrackets","editor.glyphMargin","editor.useTabStops","editor.trimAutoWhitespace","editor.stablePeek","editor.dragAndDrop","editor.formatOnSave","editor.colorDecorators","breadcrumbs.enabled","breadcrumbs.filePath","breadcrumbs.symbolPath","breadcrumbs.symbolSortOrder","breadcrumbs.useQuickPick","explorer.openEditors.visible","extensions.autoUpdate","files.associations","files.autoGuessEncoding","files.autoSave","files.autoSaveDelay","files.encoding","files.eol","files.hotExit","files.trimTrailingWhitespace","git.confirmSync","git.enabled","http.proxyStrictSSL","javascript.validate.enable","php.builtInCompletions.enable","php.validate.enable","php.validate.run","terminal.integrated.fontFamily","window.openFilesInNewWindow","window.restoreWindows","window.zoomLevel","workbench.editor.enablePreview","workbench.editor.enablePreviewFromQuickOpen","workbench.editor.showTabs","workbench.editor.highlightModifiedTabs","workbench.editor.swipeToNavigate","workbench.sideBar.location","workbench.startupEditor","workbench.statusBar.visible","workbench.welcome.enabled"] ;t.configurationTelemetry=u,t.keybindingsTelemetry=function(e,t){return t.onDidUpdateKeybindings(function(t){2===t.source&&t.keybindings&&e.publicLog("updateKeybindings",{bindings:t.keybindings.map(function(e){return{key:e.key,command:e.command,when:e.when,args:!!e.args||void 0}})})})}}),define(e[80],t([0,1,89,3,6,7]),function(e,t,n,r,i,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t,r,i){this._eventPrefix=e,this._defaultData=t,this._logService=i,this._defaultData||(this._defaultData=Object.create(null)),"string"==typeof r?this._aiClient=function(e){var t;return n.defaultClient?(t=new n.TelemetryClient(e)).channel.setUseDiskRetryCaching(!0):(n.setup(e).setAutoCollectRequests(!1).setAutoCollectPerformance(!1).setAutoCollectExceptions(!1).setAutoCollectDependencies(!1).setAutoDependencyCorrelation(!1).setAutoCollectConsole(!1).setInternalLogging(!1,!1).setUseDiskRetryCaching(!0).start(),t=n.defaultClient), 0===e.indexOf("AIF-")&&(t.config.endpointUrl="https://vortex.data.microsoft.com/collect/v1"),t}(r):"function"==typeof r&&(this._aiClient=r())}return e._getData=function(t){var n=Object.create(null),r=Object.create(null),i=Object.create(null);e._flaten(t,i);for(var o in i){var s=i[o=o.length>150?o.substr(o.length-149):o];"number"==typeof s?r[o]=s:"boolean"==typeof s?r[o]=s?1:0:"string"==typeof s?n[o]=s.substring(0,1023):void 0!==s&&null!==s&&(n[o]=s)}return{properties:n,measurements:r}},e._flaten=function(t,n,o,s){if(void 0===o&&(o=0),t)for(var a=0,u=Object.getOwnPropertyNames(t);a<u.length;a++){var c=u[a],l=t[c],f=s?s+c:c;Array.isArray(l)?n[f]=i.safeStringify(l):l instanceof Date?n[f]=l.toISOString():r.isObject(l)?o<2?e._flaten(l,n,o+1,f+"."):n[f]=i.safeStringify(l):n[f]=l}},e.prototype.log=function(t,n){this._aiClient&&(n=i.mixin(n,this._defaultData),n=e._getData(n),this._logService&&this._logService.trace("telemetry/"+t,n),this._aiClient.trackEvent({name:this._eventPrefix+"/"+t,properties:n.properties, measurements:n.measurements}))},e.prototype.dispose=function(){var e=this;if(this._aiClient)return new Promise(function(t){e._aiClient.flush({callback:function(){e._aiClient=void 0,t(void 0)}})})},e=s([a(3,o.ILogService)],e)}();t.AppInsightsAppender=u}),define(e[82],t([0,1,16,26,43,12]),function(e,t,n,r,i,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveCommonProperties=function(e,t,s,a){var u=Object.create(null);u["common.machineId"]=s,u.sessionID=i.generateUuid()+Date.now(),u.commitHash=e,u.version=t,u["common.platformVersion"]=(r.release()||"").replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/,"$1$2$3"),u["common.platform"]=n.PlatformToString(n.platform),u["common.nodePlatform"]=process.platform,u["common.nodeArch"]=process.arch;var c=0,l=Date.now();return Object.defineProperties(u,{timestamp:{get:function(){return new Date},enumerable:!0},"common.timesincesessionstart":{get:function(){return Date.now()-l},enumerable:!0},"common.sequence":{get:function(){return c++},enumerable:!0}}), o.readFile(a,"utf8").then(function(e){return u["common.source"]=e.slice(0,30),u},function(e){return u})}}),define(e[44],t([0,1,71,5,24,21,12,88,87,9]),function(e,t,n,r,i,s,a,u,c,l){"use strict";function f(e,t,o,u,c){var f=s.createCancelablePromise(function(){return Promise.resolve()}),p=0;return l.Event.once(c.onCancellationRequested)(function(){u.debug(t,"Cancelled."),f.cancel(),e.close()}),new Promise(function(u,d){var g=new s.Sequencer,v=function(t){t.isCancellationRequested||(p++,e.readEntry())};e.once("error",d),e.once("close",function(){return f.then(function(){c.isCancellationRequested||e.entryCount===p?u():d(new h("Incomplete",new Error(n.localize(1,null,p,e.entryCount))))},d)}),e.readEntry(),e.on("entry",function(u){if(!c.isCancellationRequested)if(o.sourcePathRegex.test(u.fileName)){var p=u.fileName.replace(o.sourcePathRegex,"");if(/\/$/.test(p)){var h=r.join(t,p);f=s.createCancelablePromise(function(e){return a.mkdirp(h,void 0,e).then(function(){return v(e)}).then(void 0,d)})}else{ var m=s.ninvoke(e,e.openReadStream,u),y=function(e){var t=e.externalFileAttributes>>16||33188;return[448,56,7].map(function(e){return t&e}).reduce(function(e,t){return e+t},61440&t)}(u);f=s.createCancelablePromise(function(e){return g.queue(function(){return m.then(function(o){return function(e,t,o,s,u,c){var f=r.dirname(t),p=r.join(s,f);if(0!==p.indexOf(s))return Promise.reject(new Error(n.localize(0,null,t)));var d,h=r.join(s,t);return l.Event.once(c.onCancellationRequested)(function(){d&&d.destroy()}),Promise.resolve(a.mkdirp(p,void 0,c)).then(function(){return new Promise(function(t,n){if(!c.isCancellationRequested)try{(d=i.createWriteStream(h,{mode:o})).once("close",function(){return t()}),d.once("error",n),e.once("error",n),e.pipe(d)}catch(e){n(e)}})})}(o,p,y,t,0,e).then(function(){return v(e)})})}).then(null,d)})}}else v(c)})})}function p(e,t){return void 0===t&&(t=!1),s.nfcall(u.open,e,t?{lazyEntries:!0}:void 0).then(void 0,function(e){return Promise.reject(function(e){if(e instanceof h)return e ;var t=void 0;return/end of central directory record signature not found/.test(e.message)&&(t="CorruptZip"),new h(t,e)}(e))})}function d(e,t){return function(e,t){return p(e).then(function(e){return new Promise(function(r,i){e.on("entry",function(n){n.fileName===t&&s.ninvoke(e,e.openReadStream,n).then(function(e){return r(e)},function(e){return i(e)})}),e.once("close",function(){return i(new Error(n.localize(2,null,t)))})})})}(e,t).then(function(e){return new Promise(function(t,n){var r=[];e.once("error",n),e.on("data",function(e){return r.push(e)}),e.on("end",function(){return t(Buffer.concat(r))})})})}Object.defineProperty(t,"__esModule",{value:!0});var h=function(e){function t(t,n){var r=this,i=n.message;switch(t){case"CorruptZip":i="Corrupt ZIP: "+i}return r=e.call(this,i)||this,r.type=t,r.cause=n,r}return o(t,e),t}(Error);t.ExtractError=h,t.zip=function(e,t){return new Promise(function(n,r){var o=new c.ZipFile;t.forEach(function(e){ e.contents?o.addBuffer("string"==typeof e.contents?Buffer.from(e.contents,"utf8"):e.contents,e.path):e.localPath&&o.addFile(e.localPath,e.path)}),o.end();var s=i.createWriteStream(e);o.outputStream.pipe(s),o.outputStream.once("error",r),s.once("error",r),s.once("finish",function(){return n(e)})})},t.extract=function(e,t,n,r,i){void 0===n&&(n={});var o=new RegExp(n.sourcePath?"^"+n.sourcePath:""),s=p(e,!0);return n.overwrite&&(s=s.then(function(e){return a.rimraf(t).then(function(){return e})})),s.then(function(e){return f(e,t,{sourcePathRegex:o},r,i)})},t.buffer=d}),define(e[42],t([0,1,45,18,44,69]),function(e,t,n,r,i,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getIdAndVersionFromLocalExtensionId=function(e){var t=r.LOCAL_EXTENSION_ID_REGEX.exec(e);if(t&&t[1]&&t[2]){var i=n.valid(t[2]);if(i)return{id:r.adoptToGalleryExtensionId(t[1]),version:i}}return{id:r.adoptToGalleryExtensionId(e),version:null}},t.getManifest=function(e){return i.buffer(e,"extension/package.json").then(function(e){ try{return JSON.parse(e.toString("utf8"))}catch(e){throw new Error(o.localize(0,null))}})}}),define(e[81],t([0,1,67,5,12,6,11,19,44,28,18,84,17,21,9,45,22,20,16,7,49,85,31,27,32,26,43,52,2,30,35,42]),function(e,t,i,u,c,l,f,p,d,h,g,v,m,y,b,E,S,x,C,P,_,w,I,O,k,j,T,D,L,M,R,A){"use strict";function F(e){return new Promise(function(t,n){try{var r=JSON.parse(e),o=r.__metadata||null;delete r.__metadata,t({manifest:r,metadata:o})}catch(e){n(new Error(i.localize(0,null)))}})}function N(e,t){return g.getLocalExtensionId(e.identifier.id,t)}function U(e){return g.getLocalExtensionId(g.getGalleryExtensionId(e.publisher,e.name),e.version)}Object.defineProperty(t,"__esModule",{value:!0});var z=function(e){function t(t,n){var r=e.call(this,t)||this;return r.code=n,r}return o(t,e),t}(Error);t.ExtensionManagementError=z;var V=function(t){function V(e,n,r,i,o){var s=t.call(this)||this;return s.environmentService=e,s.galleryService=n,s.logService=r,s.downloadService=i,s.telemetryService=o,s.lastReportTimestamp=0, s.installingExtensions=new Map,s.uninstallingExtensions=new Map,s._onInstallExtension=new b.Emitter,s.onInstallExtension=s._onInstallExtension.event,s._onDidInstallExtension=new b.Emitter,s.onDidInstallExtension=s._onDidInstallExtension.event,s._onUninstallExtension=new b.Emitter,s.onUninstallExtension=s._onUninstallExtension.event,s._onDidUninstallExtension=new b.Emitter,s.onDidUninstallExtension=s._onDidUninstallExtension.event,s._devSystemExtensionsPath=null,s._devSystemExtensionsFilePath=null,s.systemExtensionsPath=e.builtinExtensionsPath,s.extensionsPath=e.extensionsPath,s.uninstalledPath=u.join(s.extensionsPath,".obsolete"),s.uninstalledFileLimiter=new y.Queue,s.manifestCache=s._register(new _.ExtensionsManifestCache(e,s)),s.extensionLifecycle=s._register(new w.ExtensionsLifecycle(e,s.logService)),s._register(f.toDisposable(function(){s.installingExtensions.forEach(function(e){return e.cancel()}),s.uninstallingExtensions.forEach(function(e){return e.cancel()}),s.installingExtensions.clear(), s.uninstallingExtensions.clear()})),s}return o(V,t),V.prototype.zip=function(e){return this.logService.trace("ExtensionManagementService#zip",e.identifier.id),this.collectFiles(e).then(function(e){return d.zip(u.join(j.tmpdir(),T.generateUuid()),e)}).then(function(e){return S.URI.file(e)})},V.prototype.unzip=function(e,t){return this.logService.trace("ExtensionManagementService#unzip",e.toString()),this.install(e,t)},V.prototype.collectFiles=function(e){var t=this,i=function(e){return n(t,void 0,void 0,function(){var t,n,o;return r(this,function(r){switch(r.label){case 0:return[4,c.readdir(e)];case 1:return t=r.sent(),t=t.map(function(t){return u.join(e,t)}),[4,Promise.all(t.map(function(e){return c.stat(e)}))];case 2:return n=r.sent(),o=Promise.resolve([]),n.forEach(function(e,n){var r=t[n];e.isFile()&&(o=o.then(function(e){return e.concat([r])})),e.isDirectory()&&(o=o.then(function(e){return i(r).then(function(t){return e.concat(t)})}))}),[2,o]}})})};return i(e.location.fsPath).then(function(t){ return t.map(function(t){return{path:"extension/"+u.relative(e.location.fsPath,t),localPath:t}})})},V.prototype.install=function(e,t){var n=this;return void 0===t&&(t=1),this.logService.trace("ExtensionManagementService#install",e.toString()),y.createCancelablePromise(function(r){return n.downloadVsix(e).then(function(e){var o=u.resolve(e.fsPath);return A.getManifest(o).then(function(e){var s={id:U(e)};return e.engines&&e.engines.vscode&&!k.isEngineValid(e.engines.vscode)?Promise.reject(new Error(i.localize(1,null,s.id,x.default.version))):n.removeIfExists(s.id).then(function(){var i={id:g.getGalleryExtensionId(e.publisher,e.name)};return n.getInstalled(1).then(function(t){var r=t.filter(function(t){return g.areSameExtensions(i,{id:g.getGalleryExtensionIdFromLocal(t)})&&E.gt(t.manifest.version,e.version)})[0];return r?n.uninstall(r,!0):void 0}).then(function(){return n.logService.info("Installing the extension:",s.id),n._onInstallExtension.fire({identifier:s,zipPath:o}), n.getMetadata(g.getGalleryExtensionId(e.publisher,e.name)).then(function(e){return n.installFromZipPath(s,o,e,t,r)},function(e){return n.installFromZipPath(s,o,null,t,r)}).then(function(){return n.logService.info("Successfully installed the extension:",s.id),s},function(e){return n.logService.error("Failed to install the extension:",s.id,e.message),Promise.reject(e)})})},function(t){return Promise.reject(new Error(i.localize(2,null,e.displayName||e.name)))})})})})},V.prototype.downloadVsix=function(e){if(e.scheme===M.Schemas.file)return Promise.resolve(e);if(!this.downloadService)throw new Error("Download service is not available");var t=u.join(j.tmpdir(),T.generateUuid());return this.downloadService.download(e,t).then(function(){return S.URI.file(t)})},V.prototype.removeIfExists=function(e){var t=this;return this.getInstalled(1).then(function(t){return t.filter(function(t){return t.identifier.id===e})[0]}).then(function(e){return e?t.removeExtension(e,"existing"):void 0})}, V.prototype.installFromZipPath=function(e,t,n,r,i){var o=this;return this.toNonCancellablePromise(this.getInstalled().then(function(s){var a=o.getOperation({id:g.getIdFromLocalExtensionId(e.id),uuid:e.uuid},s);return o.installExtension({zipPath:t,id:e.id,metadata:n},r,i).then(function(e){return o.installDependenciesAndPackExtensions(e,null).then(function(){return e},function(t){return o.uninstall(e,!0).then(function(){return Promise.reject(t)},function(){return Promise.reject(t)})})}).then(function(n){return o._onDidInstallExtension.fire({identifier:e,zipPath:t,local:n,operation:a}),n},function(n){return o._onDidInstallExtension.fire({identifier:e,zipPath:t,operation:a,error:n}),Promise.reject(n)})}))},V.prototype.installFromGallery=function(e){return n(this,void 0,void 0,function(){var t,n,i,o,s,a,u,l,f,p,d,h,v,m=this;return r(this,function(r){switch(r.label){case 0:t=(new Date).getTime(),this.logService.info("Installing extension:",e.name),this._onInstallExtension.fire({identifier:e.identifier,gallery:e}), n=function(e,n,r){m.logService.info("Extensions installed successfully:",e.identifier.id),m._onDidInstallExtension.fire({identifier:{id:N(e,e.version),uuid:e.identifier.uuid},gallery:e,local:r,operation:n}),m.reportTelemetry(m.getTelemetryEvent(n),g.getGalleryExtensionTelemetryData(e),(new Date).getTime()-t,void 0)},i=function(e,n,r){var i=r&&r.code?r.code:"unknown";m.logService.error("Failed to install extension:",e.identifier.id,r?r.message:i),m._onDidInstallExtension.fire({identifier:e.identifier,gallery:e,operation:n,error:i}),m.reportTelemetry(m.getTelemetryEvent(n),g.getGalleryExtensionTelemetryData(e),(new Date).getTime()-t,r),r instanceof Error&&(r.name=i)},r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.checkAndGetCompatibleVersion(e)];case 2:return e=r.sent(),[3,4];case 3:return o=r.sent(),i(e,1,o),[2,Promise.reject(o)];case 4:if(s=g.getLocalExtensionId(e.identifier.id,e.version),a=this.installingExtensions.get(s))return[3,10];u=1,a=y.createCancelablePromise(function(e){return l=e, new Promise(function(e,t){f=e,p=t})}),this.installingExtensions.set(s,a),r.label=5;case 5:return r.trys.push([5,9,,10]),[4,this.getInstalled(1)];case 6:return d=r.sent(),(h=d.filter(function(t){return g.areSameExtensions(t.galleryIdentifier,e.identifier)})[0])?(u=2,E.gt(h.manifest.version,e.version)?[4,this.uninstall(h,!0)]:[3,8]):[3,8];case 7:r.sent(),r.label=8;case 8:return this.downloadInstallableExtension(e,u).then(function(e){return m.installExtension(e,1,l).then(function(t){return y.always(c.rimraf(e.zipPath),function(){return null}).then(function(){return t})})}).then(function(e){return m.installDependenciesAndPackExtensions(e,h).then(function(){return e},function(t){return m.uninstall(e,!0).then(function(){return Promise.reject(t)},function(){return Promise.reject(t)})})}).then(function(t){m.installingExtensions.delete(s),n(e,u,t),f(null)},function(t){m.installingExtensions.delete(s),i(e,u,t),p(t)}),[3,10];case 9:return v=r.sent(),this.installingExtensions.delete(s),i(e,u,v),[2,Promise.reject(v)] ;case 10:return[2,a]}})})},V.prototype.checkAndGetCompatibleVersion=function(e){return n(this,void 0,void 0,function(){var t;return r(this,function(n){switch(n.label){case 0:return[4,this.isMalicious(e)];case 1:return n.sent()?[2,Promise.reject(new z(i.localize(3,null),h.INSTALL_ERROR_MALICIOUS))]:[4,this.galleryService.loadCompatibleVersion(e)];case 2:return(t=n.sent())?[2,t]:[2,Promise.reject(new z(i.localize(4,null,e.identifier.id,x.default.version),h.INSTALL_ERROR_INCOMPATIBLE))]}})})},V.prototype.reinstallFromGallery=function(e){var t=this;return this.logService.trace("ExtensionManagementService#reinstallFromGallery",e.identifier.id),this.galleryService.isEnabled()?this.findGalleryExtension(e).then(function(n){return n?t.setUninstalled(e).then(function(){return t.removeUninstalledExtension(e).then(function(){return t.installFromGallery(n)},function(e){return Promise.reject(new Error(i.localize(6,null,I.toErrorMessage(e))))})}):Promise.reject(new Error(i.localize(7,null))) }):Promise.reject(new Error(i.localize(5,null)))},V.prototype.getOperation=function(e,t){return t.some(function(t){return g.areSameExtensions({id:g.getGalleryExtensionIdFromLocal(t),uuid:t.identifier.uuid},e)})?2:1},V.prototype.getTelemetryEvent=function(e){return 2===e?"extensionGallery:update":"extensionGallery:install"},V.prototype.isMalicious=function(e){return this.getExtensionsReport().then(function(t){return g.getMaliciousExtensionsSet(t).has(e.identifier.id)})},V.prototype.downloadInstallableExtension=function(e,t){var n=this,r={id:e.identifier.uuid,publisherId:e.publisherId,publisherDisplayName:e.publisherDisplayName};return this.logService.trace("Started downloading extension:",e.name),this.galleryService.download(e,t).then(function(t){return n.logService.info("Downloaded extension:",e.name,t),A.getManifest(t).then(function(e){return{zipPath:t,id:U(e),metadata:r}},function(e){return Promise.reject(new z(n.joinErrors(e).message,"validating"))})},function(e){ return Promise.reject(new z(n.joinErrors(e).message,"downloading"))})},V.prototype.installExtension=function(e,t,n){var r=this;return this.unsetUninstalledAndGetLocal(e.id).then(function(i){return i||r.extractAndInstall(e,t,n)},function(e){return C.isMacintosh?Promise.reject(new z(i.localize(8,null),"unsetUninstalled")):Promise.reject(new z(i.localize(9,null),"unsetUninstalled"))})},V.prototype.unsetUninstalledAndGetLocal=function(e){var t=this;return this.isUninstalled(e).then(function(n){return n?(t.logService.trace("Removing the extension from uninstalled list:",e),t.unsetUninstalled(e).then(function(){return t.logService.info("Removed the extension from uninstalled list:",e),t.getInstalled(1)}).then(function(t){return t.filter(function(t){return t.identifier.id===e})[0]})):null})},V.prototype.extractAndInstall=function(e,t,n){var r=this,o=e.zipPath,s=e.id,a=e.metadata,l=1===t?this.extensionsPath:this.systemExtensionsPath,f=u.join(l,"."+s),p=u.join(l,s);return c.rimraf(p).then(function(){ return r.extractAndRename(s,o,f,p,n)},function(e){return Promise.reject(new z(i.localize(10,null,p,s),"deleting"))}).then(function(){return r.scanExtension(s,l,t)}).then(function(e){return e?(r.logService.info("Installation completed.",s),a?(e.metadata=a,r.saveMetadataForLocalExtension(e)):e):Promise.reject(i.localize(11,null,l))},function(e){return c.rimraf(p).then(function(){return Promise.reject(e)},function(){return Promise.reject(e)})})},V.prototype.extractAndRename=function(e,t,n,r,i){var o=this;return this.extract(e,t,n,i).then(function(){return o.rename(e,n,r,Date.now()+12e4).then(function(){return o.logService.info("Renamed to",r)},function(e){return o.logService.info("Rename failed. Deleting from extracted location",n),y.always(c.rimraf(n),function(){return null}).then(function(){return Promise.reject(e)})})})},V.prototype.extract=function(e,t,n,r){var i=this;return this.logService.trace("Started extracting the extension from "+t+" to "+n),c.rimraf(n).then(function(){return d.extract(t,n,{ sourcePath:"extension",overwrite:!0},i.logService,r).then(function(){return i.logService.info("Extracted extension to "+n+":",e)},function(e){return y.always(c.rimraf(n),function(){return null}).then(function(){return Promise.reject(new z(e.message,e instanceof d.ExtractError&&e.type?e.type:"extracting"))})})},function(e){return Promise.reject(new z(i.joinErrors(e).message,"deleting"))})},V.prototype.rename=function(e,t,n,r){var o=this;return c.rename(t,n).then(void 0,function(s){return C.isWindows&&s&&"EPERM"===s.code&&Date.now()<r?(o.logService.info("Failed renaming "+t+" to "+n+" with 'EPERM' error. Trying again..."),o.rename(e,t,n,r)):Promise.reject(new z(s.message||i.localize(12,null,t,n),s.code||"renaming"))})},V.prototype.installDependenciesAndPackExtensions=function(e,t){var n=this;if(this.galleryService.isEnabled()){var r=e.manifest.extensionDependencies||[];if(e.manifest.extensionPack)for(var i=function(e){t&&t.manifest.extensionPack&&t.manifest.extensionPack.some(function(t){ return g.areSameExtensions({id:t},{id:e})})||r.every(function(t){return!g.areSameExtensions({id:t},{id:e})})&&r.push(e)},o=0,s=e.manifest.extensionPack;o<s.length;o++){i(s[o])}if(r.length)return this.getInstalled().then(function(e){var t=r.filter(function(t){return!n.installingExtensions.has(g.adoptToGalleryExtensionId(t))&&e.every(function(e){var n=e.galleryIdentifier;return!g.areSameExtensions(n,{id:t})})});return t.length?n.galleryService.query({names:t,pageSize:r.length}).then(function(e){var t=e.firstPage;return Promise.all(t.map(function(e){return n.installFromGallery(e)})).then(function(){return null},function(e){return n.rollback(t).then(function(){return Promise.reject(e)},function(){return Promise.reject(e)})})}):null})}return Promise.resolve(void 0)},V.prototype.rollback=function(e){var t=this;return this.getInstalled(1).then(function(n){return Promise.all(n.filter(function(t){return e.some(function(e){return t.identifier.id===N(e,e.version)})}).map(function(e){return t.uninstall(e,!0)})) }).then(function(){},function(){})},V.prototype.uninstall=function(e,t){var n=this;return void 0===t&&(t=!1),this.logService.trace("ExtensionManagementService#uninstall",e.identifier.id),this.toNonCancellablePromise(this.getInstalled(1).then(function(t){var r=t.filter(function(t){return t.manifest.publisher===e.manifest.publisher&&t.manifest.name===e.manifest.name});if(r.length){var o=r.map(function(e){return n.checkForDependenciesAndUninstall(e,t)});return Promise.all(o).then(function(){return null},function(e){return Promise.reject(n.joinErrors(e))})}return Promise.reject(new Error(i.localize(13,null,e.manifest.displayName||e.manifest.name)))}))},V.prototype.updateMetadata=function(e,t){var n=this;return this.logService.trace("ExtensionManagementService#updateMetadata",e.identifier.id),e.metadata=t,this.saveMetadataForLocalExtension(e).then(function(e){return n.manifestCache.invalidate(),e})},V.prototype.saveMetadataForLocalExtension=function(e){if(!e.metadata)return Promise.resolve(e) ;var t=u.join(this.extensionsPath,e.identifier.id,"package.json");return c.readFile(t,"utf8").then(function(e){return F(e)}).then(function(t){var n=t.manifest;return l.assign(n,{__metadata:e.metadata})}).then(function(e){return c.writeFile(t,JSON.stringify(e,null,"\t"))}).then(function(){return e})},V.prototype.getMetadata=function(e){return this.findGalleryExtensionByName(e).then(function(e){return e?{id:e.identifier.uuid,publisherDisplayName:e.publisherDisplayName,publisherId:e.publisherId}:null})},V.prototype.findGalleryExtension=function(e){var t=this;return e.identifier.uuid?this.findGalleryExtensionById(e.identifier.uuid).then(function(n){return n||t.findGalleryExtensionByName(g.getGalleryExtensionIdFromLocal(e))}):this.findGalleryExtensionByName(g.getGalleryExtensionIdFromLocal(e))},V.prototype.findGalleryExtensionById=function(e){return this.galleryService.query({ids:[e],pageSize:1}).then(function(e){return e.firstPage[0]})},V.prototype.findGalleryExtensionByName=function(e){ return this.galleryService.query({names:[e],pageSize:1}).then(function(e){return e.firstPage[0]})},V.prototype.joinErrors=function(e){var t=Array.isArray(e)?e:[e];return 1===t.length?t[0]instanceof Error?t[0]:new Error(t[0]):t.reduce(function(e,t){return new Error(e.message+(e.message?",":"")+(t instanceof Error?t.message:t))},new Error(""))},V.prototype.checkForDependenciesAndUninstall=function(e,t){var n=this;return this.preUninstallExtension(e).then(function(){var r=n.getAllPackExtensionsToUninstall(e,t);return r.length?n.uninstallExtensions(e,r,t):n.uninstallExtensions(e,[],t)}).then(function(){return n.postUninstallExtension(e)},function(t){return n.postUninstallExtension(e,new z(t instanceof Error?t.message:t,"local")),Promise.reject(t)})},V.prototype.uninstallExtensions=function(e,t,n){var r=this,i=this.getDependents(e,n);if(i.length){var o=i.filter(function(n){return e!==n&&-1===t.indexOf(n)});if(o.length)return Promise.reject(new Error(this.getDependentsErrorMessage(e,o)))} return Promise.all([this.uninstallExtension(e)].concat(t.map(function(e){return r.doUninstall(e)}))).then(function(){})},V.prototype.getDependentsErrorMessage=function(e,t){return 1===t.length?i.localize(14,null,e.manifest.displayName||e.manifest.name,t[0].manifest.displayName||t[0].manifest.name):2===t.length?i.localize(15,null,e.manifest.displayName||e.manifest.name,t[0].manifest.displayName||t[0].manifest.name,t[1].manifest.displayName||t[1].manifest.name):i.localize(16,null,e.manifest.displayName||e.manifest.name,t[0].manifest.displayName||t[0].manifest.name,t[1].manifest.displayName||t[1].manifest.name)},V.prototype.getAllPackExtensionsToUninstall=function(e,t,n){if(void 0===n&&(n=[]),-1!==n.indexOf(e))return[];n.push(e);var r=e.manifest.extensionPack?e.manifest.extensionPack:[];if(r.length){for(var i=t.filter(function(e){return r.some(function(t){return g.areSameExtensions({id:t},e.galleryIdentifier)})}),o=[],s=0,a=i;s<a.length;s++){var u=a[s];o.push.apply(o,this.getAllPackExtensionsToUninstall(u,t,n))} return i.concat(o)}return[]},V.prototype.getDependents=function(e,t){return t.filter(function(t){return t.manifest.extensionDependencies&&t.manifest.extensionDependencies.some(function(t){return g.areSameExtensions({id:t},e.galleryIdentifier)})})},V.prototype.doUninstall=function(e){var t=this;return this.preUninstallExtension(e).then(function(){return t.uninstallExtension(e)}).then(function(){return t.postUninstallExtension(e)},function(n){return t.postUninstallExtension(e,new z(n instanceof Error?n.message:n,"local")),Promise.reject(n)})},V.prototype.preUninstallExtension=function(e){var t=this;return Promise.resolve(c.exists(e.location.fsPath)).then(function(e){return e?null:Promise.reject(new Error(i.localize(17,null)))}).then(function(){t.logService.info("Uninstalling extension:",e.identifier.id),t._onUninstallExtension.fire(e.identifier)})},V.prototype.uninstallExtension=function(e){var t=this,n=g.getGalleryExtensionIdFromLocal(e),r=this.uninstallingExtensions.get(n) ;return r||(r=y.createCancelablePromise(function(r){return t.scanUserExtensions(!1).then(function(r){return t.setUninstalled.apply(t,r.filter(function(t){return g.areSameExtensions({id:g.getGalleryExtensionIdFromLocal(t),uuid:t.identifier.uuid},{id:n,uuid:e.identifier.uuid})}))}).then(function(){t.uninstallingExtensions.delete(n)})}),this.uninstallingExtensions.set(n,r)),r},V.prototype.postUninstallExtension=function(e,t){return n(this,void 0,void 0,function(){var n;return r(this,function(r){switch(r.label){case 0:return t?(this.logService.error("Failed to uninstall extension:",e.identifier.id,t.message),[3,3]):[3,1];case 1:return this.logService.info("Successfully uninstalled extension:",e.identifier.id),e.identifier.uuid?[4,this.galleryService.reportStatistic(e.manifest.publisher,e.manifest.name,e.manifest.version,"uninstall")]:[3,3];case 2:r.sent(),r.label=3;case 3:return this.reportTelemetry("extensionGallery:uninstall",g.getLocalExtensionTelemetryData(e),void 0,t), n=t?t instanceof z?t.code:"unknown":void 0,this._onDidUninstallExtension.fire({identifier:e.identifier,error:n}),[2]}})})},V.prototype.getInstalled=function(e){var t=this;void 0===e&&(e=null);var n=[];return null!==e&&0!==e||n.push(this.scanSystemExtensions().then(null,function(e){return Promise.reject(new z(t.joinErrors(e).message,"scanningSystem"))})),null!==e&&1!==e||n.push(this.scanUserExtensions(!0).then(null,function(e){return Promise.reject(new z(t.joinErrors(e).message,"scanningUser"))})),Promise.all(n).then(p.flatten,function(e){return Promise.reject(t.joinErrors(e))})},V.prototype.scanSystemExtensions=function(){var e=this;this.logService.trace("Started scanning system extensions");var t=this.scanExtensions(this.systemExtensionsPath,0).then(function(t){return e.logService.info("Scanned system extensions:",t.length),t});if(this.environmentService.isBuilt)return t;var n=this.getDevSystemExtensionsList().then(function(t){return t.length?e.scanExtensions(e.devSystemExtensionsPath,0).then(function(n){ return e.logService.info("Scanned dev system extensions:",n.length),n.filter(function(e){return t.some(function(t){return g.areSameExtensions(e.galleryIdentifier,{id:t})})})}):[]});return Promise.all([t,n]).then(function(e){var t=e[0],n=e[1];return t.concat(n)})},V.prototype.scanUserExtensions=function(e){var t=this;return this.logService.trace("Started scanning user extensions"),Promise.all([this.getUninstalledExtensions(),this.scanExtensions(this.extensionsPath,1)]).then(function(n){var r=n[0],i=n[1];if(i=i.filter(function(e){return!r[e.identifier.id]}),e){i=g.groupByExtension(i,function(e){return{id:g.getGalleryExtensionIdFromLocal(e),uuid:e.identifier.uuid}}).map(function(e){return e.sort(function(e,t){return E.rcompare(e.manifest.version,t.manifest.version)})[0]})}return t.logService.info("Scanned user extensions:",i.length),i})},V.prototype.scanExtensions=function(e,t){var n=this,r=new y.Limiter(10);return c.readdir(e).then(function(i){return Promise.all(i.map(function(i){return r.queue(function(){ return n.scanExtension(i,e,t)})}))}).then(function(e){return e.filter(function(e){return e&&e.identifier})})},V.prototype.scanExtension=function(e,t,n){if(1===n&&0===e.indexOf("."))return Promise.resolve(null);var r=u.join(t,e);return c.readdir(r).then(function(t){return function(e){var t=[c.readFile(u.join(e,"package.json"),"utf8").then(function(e){return F(e)}),c.readFile(u.join(e,"package.nls.json"),"utf8").then(void 0,function(e){return"ENOENT"!==e.code?Promise.reject(e):"{}"}).then(function(e){return JSON.parse(e)})];return Promise.all(t).then(function(e){var t=e[0],n=t.manifest,r=t.metadata,i=e[1];return{manifest:v.localizeManifest(n,i),metadata:r}})}(r).then(function(i){var o=i.manifest,s=i.metadata,a=t.filter(function(e){return/^readme(\.txt|\.md|)$/i.test(e)})[0],c=a?S.URI.file(u.join(r,a)).toString():null,l=t.filter(function(e){return/^changelog(\.txt|\.md|)$/i.test(e)})[0],f=l?S.URI.file(u.join(r,l)).toString():null ;o.extensionDependencies&&(o.extensionDependencies=o.extensionDependencies.map(function(e){return g.adoptToGalleryExtensionId(e)})),o.extensionPack&&(o.extensionPack=o.extensionPack.map(function(e){return g.adoptToGalleryExtensionId(e)}));var p={id:0===n?e:U(o),uuid:s?s.id:null},d={id:g.getGalleryExtensionId(o.publisher,o.name),uuid:p.uuid};return{type:n,identifier:p,galleryIdentifier:d,manifest:o,metadata:s,location:S.URI.file(r),readmeUrl:c,changelogUrl:f}})}).then(void 0,function(){return null})},V.prototype.removeDeprecatedExtensions=function(){var e=this;return this.removeUninstalledExtensions().then(function(){return e.removeOutdatedExtensions()})},V.prototype.removeUninstalledExtensions=function(){var e=this;return this.getUninstalledExtensions().then(function(t){return e.scanExtensions(e.extensionsPath,1).then(function(n){var r=n.filter(function(e){return t[e.identifier.id]});return Promise.all(r.map(function(t){return e.extensionLifecycle.postUninstall(t).then(function(){ return e.removeUninstalledExtension(t)})}))})}).then(function(){})},V.prototype.removeOutdatedExtensions=function(){var e=this;return this.scanExtensions(this.extensionsPath,1).then(function(t){var n=[],r=g.groupByExtension(t,function(e){return{id:g.getGalleryExtensionIdFromLocal(e),uuid:e.identifier.uuid}});return n.push.apply(n,p.flatten(r.map(function(e){return e.sort(function(e,t){return E.rcompare(e.manifest.version,t.manifest.version)}).slice(1)}))),Promise.all(n.map(function(t){return e.removeExtension(t,"outdated")}))}).then(function(){})},V.prototype.removeUninstalledExtension=function(e){var t=this;return this.removeExtension(e,"uninstalled").then(function(){return t.withUninstalledExtensions(function(t){return delete t[e.identifier.id]})}).then(function(){})},V.prototype.removeExtension=function(e,t){var n=this;return this.logService.trace("Deleting "+t+" extension from disk",e.identifier.id),c.rimraf(e.location.fsPath).then(function(){return n.logService.info("Deleted from disk",e.identifier.id)}) },V.prototype.isUninstalled=function(e){return this.filterUninstalled(e).then(function(e){return 1===e.length})},V.prototype.filterUninstalled=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.withUninstalledExtensions(function(t){for(var n=[],r=0,i=e;r<i.length;r++){var o=i[r];t[o]&&n.push(o)}return n})},V.prototype.setUninstalled=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e.map(function(e){return e.identifier.id});return this.withUninstalledExtensions(function(e){return l.assign(e,n.reduce(function(e,t){return e[t]=!0,e},{}))})},V.prototype.unsetUninstalled=function(e){return this.withUninstalledExtensions(function(t){return delete t[e]})},V.prototype.getUninstalledExtensions=function(){return this.withUninstalledExtensions(function(e){return e})},V.prototype.withUninstalledExtensions=function(e){return n(this,void 0,void 0,function(){var t=this;return r(this,function(n){switch(n.label){case 0: return[4,this.uninstalledFileLimiter.queue(function(){var n=null;return c.readFile(t.uninstalledPath,"utf8").then(void 0,function(e){return"ENOENT"===e.code?Promise.resolve("{}"):Promise.reject(e)}).then(function(e){try{return JSON.parse(e)}catch(e){return{}}}).then(function(t){return n=e(t),t}).then(function(e){if(0===Object.keys(e).length)return c.rimraf(t.uninstalledPath);var n=JSON.stringify(e);return c.writeFile(t.uninstalledPath,n)}).then(function(){return n})})];case 1:return[2,n.sent()]}})})},V.prototype.getExtensionsReport=function(){var e=(new Date).getTime();return(!this.reportedExtensions||e-this.lastReportTimestamp>3e5)&&(this.reportedExtensions=this.updateReportCache(),this.lastReportTimestamp=e),this.reportedExtensions},V.prototype.updateReportCache=function(){var e=this;return this.logService.trace("ExtensionManagementService.refreshReportedCache"),this.galleryService.getExtensionsReport().then(function(t){ return e.logService.trace("ExtensionManagementService.refreshReportedCache - got "+t.length+" reported extensions from service"),t},function(t){return e.logService.trace("ExtensionManagementService.refreshReportedCache - failed to get extension report"),[]})},Object.defineProperty(V.prototype,"devSystemExtensionsPath",{get:function(){return this._devSystemExtensionsPath||(this._devSystemExtensionsPath=u.normalize(u.join(R.getPathFromAmdModule(e,""),"..",".build","builtInExtensions"))),this._devSystemExtensionsPath},enumerable:!0,configurable:!0}),Object.defineProperty(V.prototype,"devSystemExtensionsFilePath",{get:function(){return this._devSystemExtensionsFilePath||(this._devSystemExtensionsFilePath=u.normalize(u.join(R.getPathFromAmdModule(e,""),"..","build","builtInExtensions.json"))),this._devSystemExtensionsFilePath},enumerable:!0,configurable:!0}),V.prototype.getDevSystemExtensionsList=function(){return c.readFile(this.devSystemExtensionsFilePath,"utf8").then(function(e){ return JSON.parse(e).map(function(e){return e.name})})},V.prototype.toNonCancellablePromise=function(e){return new Promise(function(t,n){return e.then(function(e){return t(e)},function(e){return n(e)})})},V.prototype.reportTelemetry=function(e,t,n,r){var i=r?r instanceof z?r.code:"unknown":void 0;this.telemetryService.publicLog(e,l.assign(t,{success:!r,duration:n,errorcode:i}))},V=s([a(0,m.IEnvironmentService),a(1,h.IExtensionGalleryService),a(2,P.ILogService),a(3,L.optional(D.IDownloadService)),a(4,O.ITelemetryService)],V)}(f.Disposable);t.ExtensionManagementService=V,t.getLocalExtensionIdFromGallery=N,t.getLocalExtensionIdFromManifest=U}),define(e[34],t([0,1,3,83,24,6,91,23]),function(e,t,i,o,s,a,u,c){"use strict";function l(t,s){var f;return(t.getRawRequest?Promise.resolve(t.getRawRequest(t)):Promise.resolve(function(t){return n(this,void 0,void 0,function(){var n,i,s;return r(this,function(r){switch(r.label){case 0:return"https:"!==(n=o.parse(t.url)).protocol?[3,2]:[4,new Promise(function(t,n){ e(["https"],t,n)})];case 1:return s=r.sent(),[3,4];case 2:return[4,new Promise(function(t,n){e(["http"],t,n)})];case 3:s=r.sent(),r.label=4;case 4:return i=s,[2,i.request]}})})}(t))).then(function(e){return new Promise(function(n,r){var p=o.parse(t.url),d={hostname:p.hostname,port:p.port?parseInt(p.port):"https:"===p.protocol?443:80,protocol:p.protocol,path:p.path,method:t.type||"GET",headers:t.headers,agent:t.agent,rejectUnauthorized:!i.isBoolean(t.strictSSL)||t.strictSSL};if(t.user&&t.password&&(d.auth=t.user+":"+t.password),(f=e(d,function(e){var o=i.isNumber(t.followRedirects)?t.followRedirects:3;if(e.statusCode&&e.statusCode>=300&&e.statusCode<400&&o>0&&e.headers.location)l(a.assign({},t,{url:e.headers.location,followRedirects:o-1}),s).then(n,r);else{var c=e;"gzip"===e.headers["content-encoding"]&&(c=c.pipe(u.createGunzip())),n({res:e,stream:c})}})).on("error",r),t.timeout&&f.setTimeout(t.timeout),t.data){if("string"!=typeof t.data)return void t.data.pipe(f);f.write(t.data)}f.end(), s.onCancellationRequested(function(){f.abort(),r(c.canceled())})})})}function f(e){return e.res.statusCode&&e.res.statusCode>=200&&e.res.statusCode<300||1223===e.res.statusCode}function p(e){return 204===e.res.statusCode}Object.defineProperty(t,"__esModule",{value:!0}),t.request=l,t.download=function(e,t){return new Promise(function(n,r){var i=s.createWriteStream(e);i.once("finish",function(){return n(void 0)}),t.stream.once("error",r),t.stream.pipe(i)})},t.asText=function(e){return new Promise(function(t,n){if(!f(e))return n("Server returned "+e.res.statusCode);if(p(e))return t(null);var r=[];e.stream.on("data",function(e){return r.push(e)}),e.stream.on("end",function(){return t(r.join(""))}),e.stream.on("error",n)})},t.asJson=function(e){return new Promise(function(t,n){if(!f(e))return n("Server returned "+e.res.statusCode);if(p(e))return t(null);var r=[];e.stream.on("data",function(e){return r.push(e)}),e.stream.on("end",function(){try{t(JSON.parse(r.join("")))}catch(e){n(e)}}),e.stream.on("error",n)})}}), define(e[86],t([0,1,26,5,19,23,18,6,41,27,34,20,36,32,17,12,39,43,33,93,7]),function(e,t,n,r,o,u,c,l,f,p,d,h,g,v,m,y,b,E,S,x,C){"use strict";function P(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return String(e.reduce(function(e,t){return e|t},0))}function _(e,t){var n=(e||[]).filter(function(e){return e.statisticName===t})[0];return n?n.value:0}function w(e,t){return e.files.filter(function(e){return e.assetType===t})[0]?{uri:e.assetUri+"/"+t,fallbackUri:e.fallbackAssetUri+"/"+t}:null}function I(e,t){var n=e.properties?e.properties.filter(function(e){return e.key===t}):[],r=n.length>0&&n[0].value;return r?r.split(",").map(function(e){return c.adoptToGalleryExtensionId(e)}):[]}function O(e){var t=e.properties?e.properties.filter(function(e){return e.key===M.Engine}):[];return t.length>0&&t[0].value||""}function k(t,n,r,i,o){var s={manifest:w(n,L.Manifest),readme:w(n,L.Details),changelog:w(n,L.Changelog),license:w(n,L.License),repository:function(e){if(e.properties){ var t=e.properties.filter(function(e){return e.key===L.Repository}),n=new RegExp("((git|ssh|http(s)?)|(git@[w.]+))(:(//)?)([w.@:/-~]+)(.git)(/)?"),r=t.filter(function(e){return n.test(e.value)})[0];return r?{uri:r.value,fallbackUri:r.value}:null}return w(e,L.Repository)}(n),download:function(e){return{uri:e.fallbackAssetUri+"/"+L.VSIX+"?redirect=true",fallbackUri:e.fallbackAssetUri+"/"+L.VSIX}}(n),icon:function(t){var n=w(t,L.Icon);if(n)return n;var r=e.toUrl("./media/defaultIcon.png");return{uri:r,fallbackUri:r}}(n),coreTranslations:function(e){return e.files.filter(function(e){return 0===e.assetType.indexOf("Microsoft.VisualStudio.Code.Translation.")}).reduce(function(t,n){return t[n.assetType.substring("Microsoft.VisualStudio.Code.Translation.".length)]=w(e,n.assetType),t},{})}(n)};return{identifier:{id:c.getGalleryExtensionId(t.publisher.publisherName,t.extensionName),uuid:t.extensionId},name:t.extensionName,version:n.version,date:n.lastUpdated,displayName:t.displayName, publisherId:t.publisher.publisherId,publisher:t.publisher.publisherName,publisherDisplayName:t.publisher.displayName,description:t.shortDescription||"",installCount:_(t.statistics,"install")+_(t.statistics,"updateCount"),rating:_(t.statistics,"averagerating"),ratingCount:_(t.statistics,"ratingcount"),assets:s,properties:{dependencies:I(n,M.Dependency),extensionPack:I(n,M.ExtensionPack),engine:O(n),localizedLanguages:function(e){var t=e.properties?e.properties.filter(function(e){return e.key===M.LocalizedLanguages}):[],n=t.length>0&&t[0].value||"";return n?n.split(","):[]}(n)},telemetryData:{index:(i.pageNumber-1)*i.pageSize+r,searchText:i.searchText,querySource:o},preview:function(e){return-1!==e.indexOf("preview")}(t.flags)}}function j(e){var t=r.join(e.userDataPath,"machineid");return y.readFile(t,"utf8").then(function(e){return E.isUUID(e)?e:Promise.resolve(null)},function(){return Promise.resolve(null)}).then(function(e){if(!e){e=E.generateUuid();try{b.writeFileAndFlushSync(t,e)}catch(e){}}return{ "X-Market-Client-Id":"VSCode "+h.default.version,"User-Agent":"VSCode "+h.default.version,"X-Market-User-Id":e}})}Object.defineProperty(t,"__esModule",{value:!0});var T;!function(e){e[e.None=0]="None",e[e.IncludeVersions=1]="IncludeVersions",e[e.IncludeFiles=2]="IncludeFiles",e[e.IncludeCategoryAndTags=4]="IncludeCategoryAndTags",e[e.IncludeSharedAccounts=8]="IncludeSharedAccounts",e[e.IncludeVersionProperties=16]="IncludeVersionProperties",e[e.ExcludeNonValidated=32]="ExcludeNonValidated",e[e.IncludeInstallationTargets=64]="IncludeInstallationTargets",e[e.IncludeAssetUri=128]="IncludeAssetUri",e[e.IncludeStatistics=256]="IncludeStatistics",e[e.IncludeLatestVersionOnly=512]="IncludeLatestVersionOnly",e[e.Unpublished=4096]="Unpublished"}(T||(T={}));var D;!function(e){e[e.Tag=1]="Tag",e[e.ExtensionId=4]="ExtensionId",e[e.Category=5]="Category",e[e.ExtensionName=7]="ExtensionName",e[e.Target=8]="Target",e[e.Featured=9]="Featured",e[e.SearchText=10]="SearchText",e[e.ExcludeWithFlags=12]="ExcludeWithFlags" }(D||(D={}));var L={Icon:"Microsoft.VisualStudio.Services.Icons.Default",Details:"Microsoft.VisualStudio.Services.Content.Details",Changelog:"Microsoft.VisualStudio.Services.Content.Changelog",Manifest:"Microsoft.VisualStudio.Code.Manifest",VSIX:"Microsoft.VisualStudio.Services.VSIXPackage",License:"Microsoft.VisualStudio.Services.Content.License",Repository:"Microsoft.VisualStudio.Services.Links.Source"},M={Dependency:"Microsoft.VisualStudio.Code.ExtensionDependencies",ExtensionPack:"Microsoft.VisualStudio.Code.ExtensionPack",Engine:"Microsoft.VisualStudio.Code.Engine",LocalizedLanguages:"Microsoft.VisualStudio.Code.LocalizedLanguages"},R={pageNumber:1,pageSize:10,sortBy:0,sortOrder:0,flags:T.None,criteria:[],assetTypes:[]},A=function(){function e(e){void 0===e&&(e=R),this.state=e}return Object.defineProperty(e.prototype,"pageNumber",{get:function(){return this.state.pageNumber},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pageSize",{get:function(){return this.state.pageSize}, enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"sortBy",{get:function(){return this.state.sortBy},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"sortOrder",{get:function(){return this.state.sortOrder},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"flags",{get:function(){return this.state.flags},enumerable:!0,configurable:!0}),e.prototype.withPage=function(t,n){return void 0===n&&(n=this.state.pageSize),new e(l.assign({},this.state,{pageNumber:t,pageSize:n}))},e.prototype.withFilter=function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];var i=this.state.criteria.concat(n.map(function(e){return{filterType:t,value:e}}));return new e(l.assign({},this.state,{criteria:i}))},e.prototype.withSortBy=function(t){return new e(l.assign({},this.state,{sortBy:t}))},e.prototype.withSortOrder=function(t){return new e(l.assign({},this.state,{sortOrder:t}))},e.prototype.withFlags=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n] ;return new e(l.assign({},this.state,{flags:t.reduce(function(e,t){return e|t},0)}))},e.prototype.withAssetTypes=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return new e(l.assign({},this.state,{assetTypes:t}))},Object.defineProperty(e.prototype,"raw",{get:function(){var e=this.state,t=e.criteria,n=e.pageNumber,r=e.pageSize,i=e.sortBy,o=e.sortOrder,s=e.flags;return{filters:[{criteria:t,pageNumber:n,pageSize:r,sortBy:i,sortOrder:o}],assetTypes:e.assetTypes,flags:s}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"searchText",{get:function(){var e=this.state.criteria.filter(function(e){return e.filterType===D.SearchText})[0];return e&&e.value?e.value:""},enumerable:!0,configurable:!0}),e}(),F=function(){function e(e,t,n,r){this.requestService=e,this.logService=t,this.environmentService=n,this.telemetryService=r;var i=g.default.extensionsGallery;this.extensionsGalleryUrl=i&&i.serviceUrl,this.extensionsControlUrl=i&&i.controlUrl, this.commonHeadersPromise=j(this.environmentService)}return e.prototype.api=function(e){return void 0===e&&(e=""),""+this.extensionsGalleryUrl+e},e.prototype.isEnabled=function(){return!!this.extensionsGalleryUrl},e.prototype.getExtension=function(e,t){var n=e.id,r=e.uuid,i=(new A).withFlags(T.IncludeAssetUri,T.IncludeStatistics,T.IncludeFiles,T.IncludeVersionProperties).withPage(1,1).withFilter(D.Target,"Microsoft.VisualStudio.Code").withFilter(D.ExcludeWithFlags,P(T.Unpublished));return i=r?i.withFilter(D.ExtensionId,r):i.withFilter(D.ExtensionName,n),this.queryGallery(i,x.CancellationToken.None).then(function(e){var n=e.galleryExtensions;if(n.length){var r=n[0],o=t?r.versions.filter(function(e){return e.version===t})[0]:r.versions[0];if(o)return k(r,o,0,i)}return null})},e.prototype.query=function(e){var t=this;if(void 0===e&&(e={}),!this.isEnabled())return Promise.reject(new Error("No extension gallery service configured.")) ;var n=e.names?"ids":e.text?"text":"all",r=e.text||"",i=l.getOrDefault(e,function(e){return e.pageSize},50);this.telemetryService.publicLog("galleryService:query",{type:n,text:r});var o=(new A).withFlags(T.IncludeLatestVersionOnly,T.IncludeAssetUri,T.IncludeStatistics,T.IncludeFiles,T.IncludeVersionProperties).withPage(1,i).withFilter(D.Target,"Microsoft.VisualStudio.Code").withFilter(D.ExcludeWithFlags,P(T.Unpublished));return r?((r=(r=(r=r.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g,function(e,t,n){return o=o.withFilter(D.Category,n||t),""})).replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g,function(e,t,n){return o=o.withFilter(D.Tag,n||t),""})).trim())&&(r=r.length<200?r:r.substring(0,200),o=o.withFilter(D.SearchText,r)),o=o.withSortBy(0)):o=e.ids?o.withFilter.apply(o,[D.ExtensionId].concat(e.ids)):e.names?o.withFilter.apply(o,[D.ExtensionName].concat(e.names)):o.withSortBy(4),"number"==typeof e.sortBy&&(o=o.withSortBy(e.sortBy)),"number"==typeof e.sortOrder&&(o=o.withSortOrder(e.sortOrder)), this.queryGallery(o,x.CancellationToken.None).then(function(n){var r=n.galleryExtensions,i=n.total;return{firstPage:r.map(function(t,n){return k(t,t.versions[0],n,o,e.source)}),total:i,pageSize:o.pageSize,getPage:function(n,r){if(r.isCancellationRequested)return Promise.reject(u.canceled());var i=o.withPage(n+1);return t.queryGallery(i,r).then(function(t){return t.galleryExtensions.map(function(t,n){return k(t,t.versions[0],n,i,e.source)})})}}})},e.prototype.queryGallery=function(e,t){var n=this;return this.isEnabled()?this.commonHeadersPromise.then(function(r){var i=JSON.stringify(e.raw),o=l.assign({},r,{"Content-Type":"application/json",Accept:"application/json;api-version=3.0-preview.1","Accept-Encoding":"gzip","Content-Length":i.length});return n.requestService.request({type:"POST",url:n.api("/extensionquery"),data:i,headers:o},t).then(function(e){return e.res.statusCode&&e.res.statusCode>=400&&e.res.statusCode<500?{galleryExtensions:[],total:0}:d.asJson(e).then(function(e){if(e){ var t=e.results[0],n=t.extensions,r=t.resultMetadata&&t.resultMetadata.filter(function(e){return"ResultCount"===e.metadataType})[0];return{galleryExtensions:n,total:r&&r.metadataItems.filter(function(e){return"TotalCount"===e.name})[0].count||0}}return{galleryExtensions:[],total:0}})})}):Promise.reject(new Error("No extension gallery service configured."))},e.prototype.reportStatistic=function(e,t,n,r){var o=this;return this.isEnabled()?this.commonHeadersPromise.then(function(s){var a=i({},s,{Accept:"*/*;api-version=4.0-preview.1"});return o.requestService.request({type:"POST",url:o.api("/publishers/"+e+"/extensions/"+t+"/"+n+"/stats?statType="+r),headers:a},x.CancellationToken.None).then(void 0,function(){})}):Promise.resolve(void 0)},e.prototype.download=function(e,t){var i=this;this.logService.trace("ExtensionGalleryService#download",e.identifier.id);var o=r.join(n.tmpdir(),E.generateUuid()),s=c.getGalleryExtensionTelemetryData(e),a=(new Date).getTime(),u=1===t?"install":2===t?"update":"",f=u?{ uri:e.assets.download.uri+"&"+u+"=true",fallbackUri:e.assets.download.fallbackUri+"?"+u+"=true"}:e.assets.download;return this.getAsset(f).then(function(e){return d.download(o,e)}).then(function(){return function(e){return i.telemetryService.publicLog("galleryService:downloadVSIX",l.assign(s,{duration:e}))}((new Date).getTime()-a)}).then(function(){return o})},e.prototype.getReadme=function(e,t){return e.assets.readme?this.getAsset(e.assets.readme,{},t).then(function(e){return d.asText(e)}).then(function(e){return e||""}):Promise.resolve("")},e.prototype.getManifest=function(e,t){return e.assets.manifest?this.getAsset(e.assets.manifest,{},t).then(d.asText).then(JSON.parse):Promise.resolve(null)},e.prototype.getCoreTranslation=function(e,t){var n=e.assets.coreTranslations[t.toUpperCase()];return n?this.getAsset(n).then(d.asText).then(JSON.parse):Promise.resolve(null)},e.prototype.getChangelog=function(e,t){return e.assets.changelog?this.getAsset(e.assets.changelog,{},t).then(function(e){return d.asText(e) }).then(function(e){return e||""}):Promise.resolve("")},e.prototype.loadAllDependencies=function(e,t){return this.getDependenciesReccursively(e.map(function(e){return e.id}),[],t)},e.prototype.getAllVersions=function(e,t){var n=this,r=(new A).withFlags(T.IncludeVersions,T.IncludeFiles,T.IncludeVersionProperties).withPage(1,1).withFilter(D.Target,"Microsoft.VisualStudio.Code").withFilter(D.ExcludeWithFlags,P(T.Unpublished));return r=e.identifier.uuid?r.withFilter(D.ExtensionId,e.identifier.uuid):r.withFilter(D.ExtensionName,e.identifier.id),this.queryGallery(r,x.CancellationToken.None).then(function(e){var r=e.galleryExtensions;return r.length?t?Promise.all(r[0].versions.map(function(e){return n.getEngine(e).then(function(t){return v.isEngineValid(t)?e:null})})).then(function(e){return e.filter(function(e){return!!e}).map(function(e){return{version:e.version,date:e.lastUpdated}})}):r[0].versions.map(function(e){return{version:e.version,date:e.lastUpdated}}):[]})}, e.prototype.loadCompatibleVersion=function(e,t){var n=this;if(void 0===t&&(t=e.version),e.version===t&&e.properties.engine&&v.isEngineValid(e.properties.engine))return Promise.resolve(e);var r=(new A).withFlags(T.IncludeVersions,T.IncludeFiles,T.IncludeVersionProperties).withPage(1,1).withFilter(D.Target,"Microsoft.VisualStudio.Code").withFilter(D.ExcludeWithFlags,P(T.Unpublished)).withAssetTypes(L.Manifest,L.VSIX).withFilter(D.ExtensionId,e.identifier.uuid);return this.queryGallery(r,x.CancellationToken.None).then(function(e){var i=e.galleryExtensions[0];if(!i)return null;var o=n.getVersionsFrom(i.versions,t);return o.length?n.getLastValidExtensionVersion(i,o).then(function(e){return e?k(i,e,0,r):null}):null})},e.prototype.getVersionsFrom=function(e,t){if(e[0].version===t)return e;for(var n=[],r=null,i=0,o=e;i<o.length;i++){var s=o[i];r||s.version===t&&(r=s),r&&n.push(s)}return n},e.prototype.loadDependencies=function(e,t){var n;if(!e||0===e.length)return Promise.resolve([]) ;var r=(n=(new A).withFlags(T.IncludeLatestVersionOnly,T.IncludeAssetUri,T.IncludeStatistics,T.IncludeFiles,T.IncludeVersionProperties).withPage(1,e.length).withFilter(D.Target,"Microsoft.VisualStudio.Code").withFilter(D.ExcludeWithFlags,P(T.Unpublished)).withAssetTypes(L.Icon,L.License,L.Details,L.Manifest,L.VSIX)).withFilter.apply(n,[D.ExtensionName].concat(e));return this.queryGallery(r,t).then(function(e){for(var t=[],n=[],i=0;i<e.galleryExtensions.length;i++){var o=e.galleryExtensions[i];-1===n.indexOf(o.extensionId)&&(t.push(k(o,o.versions[0],i,r,"dependencies")),n.push(o.extensionId))}return t})},e.prototype.getDependenciesReccursively=function(t,n,r){var i=this;return t&&t.length&&(t=n.length?t.filter(function(t){return!e.hasExtensionByName(n,t)}):t).length?this.loadDependencies(t,r).then(function(t){for(var s=new Set,a=0,u=t;a<u.length;a++){var c=u[a];c.properties.dependencies&&c.properties.dependencies.forEach(function(e){return s.add(e)})}n=o.distinct(n.concat(t),function(e){ return e.identifier.uuid});var l=[];return s.forEach(function(t){return!e.hasExtensionByName(n,t)&&l.push(t)}),i.getDependenciesReccursively(l,n,r)}):Promise.resolve(n)},e.prototype.getAsset=function(e,t,n){var r=this;return void 0===t&&(t={}),void 0===n&&(n=x.CancellationToken.None),this.commonHeadersPromise.then(function(i){var o=l.assign({},i,t.headers||{});t=l.assign({},t,{type:"GET"},{headers:o});var s=e.uri,a=e.fallbackUri,c=l.assign({},t,{url:s});return r.requestService.request(c,n).then(function(e){return 200===e.res.statusCode?Promise.resolve(e):d.asText(e).then(function(t){return Promise.reject(new Error("Expected 200, got back "+e.res.statusCode+" instead.\n\n"+t))})}).then(void 0,function(e){if(u.isPromiseCanceledError(e))return Promise.reject(e);var i=u.getErrorMessage(e);r.telemetryService.publicLog("galleryService:requestError",{url:s,cdn:!0,message:i}),r.telemetryService.publicLog("galleryService:cdnFallback",{url:s,message:i});var o=l.assign({},t,{url:a}) ;return r.requestService.request(o,n).then(void 0,function(e){if(u.isPromiseCanceledError(e))return Promise.reject(e);var t=u.getErrorMessage(e);return r.telemetryService.publicLog("galleryService:requestError",{url:a,cdn:!1,message:t}),Promise.reject(e)})})})},e.prototype.getLastValidExtensionVersion=function(e,t){var n=this.getLastValidExtensionVersionFromProperties(e,t);return n||this.getLastValidExtensionVersionReccursively(e,t)},e.prototype.getLastValidExtensionVersionFromProperties=function(e,t){for(var n=0,r=t;n<r.length;n++){var i=r[n],o=O(i);if(!o)return null;if(v.isEngineValid(o))return Promise.resolve(i)}return null},e.prototype.getEngine=function(e){var t=O(e);if(t)return Promise.resolve(t);var n=w(e,L.Manifest);if(!n)return Promise.reject("Manifest was not found");return this.getAsset(n,{headers:{"Accept-Encoding":"gzip"}}).then(function(e){return d.asJson(e)}).then(function(e){return e?e.engines.vscode:Promise.reject("Error while reading manifest")})}, e.prototype.getLastValidExtensionVersionReccursively=function(e,t){var n=this;if(!t.length)return Promise.resolve(null);var r=t[0];return this.getEngine(r).then(function(i){return v.isEngineValid(i)?(r.properties=r.properties||[],r.properties.push({key:M.Engine,value:i}),r):n.getLastValidExtensionVersionReccursively(e,t.slice(1))})},e.hasExtensionByName=function(e,t){for(var n=0,r=e;n<r.length;n++){var i=r[n];if(i.publisher+"."+i.name===t)return!0}return!1},e.prototype.getExtensionsReport=function(){return this.isEnabled()?this.extensionsControlUrl?this.requestService.request({type:"GET",url:this.extensionsControlUrl},x.CancellationToken.None).then(function(e){return 200!==e.res.statusCode?Promise.reject(new Error("Could not get extensions report.")):d.asJson(e).then(function(e){var t=new Map;if(e)for(var n=0,r=e.malicious;n<r.length;n++){var i=r[n],o=t.get(i)||{id:{id:i},malicious:!0,slow:!1};o.malicious=!0,t.set(i,o)}return Promise.resolve(S.values(t))}) }):Promise.resolve([]):Promise.reject(new Error("No extension gallery service configured."))},e=s([a(0,f.IRequestService),a(1,C.ILogService),a(2,m.IEnvironmentService),a(3,p.ITelemetryService)],e)}();t.ExtensionGalleryService=F,t.resolveMarketplaceHeaders=j}),define(e[58],t([0,1,6,34,64,13,7]),function(e,t,n,r,i,o,u){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var c=function(){function e(e,t){var n=this;this.logService=t,this.disposables=[],this.configure(e.getValue()),e.onDidChangeConfiguration(function(){return n.configure(e.getValue())},this,this.disposables)}return e.prototype.configure=function(e){this.proxyUrl=e.http&&e.http.proxy,this.strictSSL=!(!e.http||!e.http.proxyStrictSSL),this.authorization=e.http&&e.http.proxyAuthorization},e.prototype.request=function(e,t,o){var s=this;void 0===o&&(o=r.request),this.logService.trace("RequestService#request",e.url);var a=this.proxyUrl,u=this.strictSSL;return(e.agent?Promise.resolve(e.agent):Promise.resolve(i.getProxyAgent(e.url||"",{ proxyUrl:a,strictSSL:u}))).then(function(r){return e.agent=r,e.strictSSL=u,s.authorization&&(e.headers=n.assign(e.headers||{},{"Proxy-Authorization":s.authorization})),o(e,t)})},e=s([a(0,o.IConfigurationService),a(1,u.ILogService)],e)}();t.RequestService=c}),define(e[95],t([0,1,4,36,20,5,45,21,29,38,57,17,63,28,81,86,27,79,78,82,41,58,13,73,80,12,53,75,76,60,7,23,18,22,42]),function(e,t,i,o,u,c,l,f,p,d,h,g,v,m,y,b,E,S,x,C,P,_,w,I,O,k,j,T,D,L,M,R,A,F,N){"use strict";function U(e,t){return t?e.publisher+"."+e.name+"@"+e.version:e.publisher+"."+e.name}function z(e){var t=B.exec(e);return t&&t[1]?[A.adoptToGalleryExtensionId(t[1]),t[2]]:[A.adoptToGalleryExtensionId(e),void 0]}Object.defineProperty(t,"__esModule",{value:!0});var V=i.localize(2,null,"ms-vscode.csharp"),B=/^([^.]+\..+)@(\d+\.\d+\.\d+(-.*)?)$/;t.getIdAndVersion=z;var q=function(){function e(e,t,n){this.environmentService=e,this.extensionManagementService=t,this.extensionGalleryService=n}return e.prototype.run=function(e){ return n(this,void 0,void 0,function(){var t,n,i;return r(this,function(r){switch(r.label){case 0:return e["install-source"]?[4,this.setInstallSource(e["install-source"])]:[3,2];case 1:return r.sent(),[3,8];case 2:return e["list-extensions"]?[4,this.listExtensions(!!e["show-versions"])]:[3,4];case 3:return r.sent(),[3,8];case 4:return e["install-extension"]?(n=e["install-extension"],t="string"==typeof n?[n]:n,[4,this.installExtension(t,e.force)]):[3,6];case 5:return r.sent(),[3,8];case 6:return e["uninstall-extension"]?(n=e["uninstall-extension"],i="string"==typeof n?[n]:n,[4,this.uninstallExtension(i)]):[3,8];case 7:r.sent(),r.label=8;case 8:return[2]}})})},e.prototype.setInstallSource=function(e){return k.writeFile(this.environmentService.installSourcePath,e.slice(0,30))},e.prototype.listExtensions=function(e){return n(this,void 0,void 0,function(){var t;return r(this,function(n){switch(n.label){case 0:return[4,this.extensionManagementService.getInstalled(1)];case 1:return(t=n.sent()).forEach(function(t){ return console.log(U(t.manifest,e))}),[2]}})})},e.prototype.installExtension=function(e,t){var n=this,r=e.filter(function(e){return/\.vsix$/i.test(e)}).map(function(e){return function(){var r=c.isAbsolute(e)?e:c.join(process.cwd(),e);return n.validate(r,t).then(function(e){return e?n.extensionManagementService.install(F.URI.file(r)).then(function(){console.log(i.localize(3,null,j.getBaseLabel(r)))},function(e){return R.isPromiseCanceledError(e)?(console.log(i.localize(4,null,j.getBaseLabel(r))),null):Promise.reject(e)}):null})}}),o=e.filter(function(e){return!/\.vsix$/i.test(e)}).map(function(e){return function(){var r=z(e),o=r[0],s=r[1];return n.extensionManagementService.getInstalled(1).then(function(e){return n.extensionGalleryService.getExtension({id:o},s).then(null,function(e){if(e.responseText)try{var t=JSON.parse(e.responseText);return Promise.reject(t.message)}catch(e){}return Promise.reject(e)}).then(function(r){if(!r)return Promise.reject(new Error(function(e){return i.localize(0,null,e) }(s?o+"@"+s:o)+"\n"+V));var a=e.filter(function(e){return A.areSameExtensions({id:A.getGalleryExtensionIdFromLocal(e)},{id:o})})[0];return a?r.version!==a.manifest.version?s||t?(console.log(i.localize(5,null,o,r.version)),n.installFromGallery(o,r)):(console.log(i.localize(6,null,o,a.manifest.version,r.version)),Promise.resolve(null)):(console.log(i.localize(7,null,s?o+"@"+s:o)),Promise.resolve(null)):(console.log(i.localize(8,null,o)),n.installFromGallery(o,r))})})}});return f.sequence(r.concat(o))},e.prototype.validate=function(e,t){return n(this,void 0,void 0,function(){var n,o,s,a;return r(this,function(r){switch(r.label){case 0:return[4,N.getManifest(e)];case 1:if(!(n=r.sent()))throw new Error("Invalid vsix");return o={id:A.getGalleryExtensionId(n.publisher,n.name)},[4,this.extensionManagementService.getInstalled(1)];case 2:return s=r.sent(),(a=s.filter(function(e){return A.areSameExtensions(o,{id:A.getGalleryExtensionIdFromLocal(e)})&&l.gt(e.manifest.version,n.version) })[0])&&!t?(console.log(i.localize(9,null,a.galleryIdentifier.id,a.manifest.version,n.version)),[2,!1]):[2,!0]}})})},e.prototype.installFromGallery=function(e,t){return n(this,void 0,void 0,function(){var n;return r(this,function(r){switch(r.label){case 0:console.log(i.localize(10,null)),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.extensionManagementService.installFromGallery(t)];case 2:return r.sent(),console.log(i.localize(11,null,e,t.version)),[3,4];case 3:if(n=r.sent(),!R.isPromiseCanceledError(n))throw n;return console.log(i.localize(12,null,e)),[3,4];case 4:return[2]}})})},e.prototype.uninstallExtension=function(e){var t=this;return f.sequence(e.map(function(e){return function(){return function(e){return n(this,void 0,void 0,function(){var t,n;return r(this,function(r){switch(r.label){case 0:return/\.vsix$/i.test(e)?(t=c.isAbsolute(e)?e:c.join(process.cwd(),e),[4,N.getManifest(t)]):[2,e];case 1:return n=r.sent(),[2,U(n)]}})})}(e).then(function(e){ return t.extensionManagementService.getInstalled(1).then(function(n){var r=n.filter(function(t){return A.areSameExtensions({id:A.getGalleryExtensionIdFromLocal(t)},{id:e})})[0];return r?(console.log(i.localize(13,null,e)),t.extensionManagementService.uninstall(r,!0).then(function(){return console.log(i.localize(14,null,e))})):Promise.reject(new Error(function(e){return i.localize(1,null,e)}(e)+"\n"+V))})})}}))},e=s([a(0,g.IEnvironmentService),a(1,m.IExtensionManagementService),a(2,m.IExtensionGalleryService)],e)}(),G="monacoworkbench";t.main=function(e){var t=new p.ServiceCollection,n=new v.EnvironmentService(e,process.execPath),r=L.createSpdLogService("cli",M.getLogLevel(n),n.logsPath);process.once("exit",function(){return r.dispose()}),r.info("main",e),t.set(g.IEnvironmentService,n),t.set(M.ILogService,r),t.set(T.IStateService,new d.SyncDescriptor(D.StateService));var i=new h.InstantiationService(t);return i.invokeFunction(function(t){var n=t.get(g.IEnvironmentService),s=t.get(T.IStateService) ;return Promise.all([n.appSettingsHome,n.extensionsPath].map(function(e){return k.mkdirp(e)})).then(function(){var t=n.appRoot,a=n.extensionsPath,c=n.extensionDevelopmentLocationURI,l=n.isBuilt,f=n.installSourcePath,h=new p.ServiceCollection;h.set(w.IConfigurationService,new d.SyncDescriptor(I.ConfigurationService)),h.set(P.IRequestService,new d.SyncDescriptor(_.RequestService)),h.set(m.IExtensionManagementService,new d.SyncDescriptor(y.ExtensionManagementService)),h.set(m.IExtensionGalleryService,new d.SyncDescriptor(b.ExtensionGalleryService));var g=[];if(l&&!c&&!n.args["disable-telemetry"]&&o.default.enableTelemetry){o.default.aiConfig&&o.default.aiConfig.asimovKey&&g.push(new O.AppInsightsAppender(G,null,o.default.aiConfig.asimovKey,r));var v={appender:S.combinedAppender.apply(void 0,g),commonProperties:C.resolveCommonProperties(o.default.commit,u.default.version,s.getItem("telemetry.machineId"),f),piiPaths:[t,a]};h.set(E.ITelemetryService,new d.SyncDescriptor(x.TelemetryService,[v])) }else h.set(E.ITelemetryService,S.NullTelemetryService);return i.createChild(h).createInstance(q).run(e).then(function(){return S.combinedAppender.apply(void 0,g).dispose()})})})}})}).call(this); //# sourceMappingURL=https://ticino.blob.core.windows.net/sourcemaps/08cba2fb66e1673b5f6537fce1de1555d169f0a4/core/vs/code/node/cliProcessMain.js.map
import { compose } from 'redux'; import { connect } from 'react-redux'; import { withPlugins } from '../extend/withPlugins'; import * as actions from '../state/actions'; import { WindowViewer } from '../components/WindowViewer'; import { getSelectedCanvases, getCanvasIndex, getWindowViewType } from '../state/selectors'; /** * mapStateToProps - to hook up connect * @memberof WindowViewer * @private */ const mapStateToProps = (state, { windowId }) => ( { canvasIndex: getCanvasIndex(state, { windowId }), currentCanvases: getSelectedCanvases(state, { windowId }), infoResponses: state.infoResponses, view: getWindowViewType(state, { windowId }), } ); /** * mapDispatchToProps - used to hook up connect to action creators * @memberof WindowViewer * @private */ const mapDispatchToProps = { fetchAnnotation: actions.fetchAnnotation, fetchInfoResponse: actions.fetchInfoResponse, }; const enhance = compose( connect(mapStateToProps, mapDispatchToProps), withPlugins('WindowViewer'), // further HOC go here ); export default enhance(WindowViewer);
"use strict"; const stringify = require("../stringify"); const chalk = require("chalk"); const assert = require("assert"); const Path = require("path"); const xsh = require("xsh"); const replaceCwd = p => xsh.pathCwdNm.replace(p, null, "g"); const stringifyTask = x => { x = stringify(x); /* istanbul ignore next */ if (Path.sep === "\\") { /* istanbul ignore next */ x = x.replace(/\\\\/g, "\\"); } return replaceCwd(x); }; const printNSTasks = (title, names, tasks) => { let guideChar = "."; let nameColor = "cyan"; const taskType = task => task !== null && task !== undefined && task.constructor.name; const maxNameLen = 2 + names.reduce((l, x) => { const task = tasks[x]; if (taskType(task) === "Object" && !task.desc) { return l; } return x.length > l ? x.length : l; }, 0); const printTask = name => { const task = tasks[name]; const tof = taskType(task); const paddedArr = new Array(Math.max(1, maxNameLen - name.length)); const paddedName = chalk[nameColor](` ${name} ${paddedArr.join(guideChar)}`); if (tof === "String") { console.log(paddedName, chalk.magenta(replaceCwd(task))); } else if (tof === "Array") { console.log(paddedName, chalk.green(`${stringifyTask(task)}`)); } else if (tof === "Object") { if (!task.desc) { return; } console.log(paddedName, chalk.yellow(task.desc)); const spacePad = new Array(maxNameLen + 4).join(" "); if (task.task) { console.log(chalk.dim.green(`${spacePad} tasks: ${stringifyTask(task.task)}`)); } if (task.dep) { console.log(chalk.dim.cyan(`${spacePad} deps: ${stringifyTask(task.dep)}`)); } } else if (tof === "Function") { console.log(paddedName, "function", task.name); } else if (tof === "XTaskSpec") { console.log(paddedName, chalk.magenta(replaceCwd(task.toString()))); } else { console.log(paddedName, chalk.red(`Unknown task type ${tof}`)); } guideChar = guideChar === "." ? "-" : "."; nameColor = nameColor === "cyan" ? "blue" : "cyan"; }; console.log(chalk.underline(title)); console.log(""); names.sort().forEach(printTask); console.log(""); }; function printTasks(xtasks) { const namespaces = xtasks._namespaces; const tasks = xtasks._tasks; namespaces.forEach(n => { const nTasks = tasks[n]; assert(nTasks, `Task namespace ${n} is falsy`); if (Object.keys(nTasks).length === 0) { return; } console.log(chalk.inverse.bold.red(`Namespace '${n}'`)); const taskNames = Object.keys(nTasks).reduce((an, tn) => { let lbl; if (tn.match(/(^\.)|([$~])/)) { lbl = "Hidden"; } else if (tn.match(/^[a-zA-Z_0-9]+$/)) { lbl = "Primary"; } else { lbl = "Other"; } an[lbl] = an[lbl] || []; an[lbl].push(tn); return an; }, {}); const isEmpty = x => !x || x.length === 0; ["Primary", "Other"] .filter(tt => !isEmpty(taskNames[tt])) .forEach(tt => printNSTasks(chalk.bold(`${tt} Tasks`), taskNames[tt], nTasks)); }); } module.exports = printTasks;
/** * Created by arikyudin on 03/07/16. */ (function () { 'use strict'; angular.module('Simulator.pages.stats', []) .config(routeConfig) .config(chartJsConfig); function routeConfig($stateProvider) { $stateProvider .state('dashboard', { url: '/dashboard', parent: 'auth', templateUrl: 'app/pages/stats/stats.html', /** @ngInject */ controller: function (baSidebarService, user) { if (baSidebarService.isMenuCollapsed()) { baSidebarService.toggleMenuCollapsed(); } this.isCandidate = (user.role === "Candidate"); this.userType = user.role; if (!this.isCandidate) { //reporting post credit mode is only interesting in the case of customer FS.setUserVars({ "postCreditModeActive_bool": user.postCreditModeNow, }); } }, controllerAs: 'dashboard', resolve: { userType: function (userAuthService) { return userAuthService.getUser(); } }, title: 'STATS.DASHBOARD.TITLE', sidebarMeta: { icon: 'ion-speedometer', order: 100 } }); } function chartJsConfig(ChartJsProvider, baConfigProvider) { var layoutColors = baConfigProvider.colors; // Configure all charts ChartJsProvider.setOptions({ colours: [ layoutColors.primary, layoutColors.danger, layoutColors.warning, layoutColors.success, layoutColors.info, layoutColors.default, layoutColors.primaryDark, layoutColors.successDark, layoutColors.warningLight, layoutColors.successLight, layoutColors.primaryLight], responsive: true, scaleFontColor: layoutColors.defaultText, scaleLineColor: layoutColors.border, pointLabelFontColor: layoutColors.defaultText }); // Configure all line charts ChartJsProvider.setOptions('Line', { datasetFill: false }); } })();
// gh-12 require('fibers'); Fiber(function() { if (!Fiber.current.started) { throw new Error; } }).run(); console.log('pass');
$(document).ready( function(){ var gmapDiv = $("#google-map"); var gmapMarker = gmapDiv.attr("data-address"); gmapDiv.gmap3({ zoom: 16, address: gmapMarker, oomControl: true, navigationControl: true, scrollwheel: false, styles: [ { "featureType":"all", "elementType":"all", "stylers":[ { "saturation":"0" } ] }] }) .marker({ address: gmapMarker, icon: "img/map_pin.png" }) .infowindow({ content: "V Tytana St, Manila, Philippines" }) .then(function (infowindow) { var map = this.get(0); var marker = this.get(1); marker.addListener('click', function() { infowindow.open(map, marker); }); }); });
// @flow /** * @author aha-oretama * @Date 2016/11/13. */ import * as Immutable from 'immutable'; import {MAKE_BARK} from '../actions/dog-actions'; const initialState = Immutable.Map({ hasBarked: false, }); const dogReducer = (state: Object = initialState, action: Object) => { switch (action.type) { case MAKE_BARK: return state.set('hasBarked', action.payload); default: return state; } }; export default dogReducer;
"use strict"; /** * @license * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Rule = void 0; var tslib_1 = require("tslib"); var tsutils_1 = require("tsutils"); var ts = require("typescript"); var Lint = require("../index"); var Rule = /** @class */ (function (_super) { tslib_1.__extends(Rule, _super); function Rule() { return _super !== null && _super.apply(this, arguments) || this; } Rule.prototype.apply = function (sourceFile) { return this.applyWithFunction(sourceFile, walk); }; /* tslint:disable:object-literal-sort-keys */ Rule.metadata = { ruleName: "no-arg", description: "Disallows use of `arguments.callee`.", rationale: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Using `arguments.callee` makes various performance optimizations impossible.\n See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee)\n for more details on why to avoid `arguments.callee`."], ["\n Using \\`arguments.callee\\` makes various performance optimizations impossible.\n See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee)\n for more details on why to avoid \\`arguments.callee\\`."]))), optionsDescription: "Not configurable.", options: null, optionExamples: [true], type: "functionality", typescriptOnly: false, }; /* tslint:enable:object-literal-sort-keys */ Rule.FAILURE_STRING = "Access to arguments.callee is forbidden"; return Rule; }(Lint.Rules.AbstractRule)); exports.Rule = Rule; function walk(ctx) { return ts.forEachChild(ctx.sourceFile, function cb(node) { if (tsutils_1.isPropertyAccessExpression(node) && node.name.text === "callee" && node.expression.kind === ts.SyntaxKind.Identifier && node.expression.text === "arguments") { return ctx.addFailureAtNode(node, Rule.FAILURE_STRING); } return ts.forEachChild(node, cb); }); } var templateObject_1;
import React from 'react' import connect from 'react-redux/lib/connect/connect' import { getAppsInfo, reset, dismissError } from '../actions/AppsInfoActions' import bindActionCreators from 'redux/lib/bindActionCreators' import config from '../../../config' //Components import App from '../components/App' class AppsInfo extends React.Component { constructor(...props) { super(...props) } componentWillUnmount() { clearTimeout(this.timeout) this.props.reset() } componentDidMount() { this.props.dismissError() this.props.getAppsInfo() this.props.reset() } app(appsInfo) { return appsInfo.data.map((app, index) => { return <App name={app.Name} data={ app.Metrics } key={index}/> }) } render() { console.log('RENDER <AppsCharts>') clearTimeout(this.timeout) this.timeout = setTimeout(this.updateCharts, config.timeInterval) const { appsInfo } = this.props console.log(appsInfo) return ( <div className='apps_wrapper'> { appsInfo.data.length > 0 ? this.app(appsInfo) : "null" } </div> ) } } function mapStateToProps(state) { return { appsInfo: state.default.appsInfo } } function mapDispatchToProps(dispatch) { return { getAppsInfo: bindActionCreators(getAppsInfo, dispatch), reset: bindActionCreators(reset, dispatch), dismissError: bindActionCreators(dismissError, dispatch), } } export default connect(mapStateToProps, mapDispatchToProps)(AppsInfo)
/* Add a New Restauratn PAGE */ import React, { Component } from "react" import { Redirect } from "react-router-dom" import { store } from "../../../../store" import { addRestaurantSuccessful, handleChange, snackBarGreenOpen, snackBarRedOpen } from "../../../../actions" import { CancelLink } from "../../../Atoms/CancelLink/CancelLink" import { SnackbarGreen } from "../../../Atoms/SnackbarGreen/SnackbarGreen" import { SnackbarRed } from "../../../Atoms/SnackbarRed/SnackbarRed" import { Button } from "../../../Atoms/Button/Button" import { InputText } from "../../../Atoms/InputText/InputText" import { InputTextDoubleLength } from "../../../Atoms/InputTextDoubleLength/InputTextDoubleLength" import { InputTextTripleLength } from "../../../Atoms/InputTextTripleLength/InputTextTripleLength" import { TextArea } from "../../../Atoms/TextArea/TextArea" import axios from "axios" import "../css/RestaurantNew.css" class RestaurantNew extends Component { handleChange(e) { store.dispatch(handleChange(e)) } handleSubmit(e) { e.preventDefault() const { name, streetAddress, city, state, zip, phone, latitude, longitude, image, website, favFood, rating, cuisine, price, notes, username } = store.getState() const newRestaurant = { name: name, streetAddress: streetAddress, city: city, state: state, zip: zip, phone: phone, latitude: latitude, longitude: longitude, image: image, website: website, favFood: favFood, rating: rating, cuisine: cuisine, price: price, notes: notes, addedBy: username } axios.post("http://localhost:9000/restaurant", newRestaurant) .then((response) => { console.log(response) if (response.data.name === "MongoError") { store.dispatch(snackBarRedOpen(true, "Restaurant was not added...")) setTimeout(() => { store.dispatch(snackBarRedOpen(false, "")) }, 2000); } else { store.dispatch(snackBarGreenOpen(true, "Restaurant was added!")) setTimeout(() => { store.dispatch(snackBarGreenOpen(false, "")) store.dispatch(addRestaurantSuccessful()) }, 2000); } }) .catch((err) => console.log(err)) } render() { const { addRestaurantSuccessful, msg, snackBarGreenOpen, snackBarRedOpen, cancel } = store.getState() return ( <div className="RestaurantNew-main-container"> {addRestaurantSuccessful && <Redirect to="/restaurant" />} {cancel && <Redirect to="/landing" />} <div className="RestaurantNew-form-container"> <h1 className="RestaurantNew-h1">Add a New Restaurant</h1> <form className="RestaurantNew-form" onSubmit={this.handleSubmit} > <div className="RestaurantNew-div-row"> <InputText label="Restaurant Name:" type="text" name="name" handleChange={this.handleChange} /> </div> <div className="RestaurantNew-div-row"> <InputTextDoubleLength label="Street Address:" type="text" name="streetAddress" inputClassName="RestaurantNew-input-address RestaurantNew-input" handleChange={this.handleChange} /> </div> <div className="RestaurantNew-div-row"> <InputText label="City:" type="text" name="city" handleChange={this.handleChange} /> <InputText label="State:" type="text" name="state" handleChange={this.handleChange} /> <InputText label="Zip Code:" type="text" name="zip" handleChange={this.handleChange} /> </div> <div className="RestaurantNew-div-row"> <InputText label="Phone:" type="text" name="phone" handleChange={this.handleChange} /> <InputText label="Latitude:" type="text" name="latitude" handleChange={this.handleChange} /> <InputText label="Longitude:" type="text" name="longitude" handleChange={this.handleChange} /> </div> <div className="RestaurantNew-div-row"> <InputTextTripleLength label="Restaurant Image URL:" type="text" name="image" inputClassName="RestaurantNew-input-image RestaurantNew-input" handleChange={this.handleChange} /> </div> <div className="RestaurantNew-div-row"> <InputTextTripleLength label="Website URL:" type="text" name="website" inputClassName="RestaurantNew-input-image RestaurantNew-input" handleChange={this.handleChange} /> </div> <div className="RestaurantNew-div-row"> <InputText label="Favorite Food:" type="text" name="favFood" handleChange={this.handleChange} /> <InputText label="Rating:" type="text" name="rating" handleChange={this.handleChange} /> </div> <div className="RestaurantNew-div-row"> <label className="RestaurantNew-label"><span className="RestaurantNew-span">Cuisine:</span> <div> <select type="text" name="cuisine" className="RestaurantNew-select" onChange={this.handleChange}> <option value="">Select a Cuisine</option> <option value="american">American</option> <option value="cajun">Cajun</option> <option value="french">French</option> <option value="german">German</option> <option value="indian">Indian</option> <option value="italian">Italian</option> <option value="japanese">Japanese</option> <option value="korean">Korean</option> <option value="mexican">Mexican</option> <option value="spanish">Spanish</option> <option value="thai">Thai</option> </select> </div> </label> <label className="RestaurantNew-label"><span className="RestaurantNew-span">Cost:</span> <div> <select type="text" name="price" className="RestaurantNew-select" onChange={this.handleChange}> <option value="">Total Price Per Person</option> <option value="under10">Less than $10 each</option> <option value="under15">Less than $15 each</option> <option value="under20">Less than $20 each</option> <option value="under25">Less than $25 each</option> <option value="under30">Less than $30 each</option> <option value="under35">Less than $35 each</option> <option value="under40">Less than $40 each</option> <option value="under45">Less than $45 each</option> <option value="under50">Less than $50 each</option> <option value="over50">More than $50 each</option> </select> </div> </label> </div> <div className="RestaurantNew-div-row"> <TextArea rows="5" cols="89" label="Notes:" name="notes" placeholder="Enter Personal Notes Here" type="text" handleChange={this.handleChange} /> </div> {snackBarGreenOpen && <SnackbarGreen msg={msg} />} {snackBarRedOpen && <SnackbarRed msg={msg} />} <div className="RestaurantNew-div-row RestaurantNew-submit-button"> <Button label="Submit" /> </div> </form> </div> <div> <CancelLink /> </div> </div > ) } } export default RestaurantNew
'use strict'; var project = require('../../project.json'), flags = require('minimist')(process.argv.slice(2)); var envOpts = {}; if (flags.watch) { envOpts.watch = true; envOpts.debug = true; envOpts.minify = false; envOpts.env = 'dev'; } if (flags.staging) { envOpts.watch = false; envOpts.debug = false; envOpts.minify = true; envOpts.env = 'staging'; } if (flags.live) { envOpts.watch = false; envOpts.debug = false; envOpts.minify = true; envOpts.env = 'live'; } var options = { cssEntry : project.foldersName.entry + '/styles/', cssDest : project.foldersName.build + '/styles/', jsEntry : project.foldersName.entry + '/scripts/', jsDest : project.foldersName.build + '/scripts/', jsVendorsEntry : project.foldersName.entry + '/scripts/vendors/', mainJS : 'app.js', imageEntry : project.foldersName.entry + '/assets/images/', imageDest : project.foldersName.build + '/assets/images/', copyBase : project.foldersName.entry + '/assets/', copyDest : project.foldersName.build + '/assets/', jsVendorsDest : project.foldersName.build + '/scripts/vendors/', envOpts : envOpts } module.exports = options;
import React from "react"; import Svg, { Path } from "react-native-svg"; const ShieldErrorF = ({ color, ...props }) => ( <Svg viewBox="0 0 54 64" {...props}> <Path d="M27 0L0 8v20c.3 16.5 27 36 27 36s26.7-19.5 27-36V8L27 0zm10.5 40.1l-1.4 1.4c-.4.4-1 .4-1.4 0l-7.8-7.8-7.8 7.8c-.4.4-1 .4-1.4 0l-1.4-1.4c-.4-.4-.4-1 0-1.4l7.8-7.8-7.8-7.8c-.4-.4-.4-1 0-1.4l1.4-1.4c.4-.4 1-.4 1.4 0l7.8 7.8 7.8-7.8c.4-.4 1-.4 1.4 0l1.4 1.4c.4.4.4 1 0 1.4l-7.8 7.8 7.8 7.8c.4.4.4 1 0 1.4z" fill={color} /> </Svg> ); export default ShieldErrorF;
'use strict'; // --------------------------------------------------------------------------- const Exchange = require ('./base/Exchange'); const { ExchangeError } = require ('./base/errors'); // --------------------------------------------------------------------------- module.exports = class zaif extends Exchange { describe () { return this.deepExtend (super.describe (), { 'id': 'zaif', 'name': 'Zaif', 'countries': [ 'JP' ], 'rateLimit': 2000, 'version': '1', 'has': { 'CORS': false, 'createMarketOrder': false, 'fetchOpenOrders': true, 'fetchClosedOrders': true, 'withdraw': true, }, 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/27766927-39ca2ada-5eeb-11e7-972f-1b4199518ca6.jpg', 'api': 'https://api.zaif.jp', 'www': 'https://zaif.jp', 'doc': [ 'http://techbureau-api-document.readthedocs.io/ja/latest/index.html', 'https://corp.zaif.jp/api-docs', 'https://corp.zaif.jp/api-docs/api_links', 'https://www.npmjs.com/package/zaif.jp', 'https://github.com/you21979/node-zaif', ], 'fees': 'https://zaif.jp/fee?lang=en', }, 'fees': { 'trading': { 'percentage': true, 'taker': -0.0001, 'maker': -0.0005, }, }, 'api': { 'public': { 'get': [ 'depth/{pair}', 'currencies/{pair}', 'currencies/all', 'currency_pairs/{pair}', 'currency_pairs/all', 'last_price/{pair}', 'ticker/{pair}', 'trades/{pair}', ], }, 'private': { 'post': [ 'active_orders', 'cancel_order', 'deposit_history', 'get_id_info', 'get_info', 'get_info2', 'get_personal_info', 'trade', 'trade_history', 'withdraw', 'withdraw_history', ], }, 'ecapi': { 'post': [ 'createInvoice', 'getInvoice', 'getInvoiceIdsByOrderNumber', 'cancelInvoice', ], }, 'tlapi': { 'post': [ 'get_positions', 'position_history', 'active_positions', 'create_position', 'change_position', 'cancel_position', ], }, 'fapi': { 'get': [ 'groups/{group_id}', 'last_price/{group_id}/{pair}', 'ticker/{group_id}/{pair}', 'trades/{group_id}/{pair}', 'depth/{group_id}/{pair}', ], }, }, }); } async fetchMarkets () { let markets = await this.publicGetCurrencyPairsAll (); let result = []; for (let p = 0; p < markets.length; p++) { let market = markets[p]; let id = market['currency_pair']; let symbol = market['name']; let [ base, quote ] = symbol.split ('/'); let precision = { 'amount': -Math.log10 (market['item_unit_step']), 'price': market['aux_unit_point'], }; result.push ({ 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'active': true, // can trade or not 'precision': precision, 'limits': { 'amount': { 'min': this.safeFloat (market, 'item_unit_min'), 'max': undefined, }, 'price': { 'min': this.safeFloat (market, 'aux_unit_min'), 'max': undefined, }, 'cost': { 'min': undefined, 'max': undefined, }, }, 'info': market, }); } return result; } async fetchBalance (params = {}) { await this.loadMarkets (); let response = await this.privatePostGetInfo (); let balances = response['return']; let result = { 'info': balances }; let currencies = Object.keys (balances['funds']); for (let c = 0; c < currencies.length; c++) { let currency = currencies[c]; let balance = balances['funds'][currency]; let uppercase = currency.toUpperCase (); let account = { 'free': balance, 'used': 0.0, 'total': balance, }; if ('deposit' in balances) { if (currency in balances['deposit']) { account['total'] = balances['deposit'][currency]; account['used'] = account['total'] - account['free']; } } result[uppercase] = account; } return this.parseBalance (result); } async fetchOrderBook (symbol, limit = undefined, params = {}) { await this.loadMarkets (); let orderbook = await this.publicGetDepthPair (this.extend ({ 'pair': this.marketId (symbol), }, params)); return this.parseOrderBook (orderbook); } async fetchTicker (symbol, params = {}) { await this.loadMarkets (); let ticker = await this.publicGetTickerPair (this.extend ({ 'pair': this.marketId (symbol), }, params)); let timestamp = this.milliseconds (); let vwap = ticker['vwap']; let baseVolume = ticker['volume']; let quoteVolume = baseVolume * vwap; let last = ticker['last']; return { 'symbol': symbol, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'high': ticker['high'], 'low': ticker['low'], 'bid': ticker['bid'], 'bidVolume': undefined, 'ask': ticker['ask'], 'askVolume': undefined, 'vwap': vwap, 'open': undefined, 'close': last, 'last': last, 'previousClose': undefined, 'change': undefined, 'percentage': undefined, 'average': undefined, 'baseVolume': baseVolume, 'quoteVolume': quoteVolume, 'info': ticker, }; } parseTrade (trade, market = undefined) { let side = (trade['trade_type'] === 'bid') ? 'buy' : 'sell'; let timestamp = trade['date'] * 1000; let id = this.safeString (trade, 'id'); id = this.safeString (trade, 'tid', id); if (!market) market = this.markets_by_id[trade['currency_pair']]; return { 'id': id.toString (), 'info': trade, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'symbol': market['symbol'], 'type': undefined, 'side': side, 'price': trade['price'], 'amount': trade['amount'], }; } async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let market = this.market (symbol); let response = await this.publicGetTradesPair (this.extend ({ 'pair': market['id'], }, params)); return this.parseTrades (response, market, since, limit); } async createOrder (symbol, type, side, amount, price = undefined, params = {}) { await this.loadMarkets (); if (type === 'market') throw new ExchangeError (this.id + ' allows limit orders only'); let response = await this.privatePostTrade (this.extend ({ 'currency_pair': this.marketId (symbol), 'action': (side === 'buy') ? 'bid' : 'ask', 'amount': amount, 'price': price, }, params)); return { 'info': response, 'id': response['return']['order_id'].toString (), }; } async cancelOrder (id, symbol = undefined, params = {}) { return await this.privatePostCancelOrder (this.extend ({ 'order_id': id, }, params)); } parseOrder (order, market = undefined) { let side = (order['action'] === 'bid') ? 'buy' : 'sell'; let timestamp = parseInt (order['timestamp']) * 1000; if (!market) market = this.markets_by_id[order['currency_pair']]; let price = order['price']; let amount = order['amount']; return { 'id': order['id'].toString (), 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'lastTradeTimestamp': undefined, 'status': 'open', 'symbol': market['symbol'], 'type': 'limit', 'side': side, 'price': price, 'cost': price * amount, 'amount': amount, 'filled': undefined, 'remaining': undefined, 'trades': undefined, 'fee': undefined, }; } parseOrders (orders, market = undefined, since = undefined, limit = undefined) { let ids = Object.keys (orders); let result = []; for (let i = 0; i < ids.length; i++) { let id = ids[i]; let order = orders[id]; let extended = this.extend (order, { 'id': id }); result.push (this.parseOrder (extended, market)); } return this.filterBySinceLimit (result, since, limit); } async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let market = undefined; let request = { // 'is_token': false, // 'is_token_both': false, }; if (symbol) { market = this.market (symbol); request['currency_pair'] = market['id']; } let response = await this.privatePostActiveOrders (this.extend (request, params)); return this.parseOrders (response['return'], market, since, limit); } async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { await this.loadMarkets (); let market = undefined; let request = { // 'from': 0, // 'count': 1000, // 'from_id': 0, // 'end_id': 1000, // 'order': 'DESC', // 'since': 1503821051, // 'end': 1503821051, // 'is_token': false, }; if (symbol) { market = this.market (symbol); request['currency_pair'] = market['id']; } let response = await this.privatePostTradeHistory (this.extend (request, params)); return this.parseOrders (response['return'], market, since, limit); } async withdraw (currency, amount, address, tag = undefined, params = {}) { this.checkAddress (address); await this.loadMarkets (); if (currency === 'JPY') throw new ExchangeError (this.id + ' does not allow ' + currency + ' withdrawals'); let result = await this.privatePostWithdraw (this.extend ({ 'currency': currency, 'amount': amount, 'address': address, // 'message': 'Hi!', // XEM only // 'opt_fee': 0.003, // BTC and MONA only }, params)); return { 'info': result, 'id': result['return']['txid'], 'fee': result['return']['fee'], }; } nonce () { let nonce = parseFloat (this.milliseconds () / 1000); return nonce.toFixed (8); } sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { let url = this.urls['api'] + '/'; if (api === 'public') { url += 'api/' + this.version + '/' + this.implodeParams (path, params); } else if (api === 'fapi') { url += 'fapi/' + this.version + '/' + this.implodeParams (path, params); } else { this.checkRequiredCredentials (); if (api === 'ecapi') { url += 'ecapi'; } else if (api === 'tlapi') { url += 'tlapi'; } else { url += 'tapi'; } let nonce = this.nonce (); body = this.urlencode (this.extend ({ 'method': path, 'nonce': nonce, }, params)); headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Key': this.apiKey, 'Sign': this.hmac (this.encode (body), this.encode (this.secret), 'sha512'), }; } return { 'url': url, 'method': method, 'body': body, 'headers': headers }; } async request (path, api = 'api', method = 'GET', params = {}, headers = undefined, body = undefined) { let response = await this.fetch2 (path, api, method, params, headers, body); if ('error' in response) throw new ExchangeError (this.id + ' ' + response['error']); if ('success' in response) if (!response['success']) throw new ExchangeError (this.id + ' ' + this.json (response)); return response; } };
'use strict'; const { artifacts, contract, web3 } = require('hardhat'); const { assert, addSnapshotBeforeRestoreAfterEach } = require('./common'); const { currentTime, fastForward, toUnit, bytesToString } = require('../utils')(); const { ensureOnlyExpectedMutativeFunctions, onlyGivenAddressCanInvoke, convertToDecimals, } = require('./helpers'); const { setupContract, setupAllContracts } = require('./setup'); const { toBytes32, constants: { ZERO_ADDRESS }, defaults: { RATE_STALE_PERIOD }, } = require('../..'); const { toBN } = require('web3-utils'); const MockAggregator = artifacts.require('MockAggregatorV2V3'); const getRandomCurrencyKey = () => Math.random() .toString(36) .substring(2, 6) .toUpperCase(); const createRandomKeysAndRates = quantity => { const uniqueCurrencyKeys = {}; for (let i = 0; i < quantity; i++) { const rate = Math.random() * 100; const key = toBytes32(getRandomCurrencyKey()); uniqueCurrencyKeys[key] = web3.utils.toWei(rate.toFixed(18), 'ether'); } const rates = []; const currencyKeys = []; Object.entries(uniqueCurrencyKeys).forEach(([key, rate]) => { currencyKeys.push(key); rates.push(rate); }); return { currencyKeys, rates }; }; contract('Exchange Rates', async accounts => { const [deployerAccount, owner, oracle, accountOne, accountTwo] = accounts; const [PERI, pUSD, pEUR, pAUD, fastGasPrice] = [ 'PERI', 'pUSD', 'pEUR', 'pAUD', 'fastGasPrice', ].map(toBytes32); let instance; let systemSettings; let aggregatorJPY; let aggregatorXTZ; let aggregatorFastGasPrice; let initialTime; let timeSent; let resolver; let mockFlagsInterface; before(async () => { initialTime = await currentTime(); ({ ExchangeRates: instance, SystemSettings: systemSettings, AddressResolver: resolver, } = await setupAllContracts({ accounts, contracts: ['ExchangeRates', 'SystemSettings', 'AddressResolver', 'StakingStateUSDC'], })); aggregatorJPY = await MockAggregator.new({ from: owner }); aggregatorXTZ = await MockAggregator.new({ from: owner }); aggregatorFastGasPrice = await MockAggregator.new({ from: owner }); aggregatorJPY.setDecimals('8'); aggregatorXTZ.setDecimals('8'); aggregatorFastGasPrice.setDecimals('0'); // create but don't connect up the mock flags interface yet mockFlagsInterface = await artifacts.require('MockFlagsInterface').new(); }); addSnapshotBeforeRestoreAfterEach(); beforeEach(async () => { timeSent = await currentTime(); }); it('only expected functions should be mutative', () => { ensureOnlyExpectedMutativeFunctions({ abi: instance.abi, ignoreParents: ['Owned', 'MixinResolver'], expected: [ 'addAggregator', 'deleteRate', 'freezeRate', 'removeAggregator', 'removeInversePricing', 'setInversePricing', 'setOracle', 'updateRates', 'setCurrencyToExternalAggregator', ], }); }); describe('constructor', () => { it('should set constructor params on deployment', async () => { assert.equal(await instance.owner(), owner); assert.equal(await instance.oracle(), oracle); assert.etherEqual(await instance.rateForCurrency(pUSD), '1'); assert.etherEqual(await instance.rateForCurrency(PERI), '0.2'); // Ensure that when the rate isn't found, 0 is returned as the exchange rate. assert.etherEqual(await instance.rateForCurrency(toBytes32('OTHER')), '0'); const lastUpdatedTimeSUSD = await instance.lastRateUpdateTimes.call(pUSD); assert.isAtLeast(lastUpdatedTimeSUSD.toNumber(), initialTime); const lastUpdatedTimeOTHER = await instance.lastRateUpdateTimes.call(toBytes32('OTHER')); assert.equal(lastUpdatedTimeOTHER.toNumber(), 0); const lastUpdatedTimePERI = await instance.lastRateUpdateTimes.call(PERI); assert.isAtLeast(lastUpdatedTimePERI.toNumber(), initialTime); const pUSDRate = await instance.rateForCurrency(pUSD); assert.bnEqual(pUSDRate, toUnit('1')); }); it('two different currencies in same array should mean that the second one overrides', async () => { const creationTime = await currentTime(); const firstAmount = '4.33'; const secondAmount = firstAmount + 10; const instance = await setupContract({ accounts, contract: 'ExchangeRates', args: [ owner, oracle, resolver.address, [toBytes32('CARTER'), toBytes32('CARTOON')], [web3.utils.toWei(firstAmount, 'ether'), web3.utils.toWei(secondAmount, 'ether')], ], }); assert.etherEqual(await instance.rateForCurrency(toBytes32('CARTER')), firstAmount); assert.etherEqual(await instance.rateForCurrency(toBytes32('CARTOON')), secondAmount); const lastUpdatedTime = await instance.lastRateUpdateTimes.call(toBytes32('CARTER')); assert.isAtLeast(lastUpdatedTime.toNumber(), creationTime); }); it('should revert when number of currency keys > new rates length on create', async () => { await assert.revert( setupContract({ accounts, contract: 'ExchangeRates', args: [ owner, oracle, resolver.address, [PERI, toBytes32('GOLD')], [web3.utils.toWei('0.2', 'ether')], ], }), 'Currency key length and rate length must match' ); }); it('should limit to 32 bytes if currency key > 32 bytes on create', async () => { const creationTime = await currentTime(); const amount = '4.33'; const instance = await setupContract({ accounts, contract: 'ExchangeRates', args: [ owner, oracle, resolver.address, [toBytes32('ABCDEFGHIJKLMNOPQRSTUVXYZ1234567')], [web3.utils.toWei(amount, 'ether')], ], }); assert.etherEqual( await instance.rateForCurrency(toBytes32('ABCDEFGHIJKLMNOPQRSTUVXYZ1234567')), amount ); assert.etherNotEqual( await instance.rateForCurrency(toBytes32('ABCDEFGHIJKLMNOPQRSTUVXYZ123456')), amount ); const lastUpdatedTime = await instance.lastRateUpdateTimes.call( toBytes32('ABCDEFGHIJKLMNOPQRSTUVXYZ1234567') ); assert.isAtLeast(lastUpdatedTime.toNumber(), creationTime); }); it("shouldn't be able to set exchange rate to 0 on create", async () => { await assert.revert( setupContract({ accounts, contract: 'ExchangeRates', args: [owner, oracle, resolver.address, [PERI], ['0']], }), 'Zero is not a valid rate, please call deleteRate instead' ); }); it('should be able to handle lots of currencies on creation', async () => { const creationTime = await currentTime(); const numberOfCurrencies = 100; const { currencyKeys, rates } = createRandomKeysAndRates(numberOfCurrencies); const instance = await setupContract({ accounts, contract: 'ExchangeRates', args: [owner, oracle, resolver.address, currencyKeys, rates], }); for (let i = 0; i < currencyKeys.length; i++) { assert.bnEqual(await instance.rateForCurrency(currencyKeys[i]), rates[i]); const lastUpdatedTime = await instance.lastRateUpdateTimes.call(currencyKeys[i]); assert.isAtLeast(lastUpdatedTime.toNumber(), creationTime); } }); }); describe('updateRates()', () => { it('should be able to update rates of only one currency without affecting other rates', async () => { await fastForward(1); await instance.updateRates( [toBytes32('lABC'), toBytes32('lDEF'), toBytes32('lGHI')], [ web3.utils.toWei('1.3', 'ether'), web3.utils.toWei('2.4', 'ether'), web3.utils.toWei('3.5', 'ether'), ], timeSent, { from: oracle } ); await fastForward(10); const updatedTime = timeSent + 10; const updatedRate = '64.33'; await instance.updateRates( [toBytes32('lABC')], [web3.utils.toWei(updatedRate, 'ether')], updatedTime, { from: oracle } ); const updatedTimelDEF = await instance.lastRateUpdateTimes.call(toBytes32('lDEF')); const updatedTimelGHI = await instance.lastRateUpdateTimes.call(toBytes32('lGHI')); assert.etherEqual(await instance.rateForCurrency(toBytes32('lABC')), updatedRate); assert.etherEqual(await instance.rateForCurrency(toBytes32('lDEF')), '2.4'); assert.etherEqual(await instance.rateForCurrency(toBytes32('lGHI')), '3.5'); const lastUpdatedTimeLABC = await instance.lastRateUpdateTimes.call(toBytes32('lABC')); assert.equal(lastUpdatedTimeLABC.toNumber(), updatedTime); const lastUpdatedTimeLDEF = await instance.lastRateUpdateTimes.call(toBytes32('lDEF')); assert.equal(lastUpdatedTimeLDEF.toNumber(), updatedTimelDEF.toNumber()); const lastUpdatedTimeLGHI = await instance.lastRateUpdateTimes.call(toBytes32('lGHI')); assert.equal(lastUpdatedTimeLGHI.toNumber(), updatedTimelGHI.toNumber()); }); it('should be able to update rates of all currencies', async () => { await fastForward(1); await instance.updateRates( [toBytes32('lABC'), toBytes32('lDEF'), toBytes32('lGHI')], [ web3.utils.toWei('1.3', 'ether'), web3.utils.toWei('2.4', 'ether'), web3.utils.toWei('3.5', 'ether'), ], timeSent, { from: oracle } ); await fastForward(5); const updatedTime = timeSent + 5; const updatedRate1 = '64.33'; const updatedRate2 = '2.54'; const updatedRate3 = '10.99'; await instance.updateRates( [toBytes32('lABC'), toBytes32('lDEF'), toBytes32('lGHI')], [ web3.utils.toWei(updatedRate1, 'ether'), web3.utils.toWei(updatedRate2, 'ether'), web3.utils.toWei(updatedRate3, 'ether'), ], updatedTime, { from: oracle } ); assert.etherEqual(await instance.rateForCurrency(toBytes32('lABC')), updatedRate1); assert.etherEqual(await instance.rateForCurrency(toBytes32('lDEF')), updatedRate2); assert.etherEqual(await instance.rateForCurrency(toBytes32('lGHI')), updatedRate3); const lastUpdatedTimeLABC = await instance.lastRateUpdateTimes.call(toBytes32('lABC')); assert.equal(lastUpdatedTimeLABC.toNumber(), updatedTime); const lastUpdatedTimeLDEF = await instance.lastRateUpdateTimes.call(toBytes32('lDEF')); assert.equal(lastUpdatedTimeLDEF.toNumber(), updatedTime); const lastUpdatedTimeLGHI = await instance.lastRateUpdateTimes.call(toBytes32('lGHI')); assert.equal(lastUpdatedTimeLGHI.toNumber(), updatedTime); }); it('should revert when trying to set pUSD price', async () => { await fastForward(1); await assert.revert( instance.updateRates([pUSD], [web3.utils.toWei('1.0', 'ether')], timeSent, { from: oracle, }), "Rate of pUSD cannot be updated, it's always UNIT" ); }); it('should emit RatesUpdated event when rate updated', async () => { const rates = [ web3.utils.toWei('1.3', 'ether'), web3.utils.toWei('2.4', 'ether'), web3.utils.toWei('3.5', 'ether'), ]; const keys = ['lABC', 'lDEF', 'lGHI']; const currencyKeys = keys.map(toBytes32); const txn = await instance.updateRates(currencyKeys, rates, await currentTime(), { from: oracle, }); assert.eventEqual(txn, 'RatesUpdated', { currencyKeys, newRates: rates, }); }); it('should be able to handle lots of currency updates', async () => { const numberOfCurrencies = 150; const { currencyKeys, rates } = createRandomKeysAndRates(numberOfCurrencies); const updatedTime = await currentTime(); await instance.updateRates(currencyKeys, rates, updatedTime, { from: oracle }); for (let i = 0; i < currencyKeys.length; i++) { assert.equal(await instance.rateForCurrency(currencyKeys[i]), rates[i]); const lastUpdatedTime = await instance.lastRateUpdateTimes.call(currencyKeys[i]); assert.equal(lastUpdatedTime.toNumber(), updatedTime); } }); it('should revert when currency keys length != new rates length on update', async () => { await assert.revert( instance.updateRates( [pUSD, PERI, toBytes32('GOLD')], [web3.utils.toWei('1', 'ether'), web3.utils.toWei('0.2', 'ether')], await currentTime(), { from: oracle } ), 'Currency key array length must match rates array length' ); }); it('should not be able to set exchange rate to 0 on update', async () => { await assert.revert( instance.updateRates( [toBytes32('ZERO')], [web3.utils.toWei('0', 'ether')], await currentTime(), { from: oracle } ), 'Zero is not a valid rate, please call deleteRate instead' ); }); it('only oracle can update exchange rates', async () => { await onlyGivenAddressCanInvoke({ fnc: instance.updateRates, args: [ [toBytes32('GOLD'), toBytes32('FOOL')], [web3.utils.toWei('10', 'ether'), web3.utils.toWei('0.9', 'ether')], timeSent, ], address: oracle, accounts, skipPassCheck: true, reason: 'Only the oracle can perform this action', }); assert.etherNotEqual(await instance.rateForCurrency(toBytes32('GOLD')), '10'); assert.etherNotEqual(await instance.rateForCurrency(toBytes32('FOOL')), '0.9'); const updatedTime = await currentTime(); await instance.updateRates( [toBytes32('GOLD'), toBytes32('FOOL')], [web3.utils.toWei('10', 'ether'), web3.utils.toWei('0.9', 'ether')], updatedTime, { from: oracle } ); assert.etherEqual(await instance.rateForCurrency(toBytes32('GOLD')), '10'); assert.etherEqual(await instance.rateForCurrency(toBytes32('FOOL')), '0.9'); const lastUpdatedTimeGOLD = await instance.lastRateUpdateTimes.call(toBytes32('GOLD')); assert.equal(lastUpdatedTimeGOLD.toNumber(), updatedTime); const lastUpdatedTimeFOOL = await instance.lastRateUpdateTimes.call(toBytes32('FOOL')); assert.equal(lastUpdatedTimeFOOL.toNumber(), updatedTime); }); it('should not be able to update rates if they are too far in the future', async () => { const timeTooFarInFuture = (await currentTime()) + 10 * 61; await assert.revert( instance.updateRates( [toBytes32('GOLD')], [web3.utils.toWei('1', 'ether')], timeTooFarInFuture, { from: oracle } ), 'Time is too far into the future' ); }); }); describe('setOracle()', () => { it("only the owner should be able to change the oracle's address", async () => { await onlyGivenAddressCanInvoke({ fnc: instance.setOracle, args: [oracle], address: owner, accounts, skipPassCheck: true, }); await instance.setOracle(accountOne, { from: owner }); assert.equal(await instance.oracle.call(), accountOne); assert.notEqual(await instance.oracle.call(), oracle); }); it('should emit event on successful oracle address update', async () => { // Ensure oracle is set to oracle address originally await instance.setOracle(oracle, { from: owner }); assert.equal(await instance.oracle.call(), oracle); const txn = await instance.setOracle(accountOne, { from: owner }); assert.eventEqual(txn, 'OracleUpdated', { newOracle: accountOne, }); }); }); describe('setCurrencyToExternalAggregator()', () => { it('only the owner should be able to currency external status', async () => { await onlyGivenAddressCanInvoke({ fnc: instance.setCurrencyToExternalAggregator, args: [toBytes32('USDC'), true], address: owner, accounts, skipPassCheck: true, }); await instance.setCurrencyToExternalAggregator(toBytes32('USDC'), true, { from: owner }); assert.equal(await instance.currencyByExternal(toBytes32('USDC')), true); }); }); describe('deleteRate()', () => { it('should be able to remove specific rate', async () => { const foolsRate = '0.002'; const encodedRateGOLD = toBytes32('GOLD'); await instance.updateRates( [encodedRateGOLD, toBytes32('FOOL')], [web3.utils.toWei('10.123', 'ether'), web3.utils.toWei(foolsRate, 'ether')], timeSent, { from: oracle } ); const beforeRate = await instance.rateForCurrency(encodedRateGOLD); const beforeRateUpdatedTime = await instance.lastRateUpdateTimes.call(encodedRateGOLD); await instance.deleteRate(encodedRateGOLD, { from: oracle }); const afterRate = await instance.rateForCurrency(encodedRateGOLD); const afterRateUpdatedTime = await instance.lastRateUpdateTimes.call(encodedRateGOLD); assert.notEqual(afterRate, beforeRate); assert.equal(afterRate, '0'); assert.notEqual(afterRateUpdatedTime, beforeRateUpdatedTime); assert.equal(afterRateUpdatedTime, '0'); // Other rates are unaffected assert.etherEqual(await instance.rateForCurrency(toBytes32('FOOL')), foolsRate); }); it('only oracle can delete a rate', async () => { // Assume that the contract is already set up with a valid oracle account called 'oracle' const encodedRateName = toBytes32('COOL'); await instance.updateRates( [encodedRateName], [web3.utils.toWei('10.123', 'ether')], await currentTime(), { from: oracle } ); await onlyGivenAddressCanInvoke({ fnc: instance.deleteRate, args: [encodedRateName], accounts, address: oracle, reason: 'Only the oracle can perform this action', }); }); it("deleting rate that doesn't exist causes revert", async () => { // This key shouldn't exist but let's do the best we can to ensure that it doesn't const encodedCurrencyKey = toBytes32('7NEQ'); const currentRate = await instance.rateForCurrency(encodedCurrencyKey); if (currentRate > 0) { await instance.deleteRate(encodedCurrencyKey, { from: oracle }); } // Ensure rate deletion attempt results in revert await assert.revert( instance.deleteRate(encodedCurrencyKey, { from: oracle }), 'Rate is zero' ); assert.etherEqual(await instance.rateForCurrency(encodedCurrencyKey), '0'); }); it('should emit RateDeleted event when rate deleted', async () => { const updatedTime = await currentTime(); const rate = 'GOLD'; const encodedRate = toBytes32(rate); await instance.updateRates( [encodedRate], [web3.utils.toWei('10.123', 'ether')], updatedTime, { from: oracle, } ); const txn = await instance.deleteRate(encodedRate, { from: oracle }); assert.eventEqual(txn, 'RateDeleted', { currencyKey: encodedRate }); }); }); describe('getting rates', () => { it('should be able to get exchange rate with key', async () => { const updatedTime = await currentTime(); const encodedRate = toBytes32('GOLD'); const rateValueEncodedStr = web3.utils.toWei('10.123', 'ether'); await instance.updateRates([encodedRate], [rateValueEncodedStr], updatedTime, { from: oracle, }); const rate = await instance.rateForCurrency(encodedRate); assert.equal(rate, rateValueEncodedStr); }); it('all users should be able to get exchange rate with key', async () => { const updatedTime = await currentTime(); const encodedRate = toBytes32('FETC'); const rateValueEncodedStr = web3.utils.toWei('910.6661293879', 'ether'); await instance.updateRates([encodedRate], [rateValueEncodedStr], updatedTime, { from: oracle, }); await instance.rateForCurrency(encodedRate, { from: accountOne }); await instance.rateForCurrency(encodedRate, { from: accountTwo }); await instance.rateForCurrency(encodedRate, { from: oracle }); await instance.rateForCurrency(encodedRate, { from: owner }); await instance.rateForCurrency(encodedRate, { from: deployerAccount }); }); it('Fetching non-existent rate returns 0', async () => { const encodedRateKey = toBytes32('GOLD'); const currentRate = await instance.rateForCurrency(encodedRateKey); if (currentRate > 0) { await instance.deleteRate(encodedRateKey, { from: oracle }); } const rate = await instance.rateForCurrency(encodedRateKey); assert.equal(rate.toString(), '0'); }); it('should be able to get the latest exchange rate and updated time', async () => { const updatedTime = await currentTime(); const encodedRate = toBytes32('GOLD'); const rateValueEncodedStr = web3.utils.toWei('10.123', 'ether'); await instance.updateRates([encodedRate], [rateValueEncodedStr], updatedTime, { from: oracle, }); const rateAndTime = await instance.rateAndUpdatedTime(encodedRate); assert.equal(rateAndTime.rate, rateValueEncodedStr); assert.bnEqual(rateAndTime.time, updatedTime); }); }); // describe('getting rates by external aggregator', () => { // const encodedRate = toBytes32('GOLD'); // const rateValueEncodedStr = web3.utils.toWei('10.123', 'ether'); // beforeEach(async () => { // const updatedTime = await currentTime(); // await instance.updateRates([encodedRate], [rateValueEncodedStr], updatedTime, { // from: oracle, // }); // const rate = await instance.rateForCurrency(encodedRate); // assert.equal(rate, rateValueEncodedStr); // await instance.setExternalRateAggregator(externalRateAggregator.address, { from: owner }); // }); // it('should get rate from external aggregator', async () => { // await instance.setCurrencyToExternalAggregator(encodedRate, true, { from: owner }); // const rate = await instance.rateForCurrency(encodedRate); // assert.equal(rate.toString(), '0'); // const newRate = toUnit('1010'); // const updatedTime = await currentTime(); // await externalRateAggregator.updateRates([encodedRate], [newRate], updatedTime, { // from: oracle, // }); // const rate2 = await instance.rateForCurrency(encodedRate); // assert.bnEqual(rate2.toString(), toUnit('1010')); // await instance.setCurrencyToExternalAggregator(encodedRate, false, { from: owner }); // const rate3 = await instance.rateForCurrency(encodedRate); // assert.bnEqual(rate3.toString(), rateValueEncodedStr); // }); // }); describe('rateStalePeriod', () => { it('rateStalePeriod default is set correctly', async () => { assert.bnEqual(await instance.rateStalePeriod(), RATE_STALE_PERIOD); }); describe('when rate stale is changed in the system settings', () => { const newRateStalePeriod = '3601'; beforeEach(async () => { await systemSettings.setRateStalePeriod(newRateStalePeriod, { from: owner }); }); it('then rateStalePeriod is correctly updated', async () => { assert.bnEqual(await instance.rateStalePeriod(), newRateStalePeriod); }); }); }); describe('rateIsStale()', () => { it('should never allow pUSD to go stale via rateIsStale', async () => { await fastForward(await instance.rateStalePeriod()); const rateIsStale = await instance.rateIsStale(pUSD); assert.equal(rateIsStale, false); }); it('check if a single rate is stale', async () => { // Set up rates for test await systemSettings.setRateStalePeriod(30, { from: owner }); const updatedTime = await currentTime(); await instance.updateRates( [toBytes32('ABC')], [web3.utils.toWei('2', 'ether')], updatedTime, { from: oracle, } ); await fastForward(31); const rateIsStale = await instance.rateIsStale(toBytes32('ABC')); assert.equal(rateIsStale, true); }); it('check if a single rate is not stale', async () => { // Set up rates for test await systemSettings.setRateStalePeriod(30, { from: owner }); const updatedTime = await currentTime(); await instance.updateRates( [toBytes32('ABC')], [web3.utils.toWei('2', 'ether')], updatedTime, { from: oracle, } ); await fastForward(28); const rateIsStale = await instance.rateIsStale(toBytes32('ABC')); assert.equal(rateIsStale, false); }); it('ensure rate is considered stale if not set', async () => { // Set up rates for test await systemSettings.setRateStalePeriod(30, { from: owner }); const encodedRateKey = toBytes32('GOLD'); const currentRate = await instance.rateForCurrency(encodedRateKey); if (currentRate > 0) { await instance.deleteRate(encodedRateKey, { from: oracle }); } const rateIsStale = await instance.rateIsStale(encodedRateKey); assert.equal(rateIsStale, true); }); it('make sure anyone can check if rate is stale', async () => { const rateKey = toBytes32('ABC'); await instance.rateIsStale(rateKey, { from: oracle }); await instance.rateIsStale(rateKey, { from: owner }); await instance.rateIsStale(rateKey, { from: deployerAccount }); await instance.rateIsStale(rateKey, { from: accountOne }); await instance.rateIsStale(rateKey, { from: accountTwo }); }); }); describe('anyRateIsInvalid()', () => { describe('stale scenarios', () => { it('should never allow pUSD to go stale via anyRateIsInvalid', async () => { const keysArray = [PERI, toBytes32('GOLD')]; await instance.updateRates( keysArray, [web3.utils.toWei('0.1', 'ether'), web3.utils.toWei('0.2', 'ether')], await currentTime(), { from: oracle } ); assert.equal(await instance.anyRateIsInvalid(keysArray), false); await fastForward(await instance.rateStalePeriod()); await instance.updateRates( [PERI, toBytes32('GOLD')], [web3.utils.toWei('0.1', 'ether'), web3.utils.toWei('0.2', 'ether')], await currentTime(), { from: oracle } ); // Even though pUSD hasn't been updated since the stale rate period has expired, // we expect that pUSD remains "not stale" assert.equal(await instance.anyRateIsInvalid(keysArray), false); }); it('should be able to confirm no rates are stale from a subset', async () => { // Set up rates for test await systemSettings.setRateStalePeriod(25, { from: owner }); const encodedRateKeys1 = [ toBytes32('ABC'), toBytes32('DEF'), toBytes32('GHI'), toBytes32('LMN'), ]; const encodedRateKeys2 = [ toBytes32('OPQ'), toBytes32('RST'), toBytes32('UVW'), toBytes32('XYZ'), ]; const encodedRateKeys3 = [toBytes32('123'), toBytes32('456'), toBytes32('789')]; const encodedRateValues1 = [ web3.utils.toWei('1', 'ether'), web3.utils.toWei('2', 'ether'), web3.utils.toWei('3', 'ether'), web3.utils.toWei('4', 'ether'), ]; const encodedRateValues2 = [ web3.utils.toWei('5', 'ether'), web3.utils.toWei('6', 'ether'), web3.utils.toWei('7', 'ether'), web3.utils.toWei('8', 'ether'), ]; const encodedRateValues3 = [ web3.utils.toWei('9', 'ether'), web3.utils.toWei('10', 'ether'), web3.utils.toWei('11', 'ether'), ]; const updatedTime1 = await currentTime(); await instance.updateRates(encodedRateKeys1, encodedRateValues1, updatedTime1, { from: oracle, }); await fastForward(5); const updatedTime2 = await currentTime(); await instance.updateRates(encodedRateKeys2, encodedRateValues2, updatedTime2, { from: oracle, }); await fastForward(5); const updatedTime3 = await currentTime(); await instance.updateRates(encodedRateKeys3, encodedRateValues3, updatedTime3, { from: oracle, }); await fastForward(12); const rateIsInvalid = await instance.anyRateIsInvalid([ ...encodedRateKeys2, ...encodedRateKeys3, ]); assert.equal(rateIsInvalid, false); }); it('should be able to confirm a single rate is stale from a set of rates', async () => { // Set up rates for test await systemSettings.setRateStalePeriod(40, { from: owner }); const encodedRateKeys1 = [ toBytes32('ABC'), toBytes32('DEF'), toBytes32('GHI'), toBytes32('LMN'), ]; const encodedRateKeys2 = [toBytes32('OPQ')]; const encodedRateKeys3 = [toBytes32('RST'), toBytes32('UVW'), toBytes32('XYZ')]; const encodedRateValues1 = [ web3.utils.toWei('1', 'ether'), web3.utils.toWei('2', 'ether'), web3.utils.toWei('3', 'ether'), web3.utils.toWei('4', 'ether'), ]; const encodedRateValues2 = [web3.utils.toWei('5', 'ether')]; const encodedRateValues3 = [ web3.utils.toWei('6', 'ether'), web3.utils.toWei('7', 'ether'), web3.utils.toWei('8', 'ether'), ]; const updatedTime2 = await currentTime(); await instance.updateRates(encodedRateKeys2, encodedRateValues2, updatedTime2, { from: oracle, }); await fastForward(20); const updatedTime1 = await currentTime(); await instance.updateRates(encodedRateKeys1, encodedRateValues1, updatedTime1, { from: oracle, }); await fastForward(15); const updatedTime3 = await currentTime(); await instance.updateRates(encodedRateKeys3, encodedRateValues3, updatedTime3, { from: oracle, }); await fastForward(6); const rateIsInvalid = await instance.anyRateIsInvalid([ ...encodedRateKeys2, ...encodedRateKeys3, ]); assert.equal(rateIsInvalid, true); }); it('should be able to confirm a single rate (from a set of 1) is stale', async () => { // Set up rates for test await systemSettings.setRateStalePeriod(40, { from: owner }); const updatedTime = await currentTime(); await instance.updateRates( [toBytes32('ABC')], [web3.utils.toWei('2', 'ether')], updatedTime, { from: oracle, } ); await fastForward(41); const rateIsInvalid = await instance.anyRateIsInvalid([toBytes32('ABC')]); assert.equal(rateIsInvalid, true); }); it('make sure anyone can check if any rates are stale', async () => { const rateKey = toBytes32('ABC'); await instance.anyRateIsInvalid([rateKey], { from: oracle }); await instance.anyRateIsInvalid([rateKey], { from: owner }); await instance.anyRateIsInvalid([rateKey], { from: deployerAccount }); await instance.anyRateIsInvalid([rateKey], { from: accountOne }); await instance.anyRateIsInvalid([rateKey], { from: accountTwo }); }); it('ensure rates are considered stale if not set', async () => { // Set up rates for test await systemSettings.setRateStalePeriod(40, { from: owner }); const encodedRateKeys1 = [ toBytes32('ABC'), toBytes32('DEF'), toBytes32('GHI'), toBytes32('LMN'), ]; const encodedRateValues1 = [ web3.utils.toWei('1', 'ether'), web3.utils.toWei('2', 'ether'), web3.utils.toWei('3', 'ether'), web3.utils.toWei('4', 'ether'), ]; const updatedTime1 = await currentTime(); await instance.updateRates(encodedRateKeys1, encodedRateValues1, updatedTime1, { from: oracle, }); const rateIsInvalid = await instance.anyRateIsInvalid([ ...encodedRateKeys1, toBytes32('RST'), ]); assert.equal(rateIsInvalid, true); }); }); }); describe('lastRateUpdateTimesForCurrencies()', () => { it('should return correct last rate update times for specific currencies', async () => { const abc = toBytes32('lABC'); const timeSent = await currentTime(); const listOfKeys = [abc, toBytes32('lDEF'), toBytes32('lGHI')]; await instance.updateRates( listOfKeys.slice(0, 2), [web3.utils.toWei('1.3', 'ether'), web3.utils.toWei('2.4', 'ether')], timeSent, { from: oracle } ); await fastForward(100); const newTimeSent = await currentTime(); await instance.updateRates( listOfKeys.slice(2), [web3.utils.toWei('3.5', 'ether')], newTimeSent, { from: oracle } ); const lastUpdateTimes = await instance.lastRateUpdateTimesForCurrencies(listOfKeys); assert.notEqual(timeSent, newTimeSent); assert.equal(lastUpdateTimes.length, listOfKeys.length); assert.equal(lastUpdateTimes[0], timeSent); assert.equal(lastUpdateTimes[1], timeSent); assert.equal(lastUpdateTimes[2], newTimeSent); }); it('should return correct last rate update time for a specific currency', async () => { const abc = toBytes32('lABC'); const def = toBytes32('lDEF'); const ghi = toBytes32('lGHI'); const timeSent = await currentTime(); await instance.updateRates( [abc, def], [web3.utils.toWei('1.3', 'ether'), web3.utils.toWei('2.4', 'ether')], timeSent, { from: oracle } ); await fastForward(10000); const timeSent2 = await currentTime(); await instance.updateRates([ghi], [web3.utils.toWei('2.4', 'ether')], timeSent2, { from: oracle, }); const [firstTS, secondTS] = await Promise.all([ instance.lastRateUpdateTimes(abc), instance.lastRateUpdateTimes(ghi), ]); assert.equal(firstTS, timeSent); assert.equal(secondTS, timeSent2); }); }); describe('effectiveValue() and effectiveValueAndRates()', () => { let timestamp; beforeEach(async () => { timestamp = await currentTime(); }); describe('when a price is sent to the oracle', () => { beforeEach(async () => { // Send a price update to guarantee we're not depending on values from outside this test. await instance.updateRates( ['pAUD', 'pEUR', 'PERI'].map(toBytes32), ['0.5', '1.25', '0.1'].map(toUnit), timestamp, { from: oracle } ); }); it('should correctly calculate an exchange rate in effectiveValue()', async () => { // 1 pUSD should be worth 2 pAUD. assert.bnEqual(await instance.effectiveValue(pUSD, toUnit('1'), pAUD), toUnit('2')); // 10 PERI should be worth 1 pUSD. assert.bnEqual(await instance.effectiveValue(PERI, toUnit('10'), pUSD), toUnit('1')); // 2 pEUR should be worth 2.50 pUSD assert.bnEqual(await instance.effectiveValue(pEUR, toUnit('2'), pUSD), toUnit('2.5')); }); it('should calculate updated rates in effectiveValue()', async () => { // Add stale period to the time to ensure we go stale. await fastForward((await instance.rateStalePeriod()) + 1); timestamp = await currentTime(); // Update all rates except pUSD. await instance.updateRates([pEUR, PERI], ['1.25', '0.1'].map(toUnit), timestamp, { from: oracle, }); const amountOfPeriFinances = toUnit('10'); const amountOfEur = toUnit('0.8'); // Should now be able to convert from PERI to pEUR since they are both not stale. assert.bnEqual( await instance.effectiveValue(PERI, amountOfPeriFinances, pEUR), amountOfEur ); }); it('should return 0 when relying on a non-existant dest exchange rate in effectiveValue()', async () => { assert.equal(await instance.effectiveValue(PERI, toUnit('10'), toBytes32('XYZ')), '0'); }); it('should return 0 when relying on a non-existing src rate in effectiveValue', async () => { assert.equal(await instance.effectiveValue(toBytes32('XYZ'), toUnit('10'), PERI), '0'); }); it('effectiveValueAndRates() should return rates as well with pUSD on one side', async () => { const { value, sourceRate, destinationRate } = await instance.effectiveValueAndRates( pUSD, toUnit('1'), pAUD ); assert.bnEqual(value, toUnit('2')); assert.bnEqual(sourceRate, toUnit('1')); assert.bnEqual(destinationRate, toUnit('0.5')); }); it('effectiveValueAndRates() should return rates as well with pUSD on the other side', async () => { const { value, sourceRate, destinationRate } = await instance.effectiveValueAndRates( pAUD, toUnit('1'), pUSD ); assert.bnEqual(value, toUnit('0.5')); assert.bnEqual(sourceRate, toUnit('0.5')); assert.bnEqual(destinationRate, toUnit('1')); }); it('effectiveValueAndRates() should return rates as well with two live rates', async () => { const { value, sourceRate, destinationRate } = await instance.effectiveValueAndRates( pAUD, toUnit('1'), pEUR ); assert.bnEqual(value, toUnit('0.4')); // 0.5/1.25 = 0.4 assert.bnEqual(sourceRate, toUnit('0.5')); assert.bnEqual(destinationRate, toUnit('1.25')); }); }); }); describe('inverted prices', () => { const inverseRates = ['iBTC', 'iETH', 'pEUR']; const [iBTC, iETH, pEUR] = inverseRates.map(toBytes32); it('rateIsFrozen for a regular pynth returns false', async () => { assert.equal(false, await instance.rateIsFrozen(pEUR)); }); it('and list of invertedKeys is empty', async () => { await assert.invalidOpcode(instance.invertedKeys(0)); }); describe('when attempting to add inverse pynths', () => { it('ensure only the owner can invoke', async () => { await onlyGivenAddressCanInvoke({ fnc: instance.setInversePricing, args: [iBTC, toUnit('1'), toUnit('1.5'), toUnit('0.5'), false, false], accounts, address: owner, reason: 'Only the contract owner may perform this action', }); }); it('ensure entryPoint be greater than 0', async () => { await assert.revert( instance.setInversePricing(iBTC, toUnit('0'), toUnit('150'), toUnit('10'), false, false, { from: owner, }), 'upperLimit must be less than double entryPoint' ); }); it('ensure lowerLimit be greater than 0', async () => { await assert.revert( instance.setInversePricing( iBTC, toUnit('100'), toUnit('150'), toUnit('0'), false, false, { from: owner, } ), 'lowerLimit must be above 0' ); }); it('ensure upperLimit be greater than the entryPoint', async () => { await assert.revert( instance.setInversePricing( iBTC, toUnit('100'), toUnit('100'), toUnit('10'), false, false, { from: owner, } ), 'upperLimit must be above the entryPoint' ); }); it('ensure upperLimit be less than double the entryPoint', async () => { await assert.revert( instance.setInversePricing( iBTC, toUnit('100'), toUnit('200'), toUnit('10'), false, false, { from: owner, } ), 'upperLimit must be less than double entryPoint' ); }); it('ensure lowerLimit be less than the entryPoint', async () => { await assert.revert( instance.setInversePricing( iBTC, toUnit('100'), toUnit('150'), toUnit('100'), false, false, { from: owner, } ), 'lowerLimit must be below the entryPoint' ); }); it('ensure both freeze at upper and freeze at lower cannot both be true', async () => { await assert.revert( instance.setInversePricing(iBTC, toUnit('100'), toUnit('150'), toUnit('50'), true, true, { from: owner, }), 'Cannot freeze at both limits' ); }); }); describe('freezeRate()', () => { it('reverts when the currency key is not an inverse', async () => { await assert.revert(instance.freezeRate(pEUR), 'Cannot freeze non-inverse rate'); }); describe('when an inverse is added for iBTC already frozen at the upper limit', () => { beforeEach(async () => { await instance.setInversePricing( iBTC, toUnit(4000), toUnit(6500), toUnit(2300), true, false, { from: owner, } ); }); it('freezeRate reverts as its already frozen', async () => { await assert.revert(instance.freezeRate(iBTC), 'The rate is already frozen'); }); }); describe('when an inverse is added for iBTC already frozen at the lower limit', () => { beforeEach(async () => { await instance.setInversePricing( iBTC, toUnit(4000), toUnit(6500), toUnit(2300), false, true, { from: owner, } ); }); it('freezeRate reverts as its already frozen', async () => { await assert.revert(instance.freezeRate(iBTC), 'The rate is already frozen'); }); }); describe('when an inverse is added for iBTC yet not frozen', () => { beforeEach(async () => { await instance.setInversePricing( iBTC, toUnit(4000), toUnit(6500), toUnit(2300), false, false, { from: owner, } ); }); it('edge-case: freezeRate reverts as even though there is no price, it is not on bounds', async () => { await assert.revert(instance.freezeRate(iBTC), 'Rate within bounds'); }); it('roundFrozen() returns 0 for iBTC', async () => { assert.equal(await instance.roundFrozen(iBTC), '0'); }); describe('when an in-bounds rate arrives for iBTC', () => { beforeEach(async () => { await instance.updateRates([iBTC], [toUnit('5000')], await currentTime(), { from: oracle, }); }); it('freezeRate reverts as the price is within bounds', async () => { await assert.revert(instance.freezeRate(iBTC), 'Rate within bounds'); }); it('roundFrozen() returns 0 for iBTC', async () => { assert.equal(await instance.roundFrozen(iBTC), '0'); }); }); describe('when an upper out-of-bounds rate arrives for iBTC', () => { let roundId; beforeEach(async () => { await instance.updateRates([iBTC], [toUnit('6000')], await currentTime(), { from: oracle, }); roundId = await instance.getCurrentRoundId(iBTC); }); describe('when freezeRate is invoked', () => { let txn; beforeEach(async () => { txn = await instance.freezeRate(iBTC, { from: accounts[2] }); }); it('and emits an InversePriceFrozen at the lower limit', async () => { assert.eventEqual(txn, 'InversePriceFrozen', { currencyKey: iBTC, rate: toUnit(2300), roundId, initiator: accounts[2], }); }); it('and the inverse pricing shows the frozen flag at lower', async () => { const { frozenAtUpperLimit, frozenAtLowerLimit } = await instance.inversePricing( iBTC ); assert.notOk(frozenAtUpperLimit); assert.ok(frozenAtLowerLimit); }); it('and roundFrozen() returns the current round ID for iBTC', async () => { assert.bnEqual(await instance.roundFrozen(iBTC), roundId); }); }); }); describe('when a lower out-of-bounds rate arrives for iBTC', () => { let roundId; beforeEach(async () => { await instance.updateRates([iBTC], [toUnit('1000')], await currentTime(), { from: oracle, }); roundId = await instance.getCurrentRoundId(iBTC); }); describe('when freezeRate is invoked', () => { let txn; beforeEach(async () => { txn = await instance.freezeRate(iBTC, { from: accounts[2] }); }); it('and emits an InversePriceFrozen at the upper limit', async () => { assert.eventEqual(txn, 'InversePriceFrozen', { currencyKey: iBTC, rate: toUnit(6500), roundId, initiator: accounts[2], }); }); it('and the inverse pricing shows the frozen flag at upper', async () => { const { frozenAtUpperLimit, frozenAtLowerLimit } = await instance.inversePricing( iBTC ); assert.ok(frozenAtUpperLimit); assert.notOk(frozenAtLowerLimit); }); it('and roundFrozen() returns the current round ID for iBTC', async () => { assert.bnEqual(await instance.roundFrozen(iBTC), roundId); }); }); }); }); }); describe('when two inverted pynths are added', () => { // helper function to check rates are correct const assertRatesAreCorrect = async ({ currencyKeys, expectedRates, txn, outOfBounds = [], }) => { // ensure all rates returned from contract are as expected const rates = await instance.ratesForCurrencies(currencyKeys); expectedRates.forEach((rate, i) => assert.bnEqual(rates[i], rate)); const ratesUpdatedEvent = [ 'RatesUpdated', { currencyKeys, }, ]; assert.eventEqual(txn, ...ratesUpdatedEvent); if (outOfBounds.length) { for (const currencyKey of outOfBounds) { assert.ok(await instance.canFreezeRate(currencyKey)); } // now for all other currency keys, make sure canFreeze is false const keysInBounds = currencyKeys.filter(ccy => outOfBounds.indexOf(ccy) < 0); for (const currencyKey of keysInBounds) { assert.notOk(await instance.canFreezeRate(currencyKey)); } } }; const setTxns = []; beforeEach(async () => { setTxns.push( await instance.setInversePricing( iBTC, toUnit(4000), toUnit(6500), toUnit(2300), false, false, { from: owner, } ) ); setTxns.push( await instance.setInversePricing( iETH, toUnit(200), toUnit(350), toUnit(75), false, false, { from: owner, } ) ); }); it('both emit InversePriceConfigured events', async () => { assert.eventEqual(setTxns[0], 'InversePriceConfigured', { currencyKey: iBTC, entryPoint: toUnit(4000), upperLimit: toUnit(6500), lowerLimit: toUnit(2300), }); assert.eventEqual(setTxns[1], 'InversePriceConfigured', { currencyKey: iETH, entryPoint: toUnit(200), upperLimit: toUnit(350), lowerLimit: toUnit(75), }); }); it('and the list of invertedKeys lists them both', async () => { assert.equal('iBTC', bytesToString(await instance.invertedKeys(0))); assert.equal('iETH', bytesToString(await instance.invertedKeys(1))); await assert.invalidOpcode(instance.invertedKeys(2)); }); it('rateIsFrozen must be false for both', async () => { assert.equal(false, await instance.rateIsFrozen(iBTC)); assert.equal(false, await instance.rateIsFrozen(iETH)); }); it('and canFreeze is false for the inverses as no rate yet given', async () => { assert.notOk(await instance.canFreezeRate(iBTC)); assert.notOk(await instance.canFreezeRate(iETH)); }); it('and canFreeze is false for other pynths', async () => { assert.notOk(await instance.canFreezeRate(pEUR)); assert.notOk(await instance.canFreezeRate(toBytes32('ABC'))); }); describe('when another pynth is added as frozen directly', () => { let txn; describe('with it set to freezeAtUpperLimit', () => { beforeEach(async () => { txn = await instance.setInversePricing( iBTC, toUnit(4000), toUnit(6500), toUnit(2300), true, false, { from: owner, } ); }); it('then the pynth is frozen', async () => { assert.equal(true, await instance.rateIsFrozen(iBTC)); assert.equal(false, await instance.rateIsFrozen(iETH)); }); it('and it emits a frozen event', () => { assert.eventEqual(txn.logs[0], 'InversePriceFrozen', { currencyKey: iBTC, rate: toUnit(6500), roundId: '0', initiator: owner, }); }); it('yet the rate is 0 because there is no initial rate', async () => { assert.equal(await instance.ratesForCurrencies([iBTC]), '0'); }); it('and the inverse pricing struct is configured', async () => { const { entryPoint, upperLimit, lowerLimit, frozenAtUpperLimit, frozenAtLowerLimit, } = await instance.inversePricing(iBTC); assert.bnEqual(entryPoint, toUnit(4000)); assert.bnEqual(upperLimit, toUnit(6500)); assert.bnEqual(lowerLimit, toUnit(2300)); assert.equal(frozenAtUpperLimit, true); assert.equal(frozenAtLowerLimit, false); }); it('and canFreeze is false for the currency key is now frozen', async () => { assert.notOk(await instance.canFreezeRate(iBTC)); }); describe('when updateRates is called with an in-bounds update', () => { let txn; beforeEach(async () => { const rates = [toUnit('4500')]; const timeSent = await currentTime(); txn = await instance.updateRates([iBTC], rates, timeSent, { from: oracle, }); }); it('the inverted rate remains frozen at upper limit', async () => { await assertRatesAreCorrect({ txn, currencyKeys: [iBTC], expectedRates: [toUnit('6500')], }); assert.equal(true, await instance.rateIsFrozen(iBTC)); }); it('and canFreeze is still false for the currency key is now frozen', async () => { assert.notOk(await instance.canFreezeRate(iBTC)); }); }); }); describe('with it set to freezeAtLowerLimit', () => { beforeEach(async () => { txn = await instance.setInversePricing( iBTC, toUnit(4000), toUnit(6500), toUnit(2300), false, true, { from: owner, } ); }); it('then the pynth is frozen', async () => { assert.equal(true, await instance.rateIsFrozen(iBTC)); assert.equal(false, await instance.rateIsFrozen(iETH)); }); it('yet the rate is 0 because there is no initial rate', async () => { assert.equal(await instance.ratesForCurrencies([iBTC]), '0'); }); it('and it emits a frozen event', () => { assert.eventEqual(txn.logs[0], 'InversePriceFrozen', { currencyKey: iBTC, rate: toUnit(2300), roundId: '0', initiator: owner, }); }); it('and the inverse pricing struct is configured', async () => { const { entryPoint, upperLimit, lowerLimit, frozenAtUpperLimit, frozenAtLowerLimit, } = await instance.inversePricing(iBTC); assert.bnEqual(entryPoint, toUnit(4000)); assert.bnEqual(upperLimit, toUnit(6500)); assert.bnEqual(lowerLimit, toUnit(2300)); assert.equal(frozenAtUpperLimit, false); assert.equal(frozenAtLowerLimit, true); }); it('and canFreeze is false for the currency key is now frozen', async () => { assert.notOk(await instance.canFreezeRate(iBTC)); }); describe('when updateRates is called with an in-bounds update', () => { let txn; beforeEach(async () => { const rates = [toUnit('4500')]; const timeSent = await currentTime(); txn = await instance.updateRates([iBTC], rates, timeSent, { from: oracle, }); }); it('the inverted rate remains frozen at lower limit', async () => { await assertRatesAreCorrect({ txn, currencyKeys: [iBTC], expectedRates: [toUnit('2300')], }); assert.equal(true, await instance.rateIsFrozen(iBTC)); }); it('and canFreeze is false for the currency key is now frozen', async () => { assert.notOk(await instance.canFreezeRate(iBTC)); }); }); }); }); describe('when updateRates is called with an in-bounds update', () => { let txn; beforeEach(async () => { const rates = [4500.553, 225, 1.12].map(toUnit); const timeSent = await currentTime(); txn = await instance.updateRates([iBTC, iETH, pEUR], rates, timeSent, { from: oracle, }); }); it('regular and inverted rates should be updated correctly', async () => { await assertRatesAreCorrect({ txn, currencyKeys: [iBTC, iETH, pEUR], expectedRates: [3499.447, 175, 1.12].map(toUnit), }); }); it('rateIsFrozen must be false for both', async () => { assert.equal(false, await instance.rateIsFrozen(iBTC)); assert.equal(false, await instance.rateIsFrozen(iETH)); }); it('and canFreeze is false for the currency keys as the rate is valid', async () => { assert.notOk(await instance.canFreezeRate(iBTC)); assert.notOk(await instance.canFreezeRate(iETH)); }); describe('when setInversePricing is called to freeze a pynth with a rate', () => { beforeEach(async () => { await instance.setInversePricing( iBTC, toUnit(4000), toUnit(6500), toUnit(2300), true, false, { from: owner, } ); }); it('then the pynth is frozen', async () => { assert.equal(true, await instance.rateIsFrozen(iBTC)); assert.equal(false, await instance.rateIsFrozen(iETH)); }); it('and the rate for the pynth is the upperLimit - regardless of its old value', async () => { const actual = await instance.ratesForCurrencies([iBTC]); assert.bnEqual(actual, toUnit(6500)); }); it('and canFreeze is false for the currency keys as the rate is frozen', async () => { assert.notOk(await instance.canFreezeRate(iBTC)); }); }); }); describe('when updateRates is called with a lower out-of-bounds update', () => { let txn; beforeEach(async () => { const rates = [8050, 400, 1.12].map(toUnit); const timeSent = await currentTime(); txn = await instance.updateRates([iBTC, iETH, pEUR], rates, timeSent, { from: oracle, }); }); it('inverted rates return at the lower bounds', async () => { await assertRatesAreCorrect({ txn, currencyKeys: [iBTC, iETH, pEUR], expectedRates: [2300, 75, 1.12].map(toUnit), outOfBounds: [iBTC, iETH], }); }); it('and canFreeze is true for the currency keys as the rate is invalid', async () => { assert.ok(await instance.canFreezeRate(iBTC)); assert.ok(await instance.canFreezeRate(iETH)); }); describe('when freezeRate is invoked for both', () => { beforeEach(async () => { await instance.freezeRate(iBTC, { from: accounts[2] }); await instance.freezeRate(iETH, { from: accounts[3] }); }); describe('when another updateRates is called with an in bounds update', () => { beforeEach(async () => { const rates = [3500, 300, 2.12].map(toUnit); const timeSent = await currentTime(); txn = await instance.updateRates([iBTC, iETH, pEUR], rates, timeSent, { from: oracle, }); }); it('inverted rates must remain frozen at the lower bounds', async () => { await assertRatesAreCorrect({ txn, currencyKeys: [iBTC, iETH, pEUR], expectedRates: [2300, 75, 2.12].map(toUnit), }); }); }); describe('when another updateRates is called with an out of bounds update the other way', () => { beforeEach(async () => { const rates = [1000, 50, 2.3].map(toUnit); const timeSent = await currentTime(); txn = await instance.updateRates([iBTC, iETH, pEUR], rates, timeSent, { from: oracle, }); }); it('inverted rates must remain frozen at the lower bounds', async () => { await assertRatesAreCorrect({ txn, currencyKeys: [iBTC, iETH, pEUR], expectedRates: [2300, 75, 2.3].map(toUnit), }); }); }); describe('when setInversePricing is called again for one of the frozen pynths', () => { let setTxn; beforeEach(async () => { setTxn = await instance.setInversePricing( iBTC, toUnit(5000), toUnit(8900), toUnit(3000), false, false, { from: owner, } ); }); it('it emits a InversePriceConfigured event', async () => { const currencyKey = 'iBTC'; assert.eventEqual(setTxn, 'InversePriceConfigured', { currencyKey: toBytes32(currencyKey), entryPoint: toUnit(5000), upperLimit: toUnit(8900), lowerLimit: toUnit(3000), }); }); it('and the list of invertedKeys still lists them both', async () => { assert.equal('iBTC', bytesToString(await instance.invertedKeys(0))); assert.equal('iETH', bytesToString(await instance.invertedKeys(1))); await assert.invalidOpcode(instance.invertedKeys(2)); }); describe('when a price is received within bounds', () => { let txn; beforeEach(async () => { const rates = [1250, 201, 1.12].map(toUnit); const timeSent = await currentTime(); txn = await instance.updateRates([iBTC, iETH, pEUR], rates, timeSent, { from: oracle, }); }); it('then the inverted pynth updates as it is no longer frozen and respects new entryPoint and limits', async () => { await assertRatesAreCorrect({ txn, currencyKeys: [iBTC, iETH, pEUR], expectedRates: [8750, 75, 1.12].map(toUnit), }); }); it('and canFreeze is false for the unfrozen and the already frozen one', async () => { assert.notOk(await instance.canFreezeRate(iBTC)); assert.notOk(await instance.canFreezeRate(iETH)); }); describe('when a price is received out of bounds', () => { let txn; beforeEach(async () => { const rates = [1000, 201, 1.12].map(toUnit); const timeSent = await currentTime(); txn = await instance.updateRates([iBTC, iETH, pEUR], rates, timeSent, { from: oracle, }); }); it('then the inverted shows at new upper limit', async () => { await assertRatesAreCorrect({ txn, currencyKeys: [iBTC, iETH, pEUR], expectedRates: [8900, 75, 1.12].map(toUnit), }); }); it('and canFreeze is true for the currency key as the rate is invalid', async () => { assert.ok(await instance.canFreezeRate(iBTC)); }); it('but false for the already frozen one', async () => { assert.notOk(await instance.canFreezeRate(iETH)); }); }); }); }); }); }); describe('when updateRates is called with an upper out-of-bounds update', () => { let txn; beforeEach(async () => { const rates = [1200, 45, 1.12].map(toUnit); const timeSent = await currentTime(); txn = await instance.updateRates([iBTC, iETH, pEUR], rates, timeSent, { from: oracle, }); }); it('inverted rates must be set to the upper bounds', async () => { await assertRatesAreCorrect({ txn, currencyKeys: [iBTC, iETH, pEUR], expectedRates: [6500, 350, 1.12].map(toUnit), outOfBounds: [iBTC, iETH], }); }); describe('when freezeRate is invoked', () => { beforeEach(async () => { await instance.freezeRate(iBTC, { from: accounts[2] }); await instance.freezeRate(iETH, { from: accounts[2] }); }); describe('when another updateRates is called with an in bounds update', () => { beforeEach(async () => { const rates = [3500, 300, 2.12].map(toUnit); const timeSent = await currentTime(); txn = await instance.updateRates([iBTC, iETH, pEUR], rates, timeSent, { from: oracle, }); }); it('inverted rates must remain frozen at the upper bounds', async () => { await assertRatesAreCorrect({ txn, currencyKeys: [iBTC, iETH, pEUR], expectedRates: [6500, 350, 2.12].map(toUnit), }); }); }); }); describe('when iBTC is attempted removal by a non owner', () => { it('ensure only the owner can invoke', async () => { await onlyGivenAddressCanInvoke({ fnc: instance.removeInversePricing, args: [iBTC], accounts, address: owner, reason: 'Only the contract owner may perform this action', }); }); }); describe('when a regular (non-inverse) pynth is removed by the owner', () => { it('then it reverts', async () => { await assert.revert( instance.removeInversePricing(pEUR, { from: owner, }), 'No inverted price exists' ); }); }); describe('when iBTC is removed by the owner', () => { let removeTxn; beforeEach(async () => { removeTxn = await instance.removeInversePricing(iBTC, { from: owner, }); }); it('it emits a InversePriceConfigured event', async () => { assert.eventEqual(removeTxn, 'InversePriceConfigured', { currencyKey: iBTC, entryPoint: 0, upperLimit: 0, lowerLimit: 0, }); }); it('and the list of invertedKeys contains only iETH', async () => { assert.equal('iETH', bytesToString(await instance.invertedKeys(0))); await assert.invalidOpcode(instance.invertedKeys(1)); }); it('and inversePricing for iBTC returns an empty struct', async () => { const { entryPoint, upperLimit, lowerLimit, frozenAtUpperLimit, frozenAtLowerLimit, } = await instance.inversePricing(iBTC); assert.equal(entryPoint, '0'); assert.equal(upperLimit, '0'); assert.equal(lowerLimit, '0'); assert.equal(frozenAtUpperLimit, false); assert.equal(frozenAtLowerLimit, false); }); }); }); }); }); describe('when the flags interface is set', () => { beforeEach(async () => { // replace the FlagsInterface mock with a fully fledged mock that can // return arrays of information await systemSettings.setAggregatorWarningFlags(mockFlagsInterface.address, { from: owner }); }); describe('aggregatorWarningFlags', () => { it('is set correctly', async () => { assert.equal(await instance.aggregatorWarningFlags(), mockFlagsInterface.address); }); }); }); describe('roundIds for historical rates', () => { it('getCurrentRoundId() by default is 0 for all pynths except pUSD which is 1', async () => { // Note: rates that were set in the truffle migration will be at 1, so we need to check // other pynths assert.equal(await instance.getCurrentRoundId(pUSD), '1'); }); it('ratesAndUpdatedTimeForCurrencyLastNRounds() shows first entry for pUSD', async () => { const timeOfpUSDRateSetOnInit = await instance.lastRateUpdateTimes(pUSD); assert.deepEqual(await instance.ratesAndUpdatedTimeForCurrencyLastNRounds(pUSD, '3'), [ [toUnit('1'), '0', '0'], [timeOfpUSDRateSetOnInit, '0', '0'], ]); }); it('ratesAndUpdatedTimeForCurrencyLastNRounds() returns 0s for other currency keys', async () => { const fiveZeros = new Array(5).fill('0'); assert.deepEqual(await instance.ratesAndUpdatedTimeForCurrencyLastNRounds(pAUD, '5'), [ fiveZeros, fiveZeros, ]); }); }); });
(function () { 'use strict'; describe('Aquisitions List Controller Tests', function () { // Initialize global variables var AquisitionsListController, $scope, $httpBackend, $state, Authentication, AquisitionsService, mockAquisition; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function () { jasmine.addMatchers({ toEqualData: function (util, customEqualityTesters) { return { compare: function (actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _AquisitionsService_) { // Set a new global scope $scope = $rootScope.$new(); // Point global variables to injected services $httpBackend = _$httpBackend_; $state = _$state_; Authentication = _Authentication_; AquisitionsService = _AquisitionsService_; // create mock article mockAquisition = new AquisitionsService({ _id: '525a8422f6d0f87f0e407a33', name: 'Aquisition Name' }); // Mock logged in user Authentication.user = { roles: ['user'] }; // Initialize the Aquisitions List controller. AquisitionsListController = $controller('AquisitionsListController as vm', { $scope: $scope }); // Spy on state go spyOn($state, 'go'); })); describe('Instantiate', function () { var mockAquisitionList; beforeEach(function () { mockAquisitionList = [mockAquisition, mockAquisition]; }); it('should send a GET request and return all Aquisitions', inject(function (AquisitionsService) { // Set POST response $httpBackend.expectGET('api/aquisitions').respond(mockAquisitionList); $httpBackend.flush(); // Test form inputs are reset expect($scope.vm.aquisitions.length).toEqual(2); expect($scope.vm.aquisitions[0]).toEqual(mockAquisition); expect($scope.vm.aquisitions[1]).toEqual(mockAquisition); })); }); }); }());
module.exports = { globals: { 'ts-jest': { diagnostics: false } }, preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel', moduleFileExtensions: [ 'js', 'json', 'vue', 'ts', ], transform: { '^.+\\.vue$': 'vue-jest', }, moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1', }, snapshotSerializers: [ 'jest-serializer-vue', ], collectCoverageFrom: [ 'src/**/*.{js,ts,vue}', '!**/node_modules/**', '!src/assets/*', '!src/main.ts' ], }
/** * @param {number[]} candies * @param {number} extraCandies * @return {boolean[]} */ var kidsWithCandies = function (candies, extraCandies) { let max = 0; candies.forEach(c => { max = Math.max(max, c) }); return candies.map(c => c + extraCandies >= max); }; // TEST: console.log(kidsWithCandies([2, 3, 5, 1, 3], 3)) console.log(kidsWithCandies([4, 2, 1, 1, 2], 1)) console.log(kidsWithCandies([12, 1, 12], 10))
import React, {forwardRef} from 'react'; import { Link as RouterLink } from "react-router-dom"; export default forwardRef((props, ref) => <RouterLink innerRef={ref} {...props} />);
export default function canonize(url) { // const re = new RegExp('@?(https?:)?(\/\/)?((vk|twitter|telegram)[^\/]*\/)?([a-zA-Z0-9]*)', 'i'); if (url) { // const re = new RegExp('@?(https?:)?(\/\/)?((@?a-zA-Z0-9.)[^\/]*\/)?([a-zA-Z0-9.]*)', 'i'); const re = new RegExp('@?(https?:)?(\/\/)?(([@?a-zA-Z0-9._]*)[^\/]*\/)?([@?a-zA-Z0-9._a]*)', 'i'); const username = url.match(re)[5]; return username[0] != '@' ? '@' + username : username; } return 'Username undefined' };
import React from "react"; import PropTypes from "prop-types"; import logoImage from "../../images/logo.png"; import "./hero.css"; const Hero = ({ siteTitle }) => ( <div style={{ display: "flex", alignItems: "center", flexDirection: "column", padding: "2rem 1rem", }} > <div className="Hero"> <img src={logoImage} alt="Insulae Property logo, an Ancient Roman insulae building next to the company name." /> </div> </div> ); Hero.propTypes = { siteTitle: PropTypes.string, }; Hero.defaultProps = { siteTitle: ``, }; export default Hero;
/** * `core/site` data store: reset connection tests. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import { createTestRegistry, subscribeUntil, unsubscribeFromAll, } from 'tests/js/utils'; import { STORE_NAME } from './constants'; describe( 'core/site reset', () => { let registry; beforeEach( () => { registry = createTestRegistry(); } ); afterEach( () => { unsubscribeFromAll( registry ); } ); describe( 'actions', () => { describe( 'fetchReset', () => { it( 'sets isDoingReset ', async () => { const response = true; fetchMock.postOnce( /^\/google-site-kit\/v1\/core\/site\/data\/reset/, { body: JSON.stringify( response ), status: 200 } ); registry.dispatch( STORE_NAME ).fetchReset(); expect( registry.select( STORE_NAME ).isDoingReset() ).toEqual( true ); } ); } ); describe( 'reset', () => { it( 'does not require any params', () => { expect( async () => { const response = true; fetchMock.postOnce( /^\/google-site-kit\/v1\/core\/site\/data\/reset/, { body: JSON.stringify( response ), status: 200 } ); await registry.dispatch( STORE_NAME ).reset(); } ).not.toThrow(); } ); it( 'resets connection ', async () => { const response = true; fetchMock.postOnce( /^\/google-site-kit\/v1\/core\/site\/data\/reset/, { body: JSON.stringify( response ), status: 200 } ); registry .dispatch( STORE_NAME ) .receiveGetConnection( { connected: true, resettable: true }, {} ); await registry.dispatch( STORE_NAME ).reset(); expect( fetchMock ).toHaveFetchedTimes( 1 ); fetchMock.getOnce( /^\/google-site-kit\/v1\/core\/site\/data\/connection/, { body: { connected: false, resettable: false }, status: 200 } ); // After a successful reset, `connection` should be `undefined` again. const connection = await registry.select( STORE_NAME ).getConnection(); expect( connection ).toEqual( undefined ); } ); it( 'does not reset local connection if reset request fails', async () => { // Make sure there is existing data in the store so we can ensure // it isn't reset. registry.dispatch( STORE_NAME ).receiveGetConnection( { connected: true, resettable: true }, {} ); const response = { code: 'internal_server_error', message: 'Internal server error', data: { status: 500 }, }; fetchMock.postOnce( /^\/google-site-kit\/v1\/core\/site\/data\/reset/, { body: JSON.stringify( response ), status: 500 } ); registry.dispatch( STORE_NAME ).reset(); await subscribeUntil( registry, () => registry.select( STORE_NAME ).isDoingReset() === false ); expect( fetchMock ).toHaveFetchedTimes( 1 ); // After a failed reset, `connection` should still exist. const connection = registry.select( STORE_NAME ).getConnection(); expect( connection ).toEqual( { connected: true, resettable: true } ); expect( console ).toHaveErrored(); } ); } ); } ); } );
import "./styles/app.css" import "./styles/auth.css" import "./styles/depiction.css" import React, {useState, useEffect} from "react" import {BrowserRouter as Router, Route} from "react-router-dom" import {Container} from "react-bootstrap" import Header from "./components/header/header.js" import DefaultLandingPage from "./components/body/body.js" import Footer from "./components/footer/footer.js" import Loading from "./components/loading.js" import Depiction from "./components/depiction/depiction.js" import AuthForm from "./components/AuthenticationForm.js" import ProfileScreen from "./screens/profileScreen" const getToken = () => { return localStorage.getItem("token") } const App = (props) => { const [token, setToken] = useState(undefined) const [loggedIn, setLoggedIn] = useState(false) const [userDetails, setUserDetails] = useState(false) const [renderAuthForm, setRenderAuthForm] = useState(false) const [renderDepiction, setRenderDepiction] = useState(false) const [disableUserButton, setDisableUserButton] = useState(false) useEffect(() => { console.log(token) if (token !== undefined) { localStorage.setItem("token", token) setToken(token) setLoggedIn(true) setRenderAuthForm(false) } }) return ( <Router> {renderAuthForm && ( <AuthForm obscureAuthForm={() => setRenderAuthForm(false)} setToken={(token) => setToken(token)} /> )} <Header className={renderAuthForm && "disable"} renderAuthForm={() => setRenderAuthForm(!loggedIn)} renderDepiction={() => { setDisableUserButton(!disableUserButton) setRenderDepiction(!renderDepiction) setTimeout( () => setDisableUserButton(!disableUserButton), this.state.renderDepiction ? 300 : 1000 ) }} logUserOut={() => this.logUserOut()} loggedIn={loggedIn} userDetails={userDetails} disableUserButton={disableUserButton} /> <main> <Container> <Route path='/profile' component={ProfileScreen} /> {/* <Route path='/order/:id' component={OrderScreen} /> <Route path='/shipping' component={ShippingScreen} /> <Route path='/payment' component={PaymentScreen} /> <Route path='/placeorder' component={PlaceOrderScreen} /> <Route path='/login' component={LoginScreen} /> <Route path='/register' component={RegisterScreen} /> <Route path='/product/:id' component={ProductScreen} /> <Route path='/cart/:id?' component={CartScreen} /> <Route path='/admin/userlist' component={UserListScreen} /> <Route path='/admin/user/:id/edit' component={UserEditScreen} /> <Route path='/admin/productlist' component={ProductListScreen} exact /> <Route path='/admin/productlist/:pageNumber' component={ProductListScreen} exact /> <Route path='/admin/product/:id/edit' component={ProductEditScreen} /> <Route path='/admin/orderlist' component={OrderListScreen} /> <Route path='/search/:keyword' component={HomeScreen} exact /> <Route path='/page/:pageNumber' component={HomeScreen} exact /> <Route path='/search/:keyword/page/:pageNumber' component={HomeScreen} exact /> <Route path='/' component={HomeScreen} exact /> */} </Container> </main> <Footer className={renderAuthForm && "disable"} /> </Router> ) } export default App
import React from "react"; const ScoreboardContext = React.createContext(); export const Provider = ScoreboardContext.Provider; export const Consumer = ScoreboardContext.Consumer;
require('dotenv').config(); const mongoose = require('./config/database'); const express = require('express'); const path = require('path'); const cors = require('cors'); const app = express(); const taskRouter = require('./routes/task'); const userRouter = require('./routes/user'); app.use(express.json()); app.use(cors('*')); app.get('/', (req, res) => { res.sendFile(path.join(__dirname + '/index.htm')); }); app.use('/task', taskRouter); app.use('/user', userRouter); mongoose.connection.on('connected', () => app.listen(process.env.PORT || 4000, () => console.log('Server and mongoDB is running'))); mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
var generatorOf = require('../../generator-of'); module.exports = generatorOf(function generator$miscellaneous$treatys() { var names1 = ["Abdication", "Abuse", "Amalgamation", "Ambitions", "Anarchy", "Angels", "Ashes", "Assassinations", "Autarchy", "Autonomy", "Awakening", "Backdoors", "Backstabs", "Betrayal", "Blackmail", "Blessings", "Bliss", "Blood", "Bloodshed", "Blunders", "Bowing", "Broken Armies", "Broken Souls", "Brutalities", "Burning Flags", "Carnage", "Certain Demise", "Certain Doom", "Charity", "Clean Hands", "Cleansing Rains", "Coalitions", "Comraes", "Condemnation", "Control", "Corruption", "Covert Affairs", "Cowards", "Crooks", "Damnation", "Darkness", "Death", "Deaths", "Deceit", "Deception", "Defamation", "Delusion", "Demands", "Democracy", "Denial", "Desire", "Destruction", "Devotion", "Dilemmas", "Disgrace", "Disguises", "Dishonor", "Disloyalty", "Disorder", "Disruption", "Disunion", "Domination", "Duality", "Duplicity", "Duty", "Eradication", "Essence", "Evaded War", "Executions", "Exiles", "Expansion", "Extermination", "Extortion", "Faith", "Favor", "Flying Colors", "Fortune", "Fraud", "Freedom", "Fusions", "Gluttony", "Greed", "Growth", "Guilt", "Harmony", "Heart", "Heaven", "Hidden Goals", "Hoaxes", "Honesty", "Honor", "Hope", "Humiliation", "Humility", "Hypocrisy", "Ignorance", "Illusions", "Impostors", "Independence", "Individuality", "Innocent Victims", "Innocents", "Integrity", "Intelligence", "Interruption", "Justice", "Kindness", "Law", "Legitimacy", "Liberty", "Lies", "Life", "Loyalty", "Luxury", "Magic", "Malignance", "Martial Law", "Mergers", "Miracles", "Mistakes", "Mysteries", "Mystics", "Necrosis", "Neglect", "New Hope", "Nothing", "Obedience", "Obscurity", "Oppression", "Oversights", "Passivism", "Patriots", "Perfection", "Persecution", "Pressure", "Privacy", "Promises", "Promotions", "Prosperity", "Protection", "Public Order", "Public Unrest", "Purity", "Rebirth", "Recovery", "Reincarnation", "Rejuvenation", "Reparation", "Resignation", "Respect", "Restoration", "Resurgence", "Revelations", "Revival", "Riches", "Righteousness", "Sanctification", "Sanctions", "Scams", "Scarred Lands", "Secrets", "Security", "Separation", "Severance", "Shams", "Shrouded Lies", "Shrouded Truths", "Silence", "Slander", "Slavery", "Slaves", "Solutions", "Sovereignty", "Stagnation", "Submission", "Subterfuge", "Support", "Surrender", "Survival", "Terminality", "The Bastard", "The Brotherhood", "The Burning City", "The Curse", "The Dictator", "The False King", "The Forest", "The Forsaken", "The Greater Good", "The Grim Reaper", "The Impasse", "The Iron Hand", "The Lands", "The Light", "The Massacre", "The Meek", "The Mountains", "The Occult", "The Oracle", "The Pure", "The Silver Angel", "The Trojan Horse", "The True King", "Theft", "Thieves", "Torment", "Torture", "Traitors", "Treachery", "Triumph", "Truth", "Unanimity", "Unification", "Unions", "Unison", "Utopia", "Vetos", "Victims", "Victory", "Vigor", "Virtues", "Vitality", "Wealth", "Wellfare", "Wonder"]; i = Math.floor(this.random() * 10); { rnd = Math.floor(this.random() * names1.length); names = "Treaty of " + names1[rnd]; return names; } })
import BaseView from '../internals/BaseView'; import BaseForm from '../internals/BaseForm'; import Util from '../../../util/Util'; // for BETA, // redirect is needed for Apple SSO Extension to intercept the request, because // - XHR request is not interceptable // - form post is interceptable, but some app (Outlook) closes the app after // We may have a different approach/UX for EA const Body = BaseForm.extend({ noButtonBar: true, title: 'You are being redirected', initialize () { BaseForm.prototype.initialize.apply(this, arguments); // TODO: OKTA-286547 // this should be handle by the foundation, not on the view level const method = this.options.appState.get('remediations') .filter(v => v.name === this.options.appState.get('currentFormName'))[0].method || ''; if (method.toLowerCase() === 'get') { Util.redirectWithFormGet(this.options.currentViewState.href); } else { this.add('<div class="spinner"></div>'); this.options.appState.trigger('saveForm', this.model); } } }); export default BaseView.extend({ Body, });
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import View from './View' import { calcTextWidth, createFont } from '../utils/canvas' import { formatBigNumber, formatPrecision } from '../utils/format' import { YAxisType } from '../options/styleOptions' import { renderStrokeFillRoundRect } from '../renderer/rect' import { renderText } from '../renderer/text' export default class YAxisOverlayView extends View { constructor (container, chartData, yAxis, paneId) { super(container, chartData) this._yAxis = yAxis this._paneId = paneId } _draw () { this._ctx.textBaseline = 'middle' this._drawTag() this._drawCrossHairLabel() } /** * 绘制标签 * @private */ _drawTag () { const tags = this._chartData.tagStore().get(this._paneId) if (tags) { tags.forEach(tag => { tag.drawText(this._ctx) }) } } _drawCrossHairLabel () { const crosshair = this._chartData.crosshairStore().get() if (crosshair.paneId !== this._paneId || this._chartData.dataList().length === 0) { return } const styleOptions = this._chartData.styleOptions() const crosshairOptions = styleOptions.crosshair const crosshairHorizontalOptions = crosshairOptions.horizontal const crosshairHorizontalTextOptions = crosshairHorizontalOptions.text if (!crosshairOptions.show || !crosshairHorizontalOptions.show || !crosshairHorizontalTextOptions.show) { return } const value = this._yAxis.convertFromPixel(crosshair.y) let text if (this._yAxis.yAxisType() === YAxisType.PERCENTAGE) { const fromData = (this._chartData.visibleDataList()[0] || {}).data || {} text = `${((value - fromData.close) / fromData.close * 100).toFixed(2)}%` } else { const techs = this._chartData.technicalIndicatorStore().instances(this._paneId) let precision = 0 let shouldFormatBigNumber = false if (this._yAxis.isCandleYAxis()) { precision = this._chartData.pricePrecision() } else { techs.forEach(tech => { precision = Math.max(tech.precision, precision) if (!shouldFormatBigNumber) { shouldFormatBigNumber = tech.shouldFormatBigNumber } }) } text = formatPrecision(value, precision) if (shouldFormatBigNumber) { text = formatBigNumber(text) } } const textSize = crosshairHorizontalTextOptions.size this._ctx.font = createFont(textSize, crosshairHorizontalTextOptions.weight, crosshairHorizontalTextOptions.family) const yAxisDataLabelWidth = calcTextWidth(this._ctx, text) let rectStartX const paddingLeft = crosshairHorizontalTextOptions.paddingLeft const paddingRight = crosshairHorizontalTextOptions.paddingRight const paddingTop = crosshairHorizontalTextOptions.paddingTop const paddingBottom = crosshairHorizontalTextOptions.paddingBottom const borderSize = crosshairHorizontalTextOptions.borderSize const rectWidth = yAxisDataLabelWidth + borderSize * 2 + paddingLeft + paddingRight const rectHeight = textSize + borderSize * 2 + paddingTop + paddingBottom if (this._yAxis.isFromYAxisZero()) { rectStartX = 0 } else { rectStartX = this._width - rectWidth } const rectY = crosshair.y - borderSize - paddingTop - textSize / 2 // 绘制y轴文字外的边框 renderStrokeFillRoundRect( this._ctx, crosshairHorizontalTextOptions.backgroundColor, crosshairHorizontalTextOptions.borderColor, borderSize, rectStartX, rectY, rectWidth, rectHeight, crosshairHorizontalTextOptions.borderRadius ) renderText( this._ctx, crosshairHorizontalTextOptions.color, rectStartX + borderSize + paddingLeft, crosshair.y, text ) } }
/* JCE Editor - 2.4.6 | 19 January 2015 | http://www.joomlacontenteditor.net | Copyright (C) 2006 - 2014 Ryan Demmer. All rights reserved | GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html */ (function(){tinymce.create("tinymce.plugins.Print",{init:function(a,b){a.addCommand("mcePrint",function(){a.getWin().print()});a.addButton("print",{title:"print.desc",cmd:"mcePrint"})},getInfo:function(){return{longname:"Print",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/print",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("print",tinymce.plugins.Print)})();
const process = require('process') const EjsParser = require('./../EjsParser') const {getFilesByType} = require('./../FileParser'); const {fileTypes} = require('./../Constants'); module.exports.run = function run (path) { const list = getFilesByType(fileTypes.COMPONENT, `./${path}`) EjsParser.create('ComponentImporter', {list}, `./${path}/index.js`) }
const fs = require("fs") const _ = require("lodash") const shell = require("shelljs") const { execSync } = require("child_process") const utils = require("../utils/zero-dev-utils.js") class ZeroDevDeploy { constructor(options) { this.options = options this.command = "deploy" this.validate() this.getProject() } exec() { let promise = new Promise((resolve, reject) => { utils.cd(this.project.name) utils.shell("./deploy.sh") resolve({ status: "OK" }) }) .catch((error) => { utils.error(error) process.exit(-1) }) return(promise) } getProject() { this.project = utils.getProject(this.options.projectFile) if(this.project) { // Add options to project this.project.options = this.options utils.message("Project:") console.log(JSON.stringify(this.project, null, 2)) } else { utils.message("Hmmm...") utils.error(`Can't seem to find ${this.options.projectFile} here...`) console.log() utils.message("Please resolve and try again.") console.log() shell.exec(`${this.options.zeroDevOSDir}/dez deploy --help`) process.exit(-1) } } validate() { let validOptions = true let messages = [] if(!this.options.projectFile) { messages.push("--project is required") validOptions = false } if(!validOptions) { console.log() utils.message("Hmmm...") messages.forEach((message) => { utils.error(message) }) console.log() utils.message("Please resolve and try again.") console.log() shell.exec(`${this.options.zeroDevOSDir}/dez ${this.command} --help`) process.exit(-1) } } } module.exports = ZeroDevDeploy
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {AmpEvents} from '../../../src/amp-events'; import {BindEvents} from './bind-events'; import {BindExpressionResultDef} from './bind-expression'; import {BindValidator} from './bind-validator'; import {BindingDef} from './bind-evaluator'; import {ChunkPriority, chunk} from '../../../src/chunk'; import {Deferred} from '../../../src/utils/promise'; import {RAW_OBJECT_ARGS_KEY} from '../../../src/action-constants'; import {Services} from '../../../src/services'; import {Signals} from '../../../src/utils/signals'; import {debounce} from '../../../src/utils/rate-limit'; import {deepMerge, dict} from '../../../src/utils/object'; import {dev, user} from '../../../src/log'; import {elementByTag, iterateCursor, waitForBodyPromise} from '../../../src/dom'; import {filterSplice} from '../../../src/utils/array'; import {getMode} from '../../../src/mode'; import {getValueForExpr} from '../../../src/json'; import {installServiceInEmbedScope} from '../../../src/service'; import {invokeWebWorker} from '../../../src/web-worker/amp-worker'; import {isArray, isObject, toArray} from '../../../src/types'; import {isFiniteNumber} from '../../../src/types'; import {map} from '../../../src/utils/object'; import {parseJson, recursiveEquals} from '../../../src/json'; import {reportError} from '../../../src/error'; import {rewriteAttributesForElement} from '../../../src/sanitizer'; import {startsWith} from '../../../src/string'; const TAG = 'amp-bind'; /** * Regular expression that identifies AMP CSS classes. * Includes 'i-amphtml-', '-amp-', and 'amp-' prefixes. * @type {!RegExp} */ const AMP_CSS_RE = /^(i?-)?amp(html)?-/; /** * Maximum depth for state merge. * @type {number} */ const MAX_MERGE_DEPTH = 10; /** * A bound property, e.g. [property]="expression". * `previousResult` is the result of this expression during the last evaluation. * @typedef {{property: string, expressionString: string, previousResult: (./bind-expression.BindExpressionResultDef|undefined)}} */ let BoundPropertyDef; /** * A tuple containing a single element and all of its bound properties. * @typedef {{boundProperties: !Array<BoundPropertyDef>, element: !Element}} */ let BoundElementDef; /** * @typedef {{boundElements: !Array<BoundElementDef>, bindings: !Array<./bind-evaluator.BindingDef>, expressionToElements: !Object<string, !Array<!Element>>, limitExceeded: boolean}} */ let NodeScanDef; /** * A map of tag names to arrays of attributes that do not have non-bind * counterparts. For instance, amp-carousel allows a `[slide]` attribute, * but does not support a `slide` attribute. * @const {!Object<string, !Array<string>>} */ const BIND_ONLY_ATTRIBUTES = map({ 'AMP-CAROUSEL': ['slide'], 'AMP-LIST': ['state'], 'AMP-SELECTOR': ['selected'], }); /** * Bind is an ampdoc-scoped service that handles the Bind lifecycle, from * scanning for bindings to evaluating expressions to mutating elements. * @implements {../../../src/service.EmbeddableService} */ export class Bind { /** * If `opt_win` is provided, scans its document for bindings instead. * @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc * @param {!Window=} opt_win */ constructor(ampdoc, opt_win) { /** @const {!../../../src/service/ampdoc-impl.AmpDoc} */ this.ampdoc = ampdoc; /** @const @private {!Window} */ this.win_ = ampdoc.win; /** * The window containing the document to scan. * May differ from the `ampdoc`'s window e.g. in FIE. * @const @private {!Window} */ this.localWin_ = opt_win || ampdoc.win; /** * Array of ActionInvocation.sequenceId values that have been invoked. * Used to ensure that only one "AMP.setState" or "AMP.pushState" action * may be triggered per event. Periodically cleared. * @const @private {!Array<number>} */ this.actionSequenceIds_ = []; /** @const @private {!Function} */ this.eventuallyClearActionSequenceIds_ = debounce(this.win_, () => { this.actionSequenceIds_.length = 0; }, 5000); /** @private {!Array<BoundElementDef>} */ this.boundElements_ = []; /** @const @private {!Function} */ this.boundOnDomUpdate_ = this.onDomUpdate_.bind(this); /** * Maps expression string to the element(s) that contain it. * @private @const {!Object<string, !Array<!Element>>} */ this.expressionToElements_ = map(); /** @private {!../../../src/service/history-impl.History} */ this.history_ = Services.historyForDoc(ampdoc); /** @private {!Array<string>} */ this.overridableKeys_ = []; /** * Upper limit on total number of bindings. * * The initial value is set to 1000 which, based on ~2ms expression parse * time, caps "time to interactive" at ~2s after page load. * * User interactions can add new bindings (e.g. infinite scroll), so this * can increase over time to a final limit of 2000 bindings. * * @private {number} */ this.maxNumberOfBindings_ = 1000; /** @const @private {!../../../src/service/resources-impl.Resources} */ this.resources_ = Services.resourcesForDoc(ampdoc); /** * The current values of all bound expressions on the page. * @const @private {!JsonObject} */ this.state_ = /** @type {!JsonObject} */ (map()); /** @const {!../../../src/service/timer-impl.Timer} */ this.timer_ = Services.timerFor(this.win_); /** @const @private {!./bind-validator.BindValidator} */ this.validator_ = new BindValidator(); /** @const @private {!../../../src/service/viewer-impl.Viewer} */ this.viewer_ = Services.viewerForDoc(this.ampdoc); this.viewer_.onMessageRespond('premutate', this.premutate_.bind(this)); const bodyPromise = (opt_win) ? waitForBodyPromise(opt_win.document) .then(() => dev().assertElement(opt_win.document.body)) : ampdoc.whenBodyAvailable(); /** * Resolved when the service finishes scanning the document for bindings. * @const @private {Promise} */ this.initializePromise_ = this.viewer_.whenFirstVisible().then(() => bodyPromise).then(body => { const head = (opt_win) ? opt_win.document.head : ampdoc.getHeadNode(); return this.initialize_(body, head && elementByTag(head, 'title')); }); /** @private {Promise} */ this.setStatePromise_ = null; /** @private @const {!../../../src/utils/signals.Signals} */ this.signals_ = new Signals(); // Expose for debugging in the console. AMP.printState = this.printState_.bind(this); } /** @override */ adoptEmbedWindow(embedWin) { installServiceInEmbedScope( embedWin, 'bind', new Bind(this.ampdoc, embedWin)); } /** * @return {!../../../src/utils/signals.Signals} */ signals() { return this.signals_; } /** * Merges `state` into the current state and immediately triggers an * evaluation unless `opt_skipEval` is false. * @param {!JsonObject} state * @param {boolean=} opt_skipEval * @param {boolean=} opt_isAmpStateMutation * @return {!Promise} */ setState(state, opt_skipEval, opt_isAmpStateMutation) { // TODO(choumx): What if `state` contains references to globals? try { deepMerge(this.state_, state, MAX_MERGE_DEPTH); } catch (e) { user().error(TAG, 'Failed to merge result from AMP.setState().', e); } if (opt_skipEval) { return Promise.resolve(); } user().fine(TAG, 'State updated; re-evaluating expressions...'); const promise = this.initializePromise_ .then(() => this.evaluate_()) .then(results => this.apply_(results, opt_isAmpStateMutation)); if (getMode().test) { promise.then(() => { this.dispatchEventForTesting_(BindEvents.SET_STATE); }); } return this.setStatePromise_ = promise; } /** * Executes an `AMP.setState()` or `AMP.pushState()` action. * @param {!../../../src/service/action-impl.ActionInvocation} invocation * @return {!Promise} */ invoke(invocation) { const {args, event, method, sequenceId, tagOrTarget} = invocation; // Store the sequenceId values of action invocations and only allow one // setState() or pushState() event per sequence. if (this.actionSequenceIds_.includes(sequenceId)) { user().error(TAG, 'One state action allowed per event.'); return Promise.resolve(); } this.actionSequenceIds_.push(sequenceId); // Flush stored sequence IDs five seconds after the last invoked action. this.eventuallyClearActionSequenceIds_(); const expression = args[RAW_OBJECT_ARGS_KEY]; if (expression) { // Increment bindings limit by 500 on each invocation to a max of 2000. this.maxNumberOfBindings_ = Math.min(2000, Math.max(1000, this.maxNumberOfBindings_ + 500)); // Signal first mutation (subsequent signals are harmless). this.signals_.signal('FIRST_MUTATE'); const scope = dict(); if (event && event.detail) { scope['event'] = event.detail; } switch (method) { case 'setState': return this.setStateWithExpression(expression, scope); case 'pushState': return this.pushStateWithExpression(expression, scope); default: return Promise.reject(dev().createError('Unrecognized method: ' + `"${tagOrTarget}.${method}"`)); } } else { user().error('AMP-BIND', 'Please use the object-literal syntax, ' + 'e.g. "AMP.setState({foo: \'bar\'})" instead of ' + '"AMP.setState(foo=\'bar\')".'); } return Promise.resolve(); } /** * Parses and evaluates an expression with a given scope and merges the * resulting object into current state. * @param {string} expression * @param {!JsonObject} scope * @return {!Promise} */ setStateWithExpression(expression, scope) { this.setStatePromise_ = this.evaluateExpression_(expression, scope) .then(result => this.setState(result)); return this.setStatePromise_; } /** * Same as setStateWithExpression() except also pushes new history. * Popping the new history stack entry will restore the values of variables * in `expression`. * @param {string} expression * @param {!JsonObject} scope * @return {!Promise} */ pushStateWithExpression(expression, scope) { return this.evaluateExpression_(expression, scope).then(result => { // Store the current values of each referenced variable in `expression` // so that we can restore them on history-pop. const oldState = map(); Object.keys(result).forEach(variable => { const value = this.state_[variable]; // Store a deep copy of `value` to make sure `oldState` isn't // modified by subsequent setState() actions. oldState[variable] = this.copyJsonObject_(value); }); const onPop = () => this.setState(oldState); this.history_.push(onPop); return this.setState(result); }); } /** * Removes bindings from `removed` elements and scans `added` for bindings. * Then, evaluates all expressions and applies results to `added` elements. * Does _not_ mutate any other elements. * * Returned promise is resolved when all operations complete. * If they don't complete within `timeout` ms, the promise is rejected. * * @param {!Array<!Element>} added * @param {!Array<!Element>} removed * @param {number} timeout Timeout in milliseconds. * @return {!Promise} */ scanAndApply(added, removed, timeout = 2000) { const beforeFirstMutate = !this.signals_.get('FIRST_MUTATE'); const promise = this.removeBindingsForNodes_(removed) .then(() => this.addBindingsForNodes_(added)) .then(numberOfBindingsAdded => { // Don't reevaluate/apply if there are no bindings. if (numberOfBindingsAdded == 0) { return; } return this.evaluate_().then(results => { // Before first mutate, verify `added` elements and throw expected // error to measure the impact of "faster-amp-list" breaking change. if (beforeFirstMutate) { const mismatches = this.verify_(results, added, /* warn */ false); if (mismatches.length) { // Cap size of mismatch string to 30 chars. user().expectedError(TAG, 'Pre-gesture mismatch: ' + String(mismatches).substr(0, 30)); } } return this.applyElements_(results, added); }); }); return this.timer_.timeoutPromise(timeout, promise, 'Timed out waiting for amp-bind to process rendered template.'); } /** * Returns the stringified value of the global state for a given field-based * expression, e.g. "foo.bar.baz". * @param {string} expr * @return {string} */ getStateValue(expr) { const value = getValueForExpr(this.state_, expr); if (isObject(value) || isArray(value)) { return JSON.stringify(/** @type {JsonObject} */(value)); } else { return String(value); } } /** * Scans the ampdoc for bindings and creates the expression evaluator. * @param {!Node} rootNode * @param {?Node} titleNode * @return {!Promise} * @private */ initialize_(rootNode, titleNode) { dev().fine(TAG, 'Scanning DOM for bindings and macros...'); const nodes = [rootNode]; if (titleNode) { nodes.push(titleNode); } let promise = Promise.all([ this.addMacros_(), this.addBindingsForNodes_(nodes)] ).then(() => { // Listen for DOM updates (e.g. template render) to rescan for bindings. rootNode.addEventListener(AmpEvents.DOM_UPDATE, this.boundOnDomUpdate_); }); if (getMode().development) { // Check default values against initial expression results. promise = promise.then(() => this.evaluate_().then(results => this.verify_(results)) ); } if (getMode().test) { // Signal init completion for integration tests. promise.then(() => { this.dispatchEventForTesting_(BindEvents.INITIALIZE); }); } return promise; } /** * The current number of bindings. * @return {number} * @visibleForTesting */ numberOfBindings() { return this.boundElements_.reduce((number, boundElement) => { return number + boundElement.boundProperties.length; }, 0); } /** * @param {number} value * @visibleForTesting */ setMaxNumberOfBindingsForTesting(value) { this.maxNumberOfBindings_ = value; } /** @return {!../../../src/service/history-impl.History} */ historyForTesting() { return this.history_; } /** * Calls setState(s), where s is data.state with the non-overridable keys * removed. * @param {*} data * @return {!Promise} * @private */ premutate_(data) { const ignoredKeys = []; return this.initializePromise_.then(() => { Object.keys(data.state).forEach(key => { if (!this.overridableKeys_.includes(key)) { delete data.state[key]; ignoredKeys.push(key); } }); if (ignoredKeys.length > 0) { user().warn(TAG, 'Some state keys could not be premutated ' + 'because they are missing the overridable attribute: ' + ignoredKeys.join(', ')); } return this.setState(data.state); }); } /** * Marks the given key as overridable so that it can be overriden by * a premutate message from the viewer. * @param {string} key */ makeStateKeyOverridable(key) { this.overridableKeys_.push(key); } /** * Scans the document for <amp-bind-macro> elements, and adds them to the * bind-evaluator. * * Returns a promise that resolves after macros have been added. * * @return {!Promise<number>} * @private */ addMacros_() { const elements = this.ampdoc.getBody().querySelectorAll('AMP-BIND-MACRO'); const macros = /** @type {!Array<!./amp-bind-macro.AmpBindMacroDef>} */ ([]); iterateCursor(elements, element => { const argumentNames = (element.getAttribute('arguments') || '') .split(',') .map(s => s.trim()); macros.push({ id: element.getAttribute('id'), argumentNames, expressionString: element.getAttribute('expression'), }); }); if (macros.length == 0) { return Promise.resolve(0); } else { return this.ww_('bind.addMacros', [macros]).then(errors => { // Report macros that failed to parse (e.g. expression size exceeded). errors.forEach((e, i) => { this.reportWorkerError_( e, `${TAG}: Parsing amp-bind-macro failed.`, elements[i]); }); return macros.length; }); } } /** * For each node in an array, scans it and its descendants for bindings. * This function is not idempotent. * * Returns a promise that resolves after bindings have been added. * * @param {!Array<!Node>} nodes * @return {!Promise<number>} * @private */ addBindingsForNodes_(nodes) { // For each node, scan it for bindings and store them. const scanPromises = nodes.map(node => { // Limit number of total bindings (unless in local manual testing). const limit = (getMode().localDev && !getMode().test) ? Number.POSITIVE_INFINITY : this.maxNumberOfBindings_ - this.numberOfBindings(); return this.scanNode_(node, limit).then(results => { const { boundElements, bindings, expressionToElements, limitExceeded, } = results; this.boundElements_ = this.boundElements_.concat(boundElements); Object.assign(this.expressionToElements_, expressionToElements); if (limitExceeded) { dev().expectedError(TAG, 'Maximum number of bindings reached ' + `(${this.maxNumberOfBindings_}). Additional elements with ` + 'bindings will be ignored.'); } return bindings; }); }); // Once all scans are complete, combine the bindings and ask web-worker to // evaluate expressions in a single RPC. return Promise.all(scanPromises).then(results => { // `results` is a 2D array where results[i] is an array of bindings. // Flatten this into a 1D array of bindings via concat. const bindings = Array.prototype.concat.apply([], results); dev().fine(TAG, `Scanned ${bindings.length} bindings from ` + `${nodes.length} elements and their descendants.`); if (bindings.length == 0) { return bindings.length; } else { dev().fine(TAG, 'Asking worker to parse expressions...'); return this.ww_('bind.addBindings', [bindings]).then(parseErrors => { // Report each parse error. Object.keys(parseErrors).forEach(expressionString => { const elements = this.expressionToElements_[expressionString]; if (elements.length > 0) { this.reportWorkerError_(parseErrors[expressionString], `${TAG}: Expression compile error in "${expressionString}".`, elements[0]); } }); dev().fine(TAG, 'Finished parsing expressions with ' + `${Object.keys(parseErrors).length} errors.`); return bindings.length; }); } }); } /** * For each node in an array, removes all bindings for it and its descendants. * * Returns a promise that resolves after bindings have been removed. * * @param {!Array<!Node>} nodes * @return {!Promise} * @private */ removeBindingsForNodes_(nodes) { const before = (getMode().development) ? this.numberOfBindings() : 0; // Eliminate bound elements that are descendants of `nodes`. filterSplice(this.boundElements_, boundElement => { for (let i = 0; i < nodes.length; i++) { if (nodes[i].contains(boundElement.element)) { return false; } } return true; }); const after = (getMode().development) ? this.numberOfBindings() : 0; if (after < before) { dev().fine(TAG, `Removed ${before - after} bindings from ${nodes.length} ` + 'elements and their descendants.'); } // Eliminate elements from the expression to elements map that // have node as an ancestor. Delete expressions that are no longer // bound to elements. const deletedExpressions = []; for (const expression in this.expressionToElements_) { const elements = this.expressionToElements_[expression]; filterSplice(elements, element => { for (let i = 0; i < nodes.length; i++) { if (nodes[i].contains(element)) { return false; } } return true; }); if (elements.length == 0) { deletedExpressions.push(expression); delete this.expressionToElements_[expression]; } } // Remove the bindings from the evaluator. if (deletedExpressions.length > 0) { dev().fine(TAG, 'Asking worker to remove expressions...'); return this.ww_( 'bind.removeBindingsWithExpressionStrings', [deletedExpressions]); } else { return Promise.resolve(); } } /** * Scans `node` for attributes that conform to bind syntax and returns * a tuple containing bound elements and binding data for the evaluator. * @param {!Node} node * @param {number} limit * @return {!Promise<NodeScanDef>} * @private */ scanNode_(node, limit) { /** @type {!Array<BoundElementDef>} */ const boundElements = []; /** @type {!Array<./bind-evaluator.BindingDef>} */ const bindings = []; /** @type {!Object<string, !Array<!Element>>} */ const expressionToElements = map(); const doc = dev().assert(node.ownerDocument, 'ownerDocument is null.'); // Third and fourth params of `createTreeWalker` are not optional on IE11. const walker = doc.createTreeWalker(node, NodeFilter.SHOW_ELEMENT, null, /* entityReferenceExpansion */ false); // Set to true if number of bindings in `node` exceeds `limit`. let limitExceeded = false; // Helper function for scanning the tree walker's next node. // Returns true if the walker has no more nodes. const scanNextNode_ = () => { const node = walker.currentNode; if (!node) { return true; } const element = dev().assertElement(node); const {tagName} = element; let boundProperties = this.scanElement_(element); // Stop scanning once |limit| bindings are reached. if (bindings.length + boundProperties.length > limit) { boundProperties = boundProperties.slice(0, limit - bindings.length); limitExceeded = true; } if (boundProperties.length > 0) { boundElements.push({element, boundProperties}); } boundProperties.forEach(boundProperty => { const {property, expressionString} = boundProperty; bindings.push({tagName, property, expressionString}); if (!expressionToElements[expressionString]) { expressionToElements[expressionString] = []; } expressionToElements[expressionString].push(element); }); return !walker.nextNode() || limitExceeded; }; return new Promise(resolve => { const chunktion = idleDeadline => { let completed = false; // If `requestIdleCallback` is available, scan elements until // idle time runs out. if (idleDeadline && !idleDeadline.didTimeout) { while (idleDeadline.timeRemaining() > 1 && !completed) { completed = scanNextNode_(); } } else { // If `requestIdleCallback` isn't available, scan elements in buckets. // Bucket size is a magic number that fits within a single frame. const bucketSize = 250; for (let i = 0; i < bucketSize && !completed; i++) { completed = scanNextNode_(); } } // If we scanned all elements, resolve. Otherwise, continue chunking. if (completed) { resolve({ boundElements, bindings, expressionToElements, limitExceeded, }); } else { chunk(this.ampdoc, chunktion, ChunkPriority.LOW); } }; chunk(this.ampdoc, chunktion, ChunkPriority.LOW); }); } /** * Returns bound properties for an element. * @param {!Element} element * @return {!Array<{property: string, expressionString: string}>} * @private */ scanElement_(element) { const boundProperties = []; const attrs = element.attributes; for (let i = 0, numberOfAttrs = attrs.length; i < numberOfAttrs; i++) { const attr = attrs[i]; const boundProperty = this.scanAttribute_(attr, element); if (boundProperty) { boundProperties.push(boundProperty); } } return boundProperties; } /** * Returns the bound property and expression string within a given attribute, * if it exists. Otherwise, returns null. * @param {!Attr} attribute * @param {!Element} element * @return {?{property: string, expressionString: string}} * @private */ scanAttribute_(attribute, element) { const tag = element.tagName; const attr = attribute.name; let property; if (attr.length > 2 && attr[0] === '[' && attr[attr.length - 1] === ']') { property = attr.substr(1, attr.length - 2); } else if (startsWith(attr, 'data-amp-bind-')) { property = attr.substr(14); // Ignore `data-amp-bind-foo` if `[foo]` already exists. if (element.hasAttribute(`[${property}]`)) { return null; } } if (property) { if (this.validator_.canBind(tag, property)) { return {property, expressionString: attribute.value}; } else { const err = user().createError( `${TAG}: Binding to [${property}] on <${tag}> is not allowed.`); reportError(err, element); } } return null; } /** * Evaluates a single expression and returns its result. * @param {string} expression * @param {!JsonObject} scope * @return {!Promise<!JsonObject>} */ evaluateExpression_(expression, scope) { return this.initializePromise_.then(() => { // Allow expression to reference current state in addition to event state. Object.assign(scope, this.state_); return this.ww_('bind.evaluateExpression', [expression, scope]); }).then(returnValue => { const {result, error} = returnValue; if (error) { // Throw to reject promise. throw this.reportWorkerError_(error, `${TAG}: Expression eval failed.`); } else { return result; } }); } /** * Reevaluates all expressions and returns a map of expressions to results. * @return {!Promise<!Object<string, ./bind-expression.BindExpressionResultDef>>} * @private */ evaluate_() { user().fine(TAG, 'Asking worker to re-evaluate expressions...'); const evaluatePromise = this.ww_('bind.evaluateBindings', [this.state_]); return evaluatePromise.then(returnValue => { const {results, errors} = returnValue; // Report evaluation errors. Object.keys(errors).forEach(expressionString => { const elements = this.expressionToElements_[expressionString]; if (elements.length > 0) { const evalError = errors[expressionString]; const userError = user().createError( `${TAG}: Expression evaluation error in "${expressionString}". ` + evalError.message); userError.stack = evalError.stack; reportError(userError, elements[0]); } }); return results; }); } /** * Verifies expression results vs. current DOM state and returns an * array of bindings with mismatches (if any). * @param {Object<string, ./bind-expression.BindExpressionResultDef>} results * @param {?Array<!Element>=} elements If provided, only verifies bindings * contained within the given elements. Otherwise, verifies all bindings. * @param {boolean=} warn If true, emits a user warning for verification * mismatches. Otherwise, does not emit a warning. * @return {!Array<string>} * @private */ verify_(results, elements = null, warn = true) { // Collate strings containing details of verification mismatches to return. const mismatches = {}; this.boundElements_.forEach(boundElement => { const {element, boundProperties} = boundElement; // If provided, filter elements that are _not_ children of `opt_elements`. if (elements && !this.elementsContains_(elements, element)) { return; } boundProperties.forEach(boundProperty => { const newValue = results[boundProperty.expressionString]; if (newValue === undefined) { return; } const mismatch = this.verifyBinding_(boundProperty, element, newValue); if (!mismatch) { return; } const {tagName} = element; const {property, expressionString} = boundProperty; const {expected, actual} = mismatch; // Only store unique mismatches (dupes possible when rendering an array // of data to a template). mismatches[`${tagName}[${property}]${expected}:${actual}`] = true; if (warn) { user().warn(TAG, `Default value (${actual}) does not match first ` + `result (${expected}) for <${tagName} [${property}]="` + `${expressionString}">. We recommend writing expressions with ` + 'matching default values, but this can be safely ignored if ' + 'intentional.'); } }); }); return Object.keys(mismatches); } /** * Returns true if `el` is contained within any element in `elements`. * @param {!Array<!Element>} elements * @param {!Element} el * @return {boolean} * @private */ elementsContains_(elements, el) { for (let i = 0; i < elements.length; i++) { if (elements[i].contains(el)) { return true; } } return false; } /** * Determines which properties to update based on results of evaluation * of all bound expression strings with the current state. This method * will only return properties that need to be updated along with their * new value. * @param {!Array<!BoundPropertyDef>} boundProperties * @param {Object<string, ./bind-expression.BindExpressionResultDef>} results * @return {!Array<{boundProperty: !BoundPropertyDef, newValue: !./bind-expression.BindExpressionResultDef}>} * @private */ calculateUpdates_(boundProperties, results) { const updates = []; boundProperties.forEach(boundProperty => { const {expressionString, previousResult} = boundProperty; const newValue = results[expressionString]; // Support equality checks for arrays of objects containing arrays. // Useful for rendering amp-list with amp-bind state via [src]. if (newValue === undefined || recursiveEquals(newValue, previousResult, /* depth */ 5)) { user().fine(TAG, 'Expression result unchanged or missing: ' + `"${expressionString}"`); } else { boundProperty.previousResult = newValue; user().fine(TAG, 'New expression result: ' + `"${expressionString}" -> ${newValue}`); updates.push({boundProperty, newValue}); } }); return updates; } /** * Applies expression results to all elements in the document. * @param {Object<string, ./bind-expression.BindExpressionResultDef>} results * @param {boolean=} opt_isAmpStateMutation * @return {!Promise} * @private */ apply_(results, opt_isAmpStateMutation) { const promises = this.boundElements_.map(boundElement => { // If this "apply" round is triggered by an <amp-state> mutation, // ignore updates to <amp-state> element to prevent update cycles. if (opt_isAmpStateMutation && boundElement.element.tagName == 'AMP-STATE') { return Promise.resolve(); } return this.applyBoundElement_(results, boundElement); }); return Promise.all(promises); } /** * Applies expression results to only given elements and their descendants. * @param {Object<string, ./bind-expression.BindExpressionResultDef>} results * @param {!Array<!Element>} elements * @return {!Promise} */ applyElements_(results, elements) { const promises = []; this.boundElements_.forEach(boundElement => { elements.forEach(element => { if (element.contains(boundElement.element)) { promises.push(this.applyBoundElement_(results, boundElement)); } }); }); return Promise.all(promises); } /** * Applies expression results to a single BoundElementDef. * @param {Object<string, ./bind-expression.BindExpressionResultDef>} results * @param {BoundElementDef} boundElement * @return {!Promise} */ applyBoundElement_(results, boundElement) { const {element, boundProperties} = boundElement; const updates = this.calculateUpdates_(boundProperties, results); if (updates.length === 0) { return Promise.resolve(); } return this.resources_.mutateElement(element, () => { const mutations = dict(); let width, height; updates.forEach(update => { const {boundProperty, newValue} = update; const mutation = this.applyBinding_(boundProperty, element, newValue); if (mutation) { mutations[mutation.name] = mutation.value; const {property} = boundProperty; if (property == 'width') { width = isFiniteNumber(newValue) ? Number(newValue) : width; } else if (property == 'height') { height = isFiniteNumber(newValue) ? Number(newValue) : height; } } }); if (width !== undefined || height !== undefined) { // TODO(choumx): Add new Resources method for adding change-size // request without scheduling vsync pass since `mutateElement()` // will schedule a pass after a short delay anyways. this.resources_./*OK*/changeSize(element, height, width); } if (typeof element.mutatedAttributesCallback === 'function') { // Prevent an exception in the callback from interrupting execution, // instead wrap in user error and give a helpful message. try { element.mutatedAttributesCallback(mutations); } catch (e) { const error = user().createError(`${TAG}: Applying expression ` + `results (${JSON.stringify(mutations)}) failed with error`, e); reportError(error, element); } } }); } /** * Mutates the bound property of `element` with `newValue`. * @param {!BoundPropertyDef} boundProperty * @param {!Element} element * @param {./bind-expression.BindExpressionResultDef} newValue * @return {?{name: string, value:./bind-expression.BindExpressionResultDef}} * @private */ applyBinding_(boundProperty, element, newValue) { const {property} = boundProperty; const tag = element.tagName; switch (property) { case 'text': element.textContent = String(newValue); // If this is a <title> element in the <head>, update document title. if (tag === 'TITLE' && element.parentNode === this.localWin_.document.head) { this.localWin_.document.title = String(newValue); } // Setting `textContent` on TEXTAREA element only works if user // has not interacted with the element, therefore `value` also needs // to be set (but `value` is not an attribute on TEXTAREA) if (tag == 'TEXTAREA') { element.value = String(newValue); } break; case 'class': // Preserve internal AMP classes. const ampClasses = []; for (let i = 0; i < element.classList.length; i++) { const cssClass = element.classList[i]; if (AMP_CSS_RE.test(cssClass)) { ampClasses.push(cssClass); } } if (Array.isArray(newValue) || typeof newValue === 'string') { element.setAttribute('class', ampClasses.concat(newValue).join(' ')); } else if (newValue === null) { element.setAttribute('class', ampClasses.join(' ')); } else { const err = user().createError( `${TAG}: "${newValue}" is not a valid result for [class].`); reportError(err, element); } break; default: // Some input elements treat some of their attributes as initial values. // Once the user interacts with these elements, the JS properties // underlying these attributes must be updated for the change to be // visible to the user. const updateProperty = (tag == 'INPUT' && property in element); const oldValue = element.getAttribute(property); let mutated = false; if (typeof newValue === 'boolean') { if (updateProperty && element[property] !== newValue) { // Property value _must_ be read before the attribute is changed. // Before user interaction, attribute updates affect the property. element[property] = newValue; mutated = true; } if (newValue && oldValue !== '') { element.setAttribute(property, ''); mutated = true; } else if (!newValue && oldValue !== null) { element.removeAttribute(property); mutated = true; } } else if (newValue !== oldValue) { const rewrittenValue = this.rewriteAttributes_(element, property, String(newValue)); if (rewrittenValue) { // Rewriting can fail due to e.g. invalid URL. if (updateProperty) { element[property] = rewrittenValue; } mutated = true; } } if (mutated) { return {name: property, value: newValue}; } break; } return null; } /** * Performs CDN rewrites for the given mutation and updates the element. * Returns the rewrite of `value` on success. Otherwise, returns undefined. * @see amp-cache-modifications.md#url-rewrites * @param {!Element} element * @param {string} property * @param {string} value * @return {string|undefined} * @private */ rewriteAttributes_(element, property, value) { // Rewrite attributes if necessary. Not done in worker since it relies on // `url#parseUrl` which uses <a>. Worker has URL API but not on IE11. let rewrittenValue; try { rewrittenValue = rewriteAttributesForElement(element, property, value); } catch (e) { const error = user().createError(`${TAG}: "${value}" is not a ` + `valid result for [${property}]`, e); reportError(error, element); } return rewrittenValue; } /** * If current state of `element` matches `expectedValue`, returns null. * Otherwise, returns a tuple containing the expected and actual values. * @param {!BoundPropertyDef} boundProperty * @param {!Element} element * @param {./bind-expression.BindExpressionResultDef} expectedValue * @return {?{expected: *, actual: *}} * @private */ verifyBinding_(boundProperty, element, expectedValue) { const {property} = boundProperty; const {tagName} = element; // Don't show a warning for bind-only attributes, // like 'slide' on amp-carousel. const bindOnlyAttrs = BIND_ONLY_ATTRIBUTES[tagName]; if (bindOnlyAttrs && bindOnlyAttrs.includes(property)) { return null; } let initialValue; let match; switch (property) { case 'text': initialValue = element.textContent; expectedValue = String(expectedValue); match = (initialValue.trim() === expectedValue.trim()); break; case 'class': initialValue = []; for (let i = 0; i < element.classList.length; i++) { const cssClass = element.classList[i]; // Ignore internal AMP classes. if (AMP_CSS_RE.test(cssClass)) { continue; } initialValue.push(cssClass); } /** @type {!Array<string>} */ let classes = []; if (Array.isArray(expectedValue)) { classes = expectedValue; } else if (typeof expectedValue === 'string') { const trimmed = expectedValue.trim(); if (trimmed.length > 0) { classes = trimmed.split(' '); } } else { const err = user().createError( `${TAG}: "${expectedValue}" is not a valid result for [class].`); reportError(err, element); } match = this.compareStringArrays_(initialValue, classes); break; default: initialValue = element.getAttribute(property); // Boolean attributes return values of either '' or null. if (expectedValue === true) { match = (initialValue === ''); } else if (expectedValue === false) { match = (initialValue === null); } else { match = (initialValue === expectedValue); } break; } return match ? null : {expected: expectedValue, actual: initialValue}; } /** * @param {!Event} event */ onDomUpdate_(event) { const target = dev().assertElement(event.target); // Skip amp-list since there's already a custom integration for it. const parent = target.parentNode; if (parent && parent.tagName == 'AMP-LIST') { dev().info(TAG, 'Skipping DOM_UPDATE rescan of:', target); return; } this.removeBindingsForNodes_([target]).then(() => { return this.addBindingsForNodes_([target]); }).then(() => { this.dispatchEventForTesting_(BindEvents.RESCAN_TEMPLATE); }); } /** * Helper for invoking a method on web worker. * @param {string} method * @param {!Array=} opt_args * @return {!Promise} */ ww_(method, opt_args) { return invokeWebWorker(this.win_, method, opt_args, this.localWin_); } /** * @param {{message: string, stack:string}} e * @param {string} message * @param {!Element=} opt_element * @return {!Error} * @private */ reportWorkerError_(e, message, opt_element) { const userError = user().createError(message + ' ' + e.message); userError.stack = e.stack; reportError(userError, opt_element); return userError; } /** * Returns true if both arrays contain the same strings. * @param {!(IArrayLike<string>|Array<string>)} a * @param {!(IArrayLike<string>|Array<string>)} b * @return {boolean} * @private */ compareStringArrays_(a, b) { if (a.length !== b.length) { return false; } const sortedA = (isArray(a) ? a : toArray(a)).sort(); const sortedB = (isArray(b) ? b : toArray(b)).sort(); for (let i = 0; i < a.length; i++) { if (sortedA[i] !== sortedB[i]) { return false; } } return true; } /** * Copies an object containing JSON data and returns it. * Returns null if input object contains invalid JSON (e.g. undefined or * circular references). * @param {?JsonObject|undefined} o * @return {?JsonObject} */ copyJsonObject_(o) { if (o === undefined) { return null; } try { return parseJson(JSON.stringify(o)); } catch (e) { dev().error(TAG, 'Failed to copy JSON (' + o + ') with error: ' + e); } return null; } /** * Print out the current state in the console. * @private */ printState_() { const seen = []; const s = JSON.stringify(this.state_, (key, value) => { if (isObject(value)) { if (seen.includes(value)) { return '[Circular]'; } else { seen.push(value); } } return value; }); user().info(TAG, s); } /** * Wait for bind scan to finish for testing. * * @return {?Promise} * @visibleForTesting */ initializePromiseForTesting() { return this.initializePromise_; } /** * Wait for bindings to evaluate and apply for testing. Should * be called once for each event that changes bindings. * * @return {?Promise} * @visibleForTesting */ setStatePromiseForTesting() { return this.setStatePromise_; } /** * @param {string} name * @private */ dispatchEventForTesting_(name) { if (getMode().test) { let event; if (typeof this.localWin_.Event === 'function') { event = new Event(name, {bubbles: true, cancelable: true}); } else { event = this.localWin_.document.createEvent('Event'); event.initEvent(name, /* bubbles */ true, /* cancelable */ true); } this.localWin_.dispatchEvent(event); } } }
/************************************************************************ * Library: Web 2.0 UI for jQuery (using prototypical inheritance) * - Following objects defined * - w2form - form widget * - $().w2form - jQuery wrapper * - Dependencies: jQuery, w2utils, w2fields, w2tabs, w2toolbar, w2alert * * == NICE TO HAVE == * - refresh(field) - would refresh only one field * - include delta on save * - form should read <select> <options> into items * - two way data bindings * - verify validation of fields * - added getChanges() - not complete * - nested record object * * == 1.5 changes * - $('#form').w2form() - if called w/o argument then it returns form object * - added onProgress * - added field.html.style (for the whole field) * - added enable/disable, show/hide * - added field.disabled, field.hidden * - when field is blank, set record.field = null * - action: { caption: 'Limpiar', style: '', class: '', onClick: function () {} } * - added ability to generate radio and select html in generateHTML() * ************************************************************************/ (function ($) { var w2form = function(options) { // public properties this.name = null; this.header = ''; this.box = null; // HTML element that hold this element this.url = ''; this.routeData = {}; // data for dynamic routes this.formURL = ''; // url where to get form HTML this.formHTML = ''; // form HTML (might be loaded from the url) this.page = 0; // current page this.recid = 0; // can be null or 0 this.fields = []; this.actions = {}; this.record = {}; this.original = {}; this.postData = {}; this.toolbar = {}; // if not empty, then it is toolbar this.tabs = {}; // if not empty, then it is tabs object this.style = ''; this.focus = 0; // focus first or other element // events this.onRequest = null; this.onLoad = null; this.onValidate = null; this.onSubmit = null; this.onProgress = null; this.onSave = null; this.onChange = null; this.onRender = null; this.onRefresh = null; this.onResize = null; this.onDestroy = null; this.onAction = null; this.onToolbar = null; this.onError = null; // internal this.isGenerated = false; this.last = { xhr: null // jquery xhr requests }; $.extend(true, this, w2obj.form, options); }; // ==================================================== // -- Registers as a jQuery plugin $.fn.w2form = function(method) { if ($.isPlainObject(method)) { var obj = this; // check name parameter if (!w2utils.checkName(method, 'w2form')) return; // remember items var record = method.record; var original = method.original; var fields = method.fields; var toolbar = method.toolbar; var tabs = method.tabs; // extend items var object = new w2form(method); $.extend(object, { record: {}, original: {}, fields: [], tabs: {}, toolbar: {}, handlers: [] }); if ($.isArray(tabs)) { $.extend(true, object.tabs, { tabs: [] }); for (var t = 0; t < tabs.length; t++) { var tmp = tabs[t]; if (typeof tmp === 'object') object.tabs.tabs.push(tmp); else object.tabs.tabs.push({ id: tmp, caption: tmp }); } } else { $.extend(true, object.tabs, tabs); } $.extend(true, object.toolbar, toolbar); // reassign variables if (fields) for (var p = 0; p < fields.length; p++) { var field = $.extend(true, {}, fields[p]); if (field.name == null && field.field != null) field.name = field.field; if (field.field == null && field.name != null) field.field = field.name; object.fields[p] = field; } for (var p in record) { // it is an object if ($.isPlainObject(record[p])) { object.record[p] = $.extend(true, {}, record[p]); } else { object.record[p] = record[p]; } } for (var p in original) { // it is an object if ($.isPlainObject(original[p])) { object.original[p] = $.extend(true, {}, original[p]); } else { object.original[p] = original[p]; } } if (obj.length > 0) object.box = obj[0]; // render if necessary if (object.formURL != '') { $.get(object.formURL, function (data) { // should always be $.get as it is template object.formHTML = data; object.isGenerated = true; if ($(object.box).length != 0 || data.length != 0) { $(object.box).html(data); object.render(object.box); } }); } else if (object.formHTML != '') { // it is already loaded into formHTML } else if ($(this).length != 0 && $.trim($(this).html()) != '') { object.formHTML = $(this).html(); } else { // try to generate it object.formHTML = object.generateHTML(); } // register new object w2ui[object.name] = object; // render if not loaded from url if (object.formURL == '') { if (String(object.formHTML).indexOf('w2ui-page') == -1) { object.formHTML = '<div class="w2ui-page page-0">'+ object.formHTML +'</div>'; } $(object.box).html(object.formHTML); object.isGenerated = true; object.render(object.box); } return object; } else { var obj = w2ui[$(this).attr('name')]; if (!obj) return null; if (arguments.length > 0) { if (obj[method]) obj[method].apply(obj, Array.prototype.slice.call(arguments, 1)); return this; } else { return obj; } } }; // ==================================================== // -- Implementation of core functionality w2form.prototype = { msgNotJSON : w2utils.lang('Return data is not in JSON format.'), msgAJAXerror : w2utils.lang('AJAX error. See console for more details.'), msgRefresh : w2utils.lang('Refreshing...'), msgSaving : w2utils.lang('Saving...'), get: function (field, returnIndex) { if (arguments.length === 0) { var all = []; for (var f1 = 0; f1 < this.fields.length; f1++) { if (this.fields[f1].name != null) all.push(this.fields[f1].name); } return all; } else { for (var f2 = 0; f2 < this.fields.length; f2++) { if (this.fields[f2].name == field) { if (returnIndex === true) return f2; else return this.fields[f2]; } } return null; } }, set: function (field, obj) { for (var f = 0; f < this.fields.length; f++) { if (this.fields[f].name == field) { $.extend(this.fields[f] , obj); this.refresh(); return true; } } return false; }, show: function () { var affected = 0; for (var a = 0; a < arguments.length; a++) { var fld = this.get(arguments[a]); if (fld && fld.hidden) { fld.hidden = false; affected++; } } if (affected > 0) this.refresh(); return affected; }, hide: function () { var affected = 0; for (var a = 0; a < arguments.length; a++) { var fld = this.get(arguments[a]); if (fld && !fld.hidden) { fld.hidden = true; affected++; } } if (affected > 0) this.refresh(); return affected; }, enable: function () { var affected = 0; for (var a = 0; a < arguments.length; a++) { var fld = this.get(arguments[a]); if (fld && fld.disabled) { fld.disabled = false; affected++; } } if (affected > 0) this.refresh(); return affected; }, disable: function () { var affected = 0; for (var a = 0; a < arguments.length; a++) { var fld = this.get(arguments[a]); if (fld && !fld.disabled) { fld.disabled = true; affected++; } } if (affected > 0) this.refresh(); return affected; }, reload: function (callBack) { var url = (typeof this.url != 'object' ? this.url : this.url.get); if (url && this.recid != 0 && this.recid != null) { // this.clear(); this.request(callBack); } else { // this.refresh(); // no need to refresh if (typeof callBack == 'function') callBack(); } }, clear: function () { this.recid = 0; this.record = {}; $().w2tag(); this.refresh(); }, error: function (msg) { var obj = this; // let the management of the error outside of the grid var eventData = this.trigger({ target: this.name, type: 'error', message: msg , xhr: this.last.xhr }); if (eventData.isCancelled === true) { if (typeof callBack == 'function') callBack(); return; } // need a time out because message might be already up) setTimeout(function () { w2alert(msg, w2utils.lang('Error')); }, 1); // event after this.trigger($.extend(eventData, { phase: 'after' })); }, validate: function (showErrors) { if (showErrors == null) showErrors = true; $().w2tag(); // hide all tags before validating // validate before saving var errors = []; for (var f = 0; f < this.fields.length; f++) { var field = this.fields[f]; if (this.record[field.name] == null) this.record[field.name] = ''; switch (field.type) { case 'int': if (this.record[field.name] && !w2utils.isInt(this.record[field.name])) { errors.push({ field: field, error: w2utils.lang('Not an integer') }); } break; case 'float': if (this.record[field.name] && !w2utils.isFloat(this.record[field.name])) { errors.push({ field: field, error: w2utils.lang('Not a float') }); } break; case 'money': if (this.record[field.name] && !w2utils.isMoney(this.record[field.name])) { errors.push({ field: field, error: w2utils.lang('Not in money format') }); } break; case 'color': case 'hex': if (this.record[field.name] && !w2utils.isHex(this.record[field.name])) { errors.push({ field: field, error: w2utils.lang('Not a hex number') }); } break; case 'email': if (this.record[field.name] && !w2utils.isEmail(this.record[field.name])) { errors.push({ field: field, error: w2utils.lang('Not a valid email') }); } break; case 'checkbox': // convert true/false if (this.record[field.name] == true) this.record[field.name] = 1; else this.record[field.name] = 0; break; case 'date': // format date before submit if (!field.options.format) field.options.format = w2utils.settings.date_format; if (this.record[field.name] && !w2utils.isDate(this.record[field.name], field.options.format)) { errors.push({ field: field, error: w2utils.lang('Not a valid date') + ': ' + field.options.format }); } else { } break; case 'list': case 'combo': break; case 'enum': break; } // === check required - if field is '0' it should be considered not empty var val = this.record[field.name]; if (field.required && (val === '' || ($.isArray(val) && val.length == 0) || ($.isPlainObject(val) && $.isEmptyObject(val)))) { errors.push({ field: field, error: w2utils.lang('Required field') }); } if (field.equalto && this.record[field.name] != this.record[field.equalto]) { errors.push({ field: field, error: w2utils.lang('Field should be equal to ') + field.equalto }); } } // event before var eventData = this.trigger({ phase: 'before', target: this.name, type: 'validate', errors: errors }); if (eventData.isCancelled === true) return; // show error if (showErrors) { for (var e = 0; e < eventData.errors.length; e++) { var err = eventData.errors[e]; if (err.field == null) continue; if (err.field.type == 'radio') { // for radio and checkboxes $($(err.field.el).parents('div')[0]).w2tag(err.error, { "class": 'w2ui-error' }); } else if (['enum', 'file'].indexOf(err.field.type) != -1) { (function (err) { setTimeout(function () { var fld = $(err.field.el).data('w2field').helpers.multi; $(err.field.el).w2tag(err.error); $(fld).addClass('w2ui-error'); }, 1); })(err); } else { $(err.field.el).w2tag(err.error, { "class": 'w2ui-error' }); } this.goto(errors[0].field.page); } } // event after this.trigger($.extend(eventData, { phase: 'after' })); return errors; }, getChanges: function () { var differ = function(record, original, result) { for (var i in record) { if (typeof record[i] == "object") { result[i] = differ(record[i], original[i] || {}, {}); if (!result[i] || $.isEmptyObject(result[i])) delete result[i]; } else if (record[i] != original[i]) { result[i] = record[i]; } } return result; }; return differ(this.record, this.original, {}); }, request: function (postData, callBack) { // if (1) param then it is call back if (2) then postData and callBack var obj = this; // check for multiple params if (typeof postData == 'function') { callBack = postData; postData = null; } if (postData == null) postData = {}; if (!this.url || (typeof this.url == 'object' && !this.url.get)) return; if (this.recid == null) this.recid = 0; // build parameters list var params = {}; // add list params params['cmd'] = 'get-record'; params['recid'] = this.recid; // append other params $.extend(params, this.postData); $.extend(params, postData); // event before var eventData = this.trigger({ phase: 'before', type: 'request', target: this.name, url: this.url, postData: params }); if (eventData.isCancelled === true) { if (typeof callBack == 'function') callBack({ status: 'error', message: 'Request aborted.' }); return; } // default action this.record = {}; this.original = {}; // call server to get data this.lock(this.msgRefresh); var url = eventData.url; if (typeof eventData.url == 'object' && eventData.url.get) url = eventData.url.get; if (this.last.xhr) try { this.last.xhr.abort(); } catch (e) {} // process url with routeData if (!$.isEmptyObject(obj.routeData)) { var info = w2utils.parseRoute(url); if (info.keys.length > 0) { for (var k = 0; k < info.keys.length; k++) { if (obj.routeData[info.keys[k].name] == null) continue; url = url.replace((new RegExp(':'+ info.keys[k].name, 'g')), obj.routeData[info.keys[k].name]); } } } var ajaxOptions = { type : 'POST', url : url, data : eventData.postData, dataType : 'text' // expected from server }; if (w2utils.settings.dataType == 'HTTP') { ajaxOptions.data = String($.param(ajaxOptions.data, false)).replace(/%5B/g, '[').replace(/%5D/g, ']'); } if (w2utils.settings.dataType == 'RESTFULL') { ajaxOptions.type = 'GET'; ajaxOptions.data = String($.param(ajaxOptions.data, false)).replace(/%5B/g, '[').replace(/%5D/g, ']'); } if (w2utils.settings.dataType == 'RESTFULLJSON') { ajaxOptions.type = 'GET'; ajaxOptions.data = JSON.stringify(ajaxOptions.data); ajaxOptions.contentType = 'application/json'; } if (w2utils.settings.dataType == 'JSON') { ajaxOptions.type = 'POST'; ajaxOptions.data = JSON.stringify(ajaxOptions.data); ajaxOptions.contentType = 'application/json'; } this.last.xhr = $.ajax(ajaxOptions) .done(function (data, status, xhr) { obj.unlock(); // event before var eventData = obj.trigger({ phase: 'before', target: obj.name, type: 'load', xhr: xhr }); if (eventData.isCancelled === true) { if (typeof callBack == 'function') callBack({ status: 'error', message: 'Request aborted.' }); return; } // parse server response var data; var responseText = obj.last.xhr.responseText; if (status != 'error') { // default action if (responseText != null && responseText != '') { // check if the onLoad handler has not already parsed the data if (typeof responseText == "object") { data = responseText; } else { // $.parseJSON or $.getJSON did not work because those expect perfect JSON data - where everything is in double quotes // // TODO: avoid (potentially malicious) code injection from the response. try { eval('data = '+ responseText); } catch (e) { } } if (data == null) { data = { status : 'error', message : obj.msgNotJSON, responseText : responseText } } if (data['status'] == 'error') { obj.error(data['message']); } else { obj.record = $.extend({}, data.record); obj.original = $.extend({}, data.record); } } } else { obj.error('AJAX Error ' + xhr.status + ': '+ xhr.statusText); data = { status : 'error', message : obj.msgAJAXerror, responseText : responseText }; } // event after obj.trigger($.extend(eventData, { phase: 'after' })); obj.refresh(); // call back if (typeof callBack == 'function') callBack(data); }) .fail(function (xhr, status, error) { // trigger event var errorObj = { status: status, error: error, rawResponseText: xhr.responseText }; var eventData2 = obj.trigger({ phase: 'before', type: 'error', error: errorObj, xhr: xhr }); if (eventData2.isCancelled === true) return; // default behavior if (status != 'abort') { var data; try { data = $.parseJSON(xhr.responseText) } catch (e) {} console.log('ERROR: Server communication failed.', '\n EXPECTED:', { status: 'success', items: [{ id: 1, text: 'item' }] }, '\n OR:', { status: 'error', message: 'error message' }, '\n RECEIVED:', typeof data == 'object' ? data : xhr.responseText); } // event after obj.trigger($.extend(eventData2, { phase: 'after' })); }); // event after this.trigger($.extend(eventData, { phase: 'after' })); }, submit: function (postData, callBack) { return this.save(postData, callBack); }, save: function (postData, callBack) { var obj = this; $(this.box).find(':focus').change(); // trigger onchange // check for multiple params if (typeof postData == 'function') { callBack = postData; postData = null; } // validation var errors = obj.validate(true); if (errors.length !== 0) return; // submit save if (postData == null) postData = {}; if (!obj.url || (typeof obj.url == 'object' && !obj.url.save)) { console.log("ERROR: Form cannot be saved because no url is defined."); return; } obj.lock(obj.msgSaving + ' <span id="'+ obj.name +'_progress"></span>'); // need timer to allow to lock setTimeout(function () { // build parameters list var params = {}; // add list params params['cmd'] = 'save-record'; params['recid'] = obj.recid; // append other params $.extend(params, obj.postData); $.extend(params, postData); params.record = $.extend(true, {}, obj.record); // event before var eventData = obj.trigger({ phase: 'before', type: 'submit', target: obj.name, url: obj.url, postData: params }); if (eventData.isCancelled === true) return; // default action var url = eventData.url; if (typeof eventData.url == 'object' && eventData.url.save) url = eventData.url.save; if (obj.last.xhr) try { obj.last.xhr.abort(); } catch (e) {} // process url with routeData if (!$.isEmptyObject(obj.routeData)) { var info = w2utils.parseRoute(url); if (info.keys.length > 0) { for (var k = 0; k < info.keys.length; k++) { if (obj.routeData[info.keys[k].name] == null) continue; url = url.replace((new RegExp(':'+ info.keys[k].name, 'g')), obj.routeData[info.keys[k].name]); } } } var ajaxOptions = { type : 'POST', url : url, data : eventData.postData, dataType : 'text', // expected from server xhr : function() { var xhr = new window.XMLHttpRequest(); // upload xhr.upload.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var eventData3 = obj.trigger({ phase: 'before', type: 'progress', total: evt.total, loaded: evt.loaded, originalEvent: evt }); if (eventData3.isCancelled === true) return; // default behavior var percent = Math.round(evt.loaded / evt.total * 100); $('#'+ obj.name + '_progress').text(''+ percent + '%'); // event after obj.trigger($.extend(eventData3, { phase: 'after' })); } }, false); return xhr; } }; if (w2utils.settings.dataType == 'HTTP') { ajaxOptions.data = String($.param(ajaxOptions.data, false)).replace(/%5B/g, '[').replace(/%5D/g, ']'); } if (w2utils.settings.dataType == 'RESTFULL') { if (obj.recid != 0 && obj.recid != null) ajaxOptions.type = 'PUT'; ajaxOptions.data = String($.param(ajaxOptions.data, false)).replace(/%5B/g, '[').replace(/%5D/g, ']'); } if (w2utils.settings.dataType == 'RESTFULLJSON') { if (obj.recid != 0 && obj.recid != null) ajaxOptions.type = 'PUT'; ajaxOptions.data = JSON.stringify(ajaxOptions.data); ajaxOptions.contentType = 'application/json'; } if (w2utils.settings.dataType == 'JSON') { ajaxOptions.type = 'POST'; ajaxOptions.data = JSON.stringify(ajaxOptions.data); ajaxOptions.contentType = 'application/json'; } obj.last.xhr = $.ajax(ajaxOptions) .done(function (data, status, xhr) { obj.unlock(); // event before var eventData = obj.trigger({ phase: 'before', target: obj.name, type: 'save', xhr: xhr, status: status }); if (eventData.isCancelled === true) return; // parse server response var data; var responseText = xhr.responseText; if (status != 'error') { // default action if (responseText != null && responseText != '') { // check if the onLoad handler has not already parsed the data if (typeof responseText == "object") { data = responseText; } else { // $.parseJSON or $.getJSON did not work because those expect perfect JSON data - where everything is in double quotes // // TODO: avoid (potentially malicious) code injection from the response. try { eval('data = '+ responseText); } catch (e) { } } if (data == null) { data = { status : 'error', message : obj.msgNotJSON, responseText : responseText } } if (data['status'] == 'error') { obj.error(data['message']); } else { obj.original = $.extend({}, obj.record); } } } else { obj.error('AJAX Error ' + xhr.status + ': '+ xhr.statusText); data = { status : 'error', message : obj.msgAJAXerror, responseText : responseText }; } // event after obj.trigger($.extend(eventData, { phase: 'after' })); obj.refresh(); // call back if (data.status == 'success' && typeof callBack == 'function') callBack(data); }) .fail(function (xhr, status, error) { // trigger event var errorObj = { status: status, error: error, rawResponseText: xhr.responseText }; var eventData2 = obj.trigger({ phase: 'before', type: 'error', error: errorObj, xhr: xhr }); if (eventData2.isCancelled === true) return; // default behavior console.log('ERROR: server communication failed. The server should return', { status: 'success' }, 'OR', { status: 'error', message: 'error message' }, ', instead the AJAX request produced this: ', errorObj); // event after obj.trigger($.extend(eventData2, { phase: 'after' })); }); // event after obj.trigger($.extend(eventData, { phase: 'after' })); }, 50); }, lock: function (msg, showSpinner) { var args = Array.prototype.slice.call(arguments, 0); args.unshift(this.box); setTimeout(function () { w2utils.lock.apply(window, args); }, 10); }, unlock: function (speed) { var box = this.box; setTimeout(function () { w2utils.unlock(box, speed); }, 25); // needed timer so if server fast, it will not flash }, goto: function (page) { if (page != null) this.page = page; // if it was auto size, resize it if ($(this.box).data('auto-size') === true) $(this.box).height(0); this.refresh(); }, generateHTML: function () { var pages = []; // array for each page var group = ''; var page; for (var f = 0; f < this.fields.length; f++) { var html = ''; var field = this.fields[f]; if (field.html == null) field.html = {}; if (field.options == null) field.options = {}; field.html = $.extend(true, { caption: '', span: 6, attr: '', text: '', style: '', page: 0 }, field.html); if (page == null) page = field.html.page; if (field.html.caption == '') field.html.caption = field.name; // input control var input = '<input name="'+ field.name +'" class="w2ui-input" type="text" '+ field.html.attr +'/>'; switch (field.type) { case 'pass': case 'password': input = '<input name="' + field.name + '" class="w2ui-input" type = "password" ' + field.html.attr + '/>'; break; case 'checkbox': input = '<input name="'+ field.name +'" class="w2ui-input" type="checkbox" '+ field.html.attr +'/>'; break; case 'radio': input = ''; // normalized options var items = field.options.items ? field.options.items : field.html.items; if (!$.isArray(items)) items = []; if (items.length > 0) { items = w2obj.field.prototype.normMenu(items); } // generate for (var i = 0; i < items.length; i++) { input += '<label><input name="' + field.name + '" class="w2ui-input" type = "radio" ' + field.html.attr + ' value="'+ items[i].id + '"/>' + '&#160;' + items[i].text + '</label><br/>'; } break; case 'select': input = '<select name="' + field.name + '" class="w2ui-input" ' + field.html.attr + '>'; // normalized options var items = field.options.items ? field.options.items : field.html.items; if (!$.isArray(items)) items = []; if (items.length > 0) { items = w2obj.field.prototype.normMenu(items); } // generate for (var i = 0; i < items.length; i++) { input += '<option value="'+ items[i].id + '">' + items[i].text + '</option>'; } input += '</select>'; break; case 'textarea': input = '<textarea name="'+ field.name +'" class="w2ui-input" '+ field.html.attr +'></textarea>'; break; case 'toggle': input = '<input name="'+ field.name +'" type="checkbox" '+ field.html.attr +' class="w2ui-input w2ui-toggle"/><div><div></div></div>'; break; } if (field.html.group) { if (group != '') html += '\n </div>'; html += '\n <div class="w2ui-group-title">'+ field.html.group + '</div>\n <div class="w2ui-group">'; group = field.html.group; } if (field.html.page != page && group != '') { pages[pages.length-1] += '\n </div>'; group = ''; } html += '\n <div class="w2ui-field '+ (field.html.span != null ? 'w2ui-span'+ field.html.span : '') +'" style="'+ field.html.style +'">'+ '\n <label>' + w2utils.lang(field.html.caption) +'</label>'+ '\n <div>'+ input + w2utils.lang(field.html.text) + '</div>'+ '\n </div>'; if (pages[field.html.page] == null) pages[field.html.page] = ''; pages[field.html.page] += html; page = field.html.page; } if (group != '') pages[pages.length-1] += '\n </div>'; if (this.tabs.tabs) { for (var i = 0; i < this.tabs.tabs.length; i++) if (pages[i] == null) pages[i] = ''; } for (var p = 0; p < pages.length; p++) pages[p] = '<div class="w2ui-page page-'+ p +'">' + pages[p] + '\n</div>'; // buttons if any var buttons = ''; if (!$.isEmptyObject(this.actions)) { var addClass = ''; buttons += '\n<div class="w2ui-buttons">'; for (var a in this.actions) { // it is an object var act = this.actions[a]; var info = { caption: '', style: '', "class": '' }; if ($.isPlainObject(act)) { if (act.caption) info.caption = act.caption; if (act.style) info.style = act.style; if (act["class"]) info['class'] = act['class']; } else { info.caption = a; if (['save', 'update', 'create'].indexOf(a.toLowerCase()) != -1) info['class'] = 'w2ui-btn-blue'; else info['class'] = ''; } buttons += '\n <button name="'+ a +'" class="w2ui-btn '+ info['class'] +'" style="'+ info.style +'">'+ w2utils.lang(info.caption) +'</button>'; } buttons += '\n</div>'; } return pages.join('') + buttons; }, action: function (action, event) { var click = null; var act = this.actions[action]; var click = act; if ($.isPlainObject(act) && act.onClick) click = act.onClick; // event before var eventData = this.trigger({ phase: 'before', target: action, type: 'action', click: click, originalEvent: event }); if (eventData.isCancelled === true) return; // default actions if (typeof click == 'function') click.call(this, event); // event after this.trigger($.extend(eventData, { phase: 'after' })); }, resize: function () { var obj = this; // event before var eventData = this.trigger({ phase: 'before', target: this.name, type: 'resize' }); if (eventData.isCancelled === true) return; // default behaviour var main = $(this.box).find('> div:not(.w2ui-lock-msg)'); var header = $(this.box).find('> div .w2ui-form-header'); var toolbar = $(this.box).find('> div .w2ui-form-toolbar'); var tabs = $(this.box).find('> div .w2ui-form-tabs'); var page = $(this.box).find('> div .w2ui-page'); var cpage = $(this.box).find('> div .w2ui-page.page-'+ this.page); var dpage = $(this.box).find('> div .w2ui-page.page-'+ this.page + ' > div'); var buttons = $(this.box).find('> div .w2ui-buttons'); // if no height, calculate it resizeElements(); if (parseInt($(this.box).height()) == 0 || $(this.box).data('auto-size') === true) { $(this.box).height( (header.length > 0 ? w2utils.getSize(header, 'height') : 0) + ((typeof this.tabs === 'object' && $.isArray(this.tabs.tabs) && this.tabs.tabs.length > 0) ? w2utils.getSize(tabs, 'height') : 0) + ((typeof this.toolbar == 'object' && $.isArray(this.toolbar.items) && this.toolbar.items.length > 0) ? w2utils.getSize(toolbar, 'height') : 0) + (page.length > 0 ? w2utils.getSize(dpage, 'height') + w2utils.getSize(cpage, '+height') + 12 : 0) + // why 12 ??? (buttons.length > 0 ? w2utils.getSize(buttons, 'height') : 0) ); $(this.box).data('auto-size', true); } resizeElements(); // event after obj.trigger($.extend(eventData, { phase: 'after' })); function resizeElements() { // resize elements main.width($(obj.box).width()).height($(obj.box).height()); toolbar.css('top', (obj.header != '' ? w2utils.getSize(header, 'height') : 0)); tabs.css('top', (obj.header != '' ? w2utils.getSize(header, 'height') : 0) + ((typeof obj.toolbar == 'object' && $.isArray(obj.toolbar.items) && obj.toolbar.items.length > 0) ? w2utils.getSize(toolbar, 'height') : 0)); page.css('top', (obj.header != '' ? w2utils.getSize(header, 'height') : 0) + ((typeof obj.toolbar == 'object' && $.isArray(obj.toolbar.items) && obj.toolbar.items.length > 0) ? w2utils.getSize(toolbar, 'height') + 5 : 0) + ((typeof obj.tabs === 'object' && $.isArray(obj.tabs.tabs) && obj.tabs.tabs.length > 0) ? w2utils.getSize(tabs, 'height') + 5 : 0)); page.css('bottom', (buttons.length > 0 ? w2utils.getSize(buttons, 'height') : 0)); } }, refresh: function () { var time = (new Date()).getTime(); var obj = this; if (!this.box) return; if (!this.isGenerated || $(this.box).html() == null) return; // update what page field belongs $(this.box).find('input, textarea, select').each(function (index, el) { var name = ($(el).attr('name') != null ? $(el).attr('name') : $(el).attr('id')); var field = obj.get(name); if (field) { // find page var div = $(el).parents('.w2ui-page'); if (div.length > 0) { for (var i = 0; i < 100; i++) { if (div.hasClass('page-'+i)) { field.page = i; break; } } } } }); // event before var eventData = this.trigger({ phase: 'before', target: this.name, type: 'refresh', page: this.page }) if (eventData.isCancelled === true) return; // default action $(this.box).find('.w2ui-page').hide(); $(this.box).find('.w2ui-page.page-' + this.page).show(); $(this.box).find('.w2ui-form-header').html(this.header); // refresh tabs if needed if (typeof this.tabs === 'object' && $.isArray(this.tabs.tabs) && this.tabs.tabs.length > 0) { $('#form_'+ this.name +'_tabs').show(); this.tabs.active = this.tabs.tabs[this.page].id; this.tabs.refresh(); } else { $('#form_'+ this.name +'_tabs').hide(); } // refresh tabs if needed if (typeof this.toolbar == 'object' && $.isArray(this.toolbar.items) && this.toolbar.items.length > 0) { $('#form_'+ this.name +'_toolbar').show(); this.toolbar.refresh(); } else { $('#form_'+ this.name +'_toolbar').hide(); } // refresh values of all fields for (var f = 0; f < this.fields.length; f++) { var field = this.fields[f]; if (field.name == null && field.field != null) field.name = field.field; if (field.field == null && field.name != null) field.field = field.name; field.$el = $(this.box).find('[name="'+ String(field.name).replace(/\\/g, '\\\\') +'"]'); field.el = field.$el[0]; if (field.el == null) { console.log('ERROR: Cannot associate field "'+ field.name + '" with html control. Make sure html control exists with the same name.'); //return; } if (field.el) field.el.id = field.name; var tmp = $(field).data('w2field'); if (tmp) tmp.clear(); $(field.$el).off('change').on('change', function () { var value_new = this.value; var value_previous = obj.record[this.name] ? obj.record[this.name] : ''; var field = obj.get(this.name); if (['list', 'enum', 'file'].indexOf(field.type) != -1 && $(this).data('selected')) { var nv = $(this).data('selected'); var cv = obj.record[this.name]; if ($.isArray(nv)) { value_new = []; for (var i = 0; i < nv.length; i++) value_new[i] = $.extend(true, {}, nv[i]); // clone array } if ($.isPlainObject(nv)) { value_new = $.extend(true, {}, nv); // clone object } if ($.isArray(cv)) { value_previous = []; for (var i = 0; i < cv.length; i++) value_previous[i] = $.extend(true, {}, cv[i]); // clone array } if ($.isPlainObject(cv)) { value_previous = $.extend(true, {}, cv); // clone object } } if (['toggle', 'checkbox'].indexOf(field.type) != -1) { value_new = ($(this).prop('checked') ? ($(this).prop('value') == 'on' ? true : $(this).prop('value')) : false); } // clean extra chars if (['int', 'float', 'percent', 'money', 'currency'].indexOf(field.type) != -1) { value_new = $(this).data('w2field').clean(value_new); } if (value_new === value_previous) return; // event before var eventData = obj.trigger({ phase: 'before', target: this.name, type: 'change', value_new: value_new, value_previous: value_previous }); if (eventData.isCancelled === true) { $(this).val(obj.record[this.name]); // return previous value return; } // default action var val = this.value; if (this.type == 'select') val = this.value; if (this.type == 'checkbox') val = this.checked ? true : false; if (this.type == 'radio') { field.$el.each(function (index, el) { if (el.checked) val = el.value; }); } if (['int', 'float', 'percent', 'money', 'currency', 'list', 'combo', 'enum', 'file', 'toggle'].indexOf(field.type) != -1) { val = value_new; } if (['enum', 'file'].indexOf(field.type) != -1) { if (val.length > 0) { var fld = $(field.el).data('w2field').helpers.multi; $(fld).removeClass('w2ui-error'); } } if (val === '' || val == null || ($.isArray(val) && val.length == 0) || ($.isPlainObject(val) && $.isEmptyObject(val))) { val = null; } obj.record[this.name] = val; // event after obj.trigger($.extend(eventData, { phase: 'after' })); }); // required if (field.required) { $(field.el).parent().parent().addClass('w2ui-required'); } else { $(field.el).parent().parent().removeClass('w2ui-required'); } // disabled if (field.disabled != null) { if (field.disabled) { $(field.el).prop('readonly', true); } else { $(field.el).prop('readonly', false); } } // hidden if (field.hidden) { $(field.el).parent().parent().hide(); } else { $(field.el).parent().parent().show(); } } // attach actions on buttons $(this.box).find('button, input[type=button]').each(function (index, el) { $(el).off('click').on('click', function (event) { var action = this.value; if (this.id) action = this.id; if (this.name) action = this.name; obj.action(action, event); }); }); // init controls with record for (var f = 0; f < this.fields.length; f++) { var field = this.fields[f]; var value = (this.record[field.name] != null ? this.record[field.name] : ''); if (!field.el) continue; field.type = String(field.type).toLowerCase(); if (!field.options) field.options = {}; switch (field.type) { case 'text': case 'textarea': case 'email': case 'pass': case 'password': field.el.value = value; break; case 'int': case 'float': case 'money': case 'currency': case 'percent': // issue #761 field.el.value = value; $(field.el).w2field($.extend({}, field.options, { type: field.type })); break; case 'hex': case 'alphanumeric': case 'color': case 'date': case 'time': field.el.value = value; $(field.el).w2field($.extend({}, field.options, { type: field.type })); break; case 'toggle': if (w2utils.isFloat(value)) value = parseFloat(value); $(field.el).prop('checked', (value ? true : false)); this.record[field.name] = (value ? value : false); break; // enums case 'list': case 'combo': if (field.type == 'list') { var tmp_value = ($.isPlainObject(value) ? value.id : ($.isPlainObject(field.options.selected) ? field.options.selected.id : value)); // normalized options if (!field.options.items) field.options.items = []; var items = field.options.items; if ($.isArray(items) && items.length > 0 && !$.isPlainObject(items[0])) { field.options.items = w2obj.field.prototype.normMenu(items); } // find value from items for (var i = 0; i < field.options.items.length; i++) { var item = field.options.items[i]; if (item.id == tmp_value) { value = $.extend(true, {}, item); obj.record[field.name] = value; break; } } } else if (field.type == 'combo' && !$.isPlainObject(value)) { field.el.value = value; } else if ($.isPlainObject(value) && value.text != null) { field.el.value = value.text; } else { field.el.value = ''; } if (!$.isPlainObject(value)) value = {}; $(field.el).w2field($.extend({}, field.options, { type: field.type, selected: value })); break; case 'enum': case 'file': if (!$.isArray(value)) value = []; $(field.el).w2field($.extend({}, field.options, { type: field.type, selected: value })); break; // standard HTML case 'select': // generate options var items = field.options.items; if (items != null && items.length > 0) { items = w2obj.field.prototype.normMenu(items); $(field.el).html(''); for (var it = 0; it < items.length; it++) { $(field.el).append('<option value="'+ items[it].id +'">' + items[it].text + '</option'); } } $(field.el).val(value); break; case 'radio': $(field.$el).prop('checked', false).each(function (index, el) { if ($(el).val() == value) $(el).prop('checked', true); }); break; case 'checkbox': $(field.el).prop('checked', value ? true : false); break; default: $(field.el).val(value); $(field.el).w2field($.extend({}, field.options, { type: field.type })); break; } } // wrap pages in div var tmp = $(this.box).find('.w2ui-page'); for (var i = 0; i < tmp.length; i++) { if ($(tmp[i]).find('> *').length > 1) $(tmp[i]).wrapInner('<div></div>'); } // event after this.trigger($.extend(eventData, { phase: 'after' })); this.resize(); return (new Date()).getTime() - time; }, render: function (box) { var time = (new Date()).getTime(); var obj = this; if (typeof box == 'object') { // remove from previous box if ($(this.box).find('#form_'+ this.name +'_tabs').length > 0) { $(this.box).removeAttr('name') .removeClass('w2ui-reset w2ui-form') .html(''); } this.box = box; } if (!this.isGenerated) return; if (!this.box) return; // event before var eventData = this.trigger({ phase: 'before', target: this.name, type: 'render', box: (box != null ? box : this.box) }); if (eventData.isCancelled === true) return; // default actions if ($.isEmptyObject(this.original) && !$.isEmptyObject(this.record)) { this.original = $.extend(true, {}, this.record); } var html = '<div>' + (this.header != '' ? '<div class="w2ui-form-header">' + this.header + '</div>' : '') + ' <div id="form_'+ this.name +'_toolbar" class="w2ui-form-toolbar" style="display: none"></div>' + ' <div id="form_'+ this.name +'_tabs" class="w2ui-form-tabs" style="display: none"></div>' + this.formHTML + '</div>'; $(this.box).attr('name', this.name) .addClass('w2ui-reset w2ui-form') .html(html); if ($(this.box).length > 0) $(this.box)[0].style.cssText += this.style; // init toolbar regardless it is defined or not if (typeof this.toolbar.render !== 'function') { this.toolbar = $().w2toolbar($.extend({}, this.toolbar, { name: this.name +'_toolbar', owner: this })); this.toolbar.on('click', function (event) { var eventData = obj.trigger({ phase: 'before', type: 'toolbar', target: event.target, originalEvent: event }); if (eventData.isCancelled === true) return; // no default action obj.trigger($.extend(eventData, { phase: 'after' })); }); } if (typeof this.toolbar == 'object' && typeof this.toolbar.render == 'function') { this.toolbar.render($('#form_'+ this.name +'_toolbar')[0]); } // init tabs regardless it is defined or not if (typeof this.tabs.render !== 'function') { this.tabs = $().w2tabs($.extend({}, this.tabs, { name: this.name +'_tabs', owner: this })); this.tabs.on('click', function (event) { obj.goto(this.get(event.target, true)); }); } if (typeof this.tabs == 'object' && typeof this.tabs.render == 'function') { this.tabs.render($('#form_'+ this.name +'_tabs')[0]); } // event after this.trigger($.extend(eventData, { phase: 'after' })); // after render actions this.resize(); var url = (typeof this.url != 'object' ? this.url : this.url.get); if (url && this.recid != 0 && this.recid != null) { this.request(); } else { this.refresh(); } // attach to resize event if ($('.w2ui-layout').length == 0) { // if there is layout, it will send a resize event this.tmp_resize = function (event) { w2ui[obj.name].resize(); }; $(window).off('resize', 'body').on('resize', 'body', this.tmp_resize); } setTimeout(function () { obj.resize(); obj.refresh(); }, 150); // need timer because resize is on timer // focus on load function focusEl() { var inputs = $(obj.box).find('input, select, textarea'); if (inputs.length > obj.focus) inputs[obj.focus].focus(); } if (this.focus >= 0) setTimeout(focusEl, 500); // need timeout to allow form to render return (new Date()).getTime() - time; }, destroy: function () { // event before var eventData = this.trigger({ phase: 'before', target: this.name, type: 'destroy' }); if (eventData.isCancelled === true) return; // clean up if (typeof this.toolbar == 'object' && this.toolbar.destroy) this.toolbar.destroy(); if (typeof this.tabs == 'object' && this.tabs.destroy) this.tabs.destroy(); if ($(this.box).find('#form_'+ this.name +'_tabs').length > 0) { $(this.box) .removeAttr('name') .removeClass('w2ui-reset w2ui-form') .html(''); } delete w2ui[this.name]; // event after this.trigger($.extend(eventData, { phase: 'after' })); $(window).off('resize', 'body') } }; $.extend(w2form.prototype, w2utils.event); w2obj.form = w2form; })(jQuery);
// The Font object import Path from './path'; import sfnt from './tables/sfnt'; import { DefaultEncoding } from './encoding'; import glyphset from './glyphset'; import Substitution from './substitution'; import { isBrowser, checkArgument, arrayBufferToNodeBuffer } from './util'; import HintingTrueType from './hintingtt'; /** * @typedef FontOptions * @type Object * @property {Boolean} empty - whether to create a new empty font * @property {string} familyName * @property {string} styleName * @property {string=} fullName * @property {string=} postScriptName * @property {string=} designer * @property {string=} designerURL * @property {string=} manufacturer * @property {string=} manufacturerURL * @property {string=} license * @property {string=} licenseURL * @property {string=} version * @property {string=} description * @property {string=} copyright * @property {string=} trademark * @property {Number} unitsPerEm * @property {Number} ascender * @property {Number} descender * @property {Number} createdTimestamp * @property {string=} weightClass * @property {string=} widthClass * @property {string=} fsSelection */ /** * A Font represents a loaded OpenType font file. * It contains a set of glyphs and methods to draw text on a drawing context, * or to get a path representing the text. * @exports opentype.Font * @class * @param {FontOptions} * @constructor */ function Font(options) { options = options || {}; if (!options.empty) { // Check that we've provided the minimum set of names. checkArgument(options.familyName, 'When creating a new Font object, familyName is required.'); checkArgument(options.styleName, 'When creating a new Font object, styleName is required.'); checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.'); checkArgument(options.ascender, 'When creating a new Font object, ascender is required.'); checkArgument(options.descender, 'When creating a new Font object, descender is required.'); checkArgument(options.descender < 0, 'Descender should be negative (e.g. -512).'); // OS X will complain if the names are empty, so we put a single space everywhere by default. this.names = { fontFamily: {en: options.familyName || ' '}, fontSubfamily: {en: options.styleName || ' '}, fullName: {en: options.fullName || options.familyName + ' ' + options.styleName}, postScriptName: {en: options.postScriptName || options.familyName + options.styleName}, designer: {en: options.designer || ' '}, designerURL: {en: options.designerURL || ' '}, manufacturer: {en: options.manufacturer || ' '}, manufacturerURL: {en: options.manufacturerURL || ' '}, license: {en: options.license || ' '}, licenseURL: {en: options.licenseURL || ' '}, version: {en: options.version || 'Version 0.1'}, description: {en: options.description || ' '}, copyright: {en: options.copyright || ' '}, trademark: {en: options.trademark || ' '} }; this.unitsPerEm = options.unitsPerEm || 1000; this.ascender = options.ascender; this.descender = options.descender; this.createdTimestamp = options.createdTimestamp; this.tables = { os2: { usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR } }; } this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported. this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); this.encoding = new DefaultEncoding(this); this.substitution = new Substitution(this); this.tables = this.tables || {}; Object.defineProperty(this, 'hinting', { get: function() { if (this._hinting) return this._hinting; if (this.outlinesFormat === 'truetype') { return (this._hinting = new HintingTrueType(this)); } } }); } /** * Check if the font has a glyph for the given character. * @param {string} * @return {Boolean} */ Font.prototype.hasChar = function(c) { return this.encoding.charToGlyphIndex(c) !== null; }; /** * Convert the given character to a single glyph index. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {Number} */ Font.prototype.charToGlyphIndex = function(s) { return this.encoding.charToGlyphIndex(s); }; /** * Convert the given character to a single Glyph object. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {opentype.Glyph} */ Font.prototype.charToGlyph = function(c) { const glyphIndex = this.charToGlyphIndex(c); let glyph = this.glyphs.get(glyphIndex); if (!glyph) { // .notdef glyph = this.glyphs.get(0); } return glyph; }; /** * Convert the given text to a list of Glyph objects. * Note that there is no strict one-to-one mapping between characters and * glyphs, so the list of returned glyphs can be larger or smaller than the * length of the given string. * @param {string} * @param {GlyphRenderOptions} [options] * @return {opentype.Glyph[]} */ Font.prototype.stringToGlyphs = function(s, options) { options = options || this.defaultRenderOptions; // Get glyph indexes const indexes = []; for (let i = 0; i < s.length; i += 1) { const c = s[i]; indexes.push(this.charToGlyphIndex(c)); } let length = indexes.length; // Apply substitutions on glyph indexes if (options.features) { const script = options.script || this.substitution.getDefaultScriptName(); let manyToOne = []; if (options.features.liga) manyToOne = manyToOne.concat(this.substitution.getFeature('liga', script, options.language)); if (options.features.rlig) manyToOne = manyToOne.concat(this.substitution.getFeature('rlig', script, options.language)); for (let i = 0; i < length; i += 1) { for (let j = 0; j < manyToOne.length; j++) { const ligature = manyToOne[j]; const components = ligature.sub; const compCount = components.length; let k = 0; while (k < compCount && components[k] === indexes[i + k]) k++; if (k === compCount) { indexes.splice(i, compCount, ligature.by); length = length - compCount + 1; } } } } // convert glyph indexes to glyph objects const glyphs = new Array(length); const notdef = this.glyphs.get(0); for (let i = 0; i < length; i += 1) { glyphs[i] = this.glyphs.get(indexes[i]) || notdef; } return glyphs; }; /** * @param {string} * @return {Number} */ Font.prototype.nameToGlyphIndex = function(name) { return this.glyphNames.nameToGlyphIndex(name); }; /** * @param {string} * @return {opentype.Glyph} */ Font.prototype.nameToGlyph = function(name) { const glyphIndex = this.nameToGlyphIndex(name); let glyph = this.glyphs.get(glyphIndex); if (!glyph) { // .notdef glyph = this.glyphs.get(0); } return glyph; }; /** * @param {Number} * @return {String} */ Font.prototype.glyphIndexToName = function(gid) { if (!this.glyphNames.glyphIndexToName) { return ''; } return this.glyphNames.glyphIndexToName(gid); }; /** * Retrieve the value of the kerning pair between the left glyph (or its index) * and the right glyph (or its index). If no kerning pair is found, return 0. * The kerning value gets added to the advance width when calculating the spacing * between glyphs. * @param {opentype.Glyph} leftGlyph * @param {opentype.Glyph} rightGlyph * @return {Number} */ Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { leftGlyph = leftGlyph.index || leftGlyph; rightGlyph = rightGlyph.index || rightGlyph; const gposKerning = this.getGposKerningValue; return gposKerning ? gposKerning(leftGlyph, rightGlyph) : (this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0); }; /** * @typedef GlyphRenderOptions * @type Object * @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used. * See https://www.microsoft.com/typography/otspec/scripttags.htm * @property {string} [language='dflt'] - language system used to determine which features to apply. * See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx * @property {boolean} [kerning=true] - whether to include kerning values * @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system. * See https://www.microsoft.com/typography/otspec/featuretags.htm */ Font.prototype.defaultRenderOptions = { kerning: true, features: { liga: true, rlig: true } }; /** * Helper function that invokes the given callback for each glyph in the given text. * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text * @param {string} text - The text to apply. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @param {Function} callback */ Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) { x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 72; options = options || this.defaultRenderOptions; const fontScale = 1 / this.unitsPerEm * fontSize; const glyphs = this.stringToGlyphs(text, options); for (let i = 0; i < glyphs.length; i += 1) { const glyph = glyphs[i]; callback.call(this, glyph, x, y, fontSize, options); if (glyph.advanceWidth) { x += glyph.advanceWidth * fontScale; } if (options.kerning && i < glyphs.length - 1) { const kerningValue = this.getKerningValue(glyph, glyphs[i + 1]); x += kerningValue * fontScale; } if (options.letterSpacing) { x += options.letterSpacing * fontSize; } else if (options.tracking) { x += (options.tracking / 1000) * fontSize; } } return x; }; /** * Create a Path object that represents the given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path} */ Font.prototype.getPath = function(text, x, y, fontSize, options) { const fullPath = new Path(); this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { const glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); fullPath.extend(glyphPath); }); return fullPath; }; /** * Create an array of Path objects that represent the glyphs of a given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path[]} */ Font.prototype.getPaths = function(text, x, y, fontSize, options) { const glyphPaths = []; this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { const glyphPath = glyph.getPath(gX, gY, gFontSize); glyphPaths.push(glyphPath); }); return glyphPaths; }; /** * Returns the advance width of a text. * * This is something different than Path.getBoundingBox() as for example a * suffixed whitespace increases the advanceWidth but not the bounding box * or an overhanging letter like a calligraphic 'f' might have a quite larger * bounding box than its advance width. * * This corresponds to canvas2dContext.measureText(text).width * * @param {string} text - The text to create. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return advance width */ Font.prototype.getAdvanceWidth = function(text, fontSize, options) { return this.forEachGlyph(text, 0, 0, fontSize, options, function() {}); }; /** * Draw the text on the given drawing context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.draw = function(ctx, text, x, y, fontSize, options) { this.getPath(text, x, y, fontSize, options).draw(ctx); }; /** * Draw the points of all glyphs in the text. * On-curve points will be drawn in blue, off-curve points will be drawn in red. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawPoints(ctx, gX, gY, gFontSize); }); }; /** * Draw lines indicating important font measurements for all glyphs in the text. * Black lines indicate the origin of the coordinate system (point 0,0). * Blue lines indicate the glyph bounding box. * Green line indicates the advance width of the glyph. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawMetrics(ctx, gX, gY, gFontSize); }); }; /** * @param {string} * @return {string} */ Font.prototype.getEnglishName = function(name) { const translations = this.names[name]; if (translations) { return translations.en; } }; /** * Validate */ Font.prototype.validate = function() { const warnings = []; const _this = this; function assert(predicate, message) { if (!predicate) { warnings.push(message); } } function assertNamePresent(name) { const englishName = _this.getEnglishName(name); assert(englishName && englishName.trim().length > 0, 'No English ' + name + ' specified.'); } // Identification information assertNamePresent('fontFamily'); assertNamePresent('weightName'); assertNamePresent('manufacturer'); assertNamePresent('copyright'); assertNamePresent('version'); // Dimension information assert(this.unitsPerEm > 0, 'No unitsPerEm specified.'); }; /** * Convert the font object to a SFNT data structure. * This structure contains all the necessary tables and metadata to create a binary OTF file. * @return {opentype.Table} */ Font.prototype.toTables = function() { return sfnt.fontToTable(this); }; /** * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead. */ Font.prototype.toBuffer = function() { console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.'); return this.toArrayBuffer(); }; /** * Converts a `opentype.Font` into an `ArrayBuffer` * @return {ArrayBuffer} */ Font.prototype.toArrayBuffer = function() { const sfntTable = this.toTables(); const bytes = sfntTable.encode(); const buffer = new ArrayBuffer(bytes.length); const intArray = new Uint8Array(buffer); for (let i = 0; i < bytes.length; i++) { intArray[i] = bytes[i]; } return buffer; }; /** * Initiate a download of the OpenType font. */ Font.prototype.download = function(fileName) { const familyName = this.getEnglishName('fontFamily'); const styleName = this.getEnglishName('fontSubfamily'); fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf'; const arrayBuffer = this.toArrayBuffer(); if (isBrowser()) { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(window.TEMPORARY, arrayBuffer.byteLength, function(fs) { fs.root.getFile(fileName, {create: true}, function(fileEntry) { fileEntry.createWriter(function(writer) { const dataView = new DataView(arrayBuffer); const blob = new Blob([dataView], {type: 'font/opentype'}); writer.write(blob); writer.addEventListener('writeend', function() { // Navigating to the file will download it. location.href = fileEntry.toURL(); }, false); }); }); }, function(err) { throw new Error(err.name + ': ' + err.message); }); } else { const fs = require('fs'); const buffer = arrayBufferToNodeBuffer(arrayBuffer); fs.writeFileSync(fileName, buffer); } }; /** * @private */ Font.prototype.fsSelectionValues = { ITALIC: 0x001, //1 UNDERSCORE: 0x002, //2 NEGATIVE: 0x004, //4 OUTLINED: 0x008, //8 STRIKEOUT: 0x010, //16 BOLD: 0x020, //32 REGULAR: 0x040, //64 USER_TYPO_METRICS: 0x080, //128 WWS: 0x100, //256 OBLIQUE: 0x200 //512 }; /** * @private */ Font.prototype.usWidthClasses = { ULTRA_CONDENSED: 1, EXTRA_CONDENSED: 2, CONDENSED: 3, SEMI_CONDENSED: 4, MEDIUM: 5, SEMI_EXPANDED: 6, EXPANDED: 7, EXTRA_EXPANDED: 8, ULTRA_EXPANDED: 9 }; /** * @private */ Font.prototype.usWeightClasses = { THIN: 100, EXTRA_LIGHT: 200, LIGHT: 300, NORMAL: 400, MEDIUM: 500, SEMI_BOLD: 600, BOLD: 700, EXTRA_BOLD: 800, BLACK: 900 }; export default Font;
(function(_){var aa,ga,ha;_.l=function(a){return function(){return aa[a].apply(this,arguments)}};_.n=function(a,b){return aa[a]=b};_.ba=function(a){return"function"===typeof window.encodeURIComponent?(0,window.encodeURIComponent)(a):(0,window.escape)(a)};aa=[];_.p=this;_.q=function(a){return void 0!==a};_.r=function(a,b,c){a=a.split(".");c=c||_.p;a[0]in c||!c.execScript||c.execScript("var "+a[0]);for(var d;a.length&&(d=a.shift());)!a.length&&_.q(b)?c[d]=b:c=c[d]?c[d]:c[d]={}};_.t=function(){};_.ca=function(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null";else if("function"==b&&"undefined"==typeof a.call)return"object";return b};_.ea=function(a){return"array"==_.ca(a)};_.v=function(a){return"string"==typeof a};_.w=function(a){return"number"==typeof a};_.x=function(a){return"function"==_.ca(a)};_.fa=function(a){var b=typeof a;return"object"==b&&null!=a||"function"==b};ga=function(a,b,c){return a.call.apply(a.bind,arguments)};ha=function(a,b,c){if(!a)throw Error();if(2<arguments.length){var d=Array.prototype.slice.call(arguments,2);return function(){var c=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(c,d);return a.apply(b,c)}}return function(){return a.apply(b,arguments)}};_.y=function(a,b,c){_.y=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?ga:ha;return _.y.apply(null,arguments)};_.ia=function(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){var b=c.slice();b.push.apply(b,arguments);return a.apply(this,b)}};_.A=Date.now||function(){return+new Date};_.B=function(a,b){function c(){}c.prototype=b.prototype;a.I=b.prototype;a.prototype=new c;a.prototype.constructor=a;a.LC=function(a,c,f){for(var h=Array(arguments.length-2),k=2;k<arguments.length;k++)h[k-2]=arguments[k];return b.prototype[c].apply(a,h)}};_.ka=function(a,b){a[b]||(a[b]=[]);return a[b]};_.la=function(a,b){return a[b]?a[b].length:0};_.ma=function(a,b,c){for(var d in a)b.call(c,a[d],d,a)};_.na=function(a){var b=[],c=0,d;for(d in a)b[c++]=a[d];return b};_.oa=function(a){var b=[],c=0,d;for(d in a)b[c++]=d;return b};var pa;var ua,ya;_.qa=function(a,b){var c=a.length-b.length;return 0<=c&&a.indexOf(b,c)==c};_.ra=String.prototype.trim?function(a){return a.trim()}:function(a){return a.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")};_.sa=function(a,b){return-1!=a.toLowerCase().indexOf(b.toLowerCase())};_.ta=String.prototype.repeat?function(a,b){return a.repeat(b)}:function(a,b){return Array(b+1).join(a)};_.va=function(a,b){for(var c=0,d=(0,_.ra)(String(a)).split("."),e=(0,_.ra)(String(b)).split("."),f=Math.max(d.length,e.length),h=0;0==c&&h<f;h++){var k=d[h]||"",m=e[h]||"",u=RegExp("(\\d*)(\\D*)","g"),z=RegExp("(\\d*)(\\D*)","g");do{var G=u.exec(k)||["","",""],U=z.exec(m)||["","",""];if(0==G[0].length&&0==U[0].length)break;c=ua(0==G[1].length?0:(0,window.parseInt)(G[1],10),0==U[1].length?0:(0,window.parseInt)(U[1],10))||ua(0==G[2].length,0==U[2].length)||ua(G[2],U[2])}while(0==c)}return c};ua=function(a,b){return a<b?-1:a>b?1:0};_.wa=2147483648*Math.random()|0;_.xa=function(a){return String(a).replace(/\-([a-z])/g,function(a,c){return c.toUpperCase()})};ya=function(a){var b=_.v(void 0)?"undefined".replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08"):"\\s";return a.replace(new RegExp("(^"+(b?"|["+b+"]+":"")+")([a-z])","g"),function(a,b,e){return b+e.toUpperCase()})};_.za=function(a){this.g=a||[]};_.za.prototype.$=function(){return this.g};_.za.prototype.im=function(){var a=this.g[8];return null!=a?a:""};_.za.prototype.po=_.l(0);_.Aa=function(a){this.g=a||[]};_.Ba=function(a){this.g=a||[]};_.Ca=new _.Aa;_.Da=new _.Ba;_.Aa.prototype.$=function(){return this.g};_.g=_.Ba.prototype;_.g.$=function(){return this.g};_.g.zm=_.l(1);_.g.getDuration=function(){var a=this.g[0];return null!=a?a:300};_.g.kh=function(){var a=this.g[3];return null!=a?a:1};_.g.mm=function(){var a=this.g[4];return null!=a?a:0};var Fa,Ga,Ka,Ma,Oa,Za,ab,bb,cb,db,eb,jb,kb,wb,xb,yb,zb,Bb,Cb;_.Ea=function(a){this.g=a||[]};Fa=function(a){this.g=a||[]};Ga=function(a){this.g=a||[]};_.Ha=function(a){this.g=a||[]};_.Ia=function(a){this.g=a||[]};_.Ja=function(a){this.g=a||[]};Ka=function(a){this.g=a||[]};_.La=function(a){this.g=a||[]};Ma=function(a){this.g=a||[]};_.Na=function(a){this.g=a||[]};Oa=function(a){this.g=a||[]};_.Pa=function(a){this.g=a||[]};_.Qa=function(a){this.g=a||[]};_.Ra=function(a){this.g=a||[]};_.Sa=function(a){this.g=a||[]};_.Ua=function(a){this.g=a||[]};_.Ea.prototype.$=function(){return this.g};_.Ea.prototype.getWidth=function(){var a=this.g[1];return null!=a?a:0};_.Ea.prototype.getHeight=function(){var a=this.g[2];return null!=a?a:0};_.Va=function(a){a=a.g[3];return null!=a?a:!1};_.Wa=function(a){a=a.g[4];return null!=a?a:!1};_.g=_.Ea.prototype;_.g.getEscapedQemQueryId=function(){var a=this.g[6];return null!=a?a:""};_.g.getEscapedGwsQueryId=function(){var a=this.g[7];return null!=a?a:""};_.g.getWebProperty=function(){var a=this.g[9];return null!=a?a:""};_.g.hh=_.l(3);_.g.gh=_.l(5);var Xa=function(a){a=a.g[12];return null!=a?a:!1};_.Ea.prototype.kf=_.l(7);_.Ea.prototype.jf=_.l(9);_.Ea.prototype.hf=_.l(11);_.Ya=new _.Ha;Za=new _.Na;ab=function(a){return(a=a.g[8])?new _.Na(a):Za};bb=new Oa;cb=function(a){return(a=a.g[15])?new Oa(a):bb};db=new Ga;eb=function(a){return(a=a.g[23])?new Ga(a):db};_.fb=new _.Pa;_.Ea.prototype.fh=_.l(13);_.gb=new _.Qa;_.ib=new _.Ia;jb=new Fa;kb=function(a){return(a=a.g[27])?new Fa(a):jb};_.nb=new _.Sa;_.ob=new _.Ua;_.Ea.prototype.getAds=function(a){return new _.Ja(_.ka(this.g,0)[a])};_.Ea.prototype.fe=_.l(15);Fa.prototype.$=function(){return this.g};var pb=function(a){a=a.g[0];return null!=a?a:!1},qb=function(a){a=a.g[1];return null!=a?a:!1},rb=function(a){a=a.g[2];return null!=a?a:!1},sb=function(a){a=a.g[3];return null!=a?a:!1},ub=function(a){a=a.g[4];return null!=a?a:!1};Ga.prototype.$=function(){return this.g};_.g=_.Ha.prototype;_.g.$=function(){return this.g};_.g.km=function(){var a=this.g[0];return null!=a?a:!1};_.g.lm=function(){var a=this.g[1];return null!=a?a:!1};_.g.jm=function(){var a=this.g[2];return null!=a?a:!1};_.g.nm=function(){var a=this.g[4];return null!=a?a:!1};_.g=_.Ia.prototype;_.g.$=function(){return this.g};_.g.km=function(){var a=this.g[4];return null!=a?a:!1};_.g.lm=function(){var a=this.g[5];return null!=a?a:!1};_.g.jm=function(){var a=this.g[6];return null!=a?a:!1};_.g.nm=function(){var a=this.g[7];return null!=a?a:!1};_.g=_.Ja.prototype;_.g.$=function(){return this.g};_.g.getType=_.l(18);_.g.getIndex=function(){var a=this.g[1];return null!=a?a:0};_.g.getWidth=function(){var a=this.g[2];return null!=a?a:0};_.g.getHeight=function(){var a=this.g[3];return null!=a?a:0};var vb=function(a){a=a.g[4];return null!=a?a:""};_.Ja.prototype.im=function(){var a=this.g[5];return null!=a?a:""};_.Ja.prototype.dj=function(){var a=this.g[7];return null!=a?a:""};wb=function(a){a=a.g[10];return null!=a?a:!1};xb=function(a){a=a.g[14];return null!=a?a:""};yb=function(a){a=a.g[15];return null!=a?a:""};zb=new Ma;_.Ab=function(a){return(a=a.g[8])?new Ma(a):zb};Bb=new Ka;Cb=function(a){return(a=a.g[9])?new Ka(a):Bb};_.Db=new _.La;Ka.prototype.$=function(){return this.g};Ka.prototype.dj=function(){var a=this.g[0];return null!=a?a:""};var Eb=function(a){a=a.g[2];return null!=a?a:""};_.La.prototype.$=function(){return this.g};_.Fb=new _.za;Ma.prototype.$=function(){return this.g};_.Gb=function(a){a=a.g[2];return null!=a?a:""};_.Na.prototype.$=function(){return this.g};_.Na.prototype.ym=_.l(19);_.Na.prototype.hm=function(){var a=this.g[0];return null!=a?a:""};var Hb=function(a){a=a.g[1];return null!=a?a:!1},Ib=function(a){a=a.g[2];return null!=a?a:!1},Jb=function(a){a=a.g[3];return null!=a?a:!1};Oa.prototype.$=function(){return this.g};var Kb=function(a){a=a.g[0];return null!=a?a:!1};_.Pa.prototype.$=function(){return this.g};_.Qa.prototype.$=function(){return this.g};_.Lb=new _.Ra;_.Ra.prototype.$=function(){return this.g};_.Sa.prototype.$=function(){return this.g};_.Ua.prototype.$=function(){return this.g};var Sb,$b;_.Nb=Array.prototype.indexOf?function(a,b,c){return Array.prototype.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(_.v(a))return _.v(b)&&1==b.length?a.indexOf(b,c):-1;for(;c<a.length;c++)if(c in a&&a[c]===b)return c;return-1};_.Ob=Array.prototype.lastIndexOf?function(a,b,c){return Array.prototype.lastIndexOf.call(a,b,null==c?a.length-1:c)}:function(a,b,c){c=null==c?a.length-1:c;0>c&&(c=Math.max(0,a.length+c));if(_.v(a))return _.v(b)&&1==b.length?a.lastIndexOf(b,c):-1;for(;0<=c;c--)if(c in a&&a[c]===b)return c;return-1};_.C=Array.prototype.forEach?function(a,b,c){Array.prototype.forEach.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=_.v(a)?a.split(""):a,f=0;f<d;f++)f in e&&b.call(c,e[f],f,a)};_.Pb=Array.prototype.filter?function(a,b,c){return Array.prototype.filter.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=[],f=0,h=_.v(a)?a.split(""):a,k=0;k<d;k++)if(k in h){var m=h[k];b.call(c,m,k,a)&&(e[f++]=m)}return e};_.Qb=Array.prototype.map?function(a,b,c){return Array.prototype.map.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=Array(d),f=_.v(a)?a.split(""):a,h=0;h<d;h++)h in f&&(e[h]=b.call(c,f[h],h,a));return e};_.Rb=Array.prototype.some?function(a,b,c){return Array.prototype.some.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=_.v(a)?a.split(""):a,f=0;f<d;f++)if(f in e&&b.call(c,e[f],f,a))return!0;return!1};Sb=Array.prototype.every?function(a,b,c){return Array.prototype.every.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=_.v(a)?a.split(""):a,f=0;f<d;f++)if(f in e&&!b.call(c,e[f],f,a))return!1;return!0};_.Ub=function(a,b){var c=_.Tb(a,b,void 0);return 0>c?null:_.v(a)?a.charAt(c):a[c]};_.Tb=function(a,b,c){for(var d=a.length,e=_.v(a)?a.split(""):a,f=0;f<d;f++)if(f in e&&b.call(c,e[f],f,a))return f;return-1};_.Vb=function(a,b){return 0<=(0,_.Nb)(a,b)};_.Xb=function(a,b){var c=(0,_.Nb)(a,b),d;(d=0<=c)&&_.Wb(a,c);return d};_.Wb=function(a,b){Array.prototype.splice.call(a,b,1)};_.Yb=function(a){return Array.prototype.concat.apply(Array.prototype,arguments)};_.Zb=function(a){var b=a.length;if(0<b){for(var c=Array(b),d=0;d<b;d++)c[d]=a[d];return c}return[]};$b=function(a,b){return a>b?1:a<b?-1:0};a:{var bc=_.p.navigator;if(bc){var cc=bc.userAgent;if(cc){_.ac=cc;break a}}_.ac=""}_.D=function(a){return-1!=_.ac.indexOf(a)};var dc=function(){return _.D("Opera")||_.D("OPR")},ec=function(){return(_.D("Chrome")||_.D("CriOS"))&&!dc()&&!_.D("Edge")};var fc=function(a){_.p.setTimeout(function(){throw a;},0)},gc,hc=function(){var a=_.p.MessageChannel;"undefined"===typeof a&&"undefined"!==typeof window&&window.postMessage&&window.addEventListener&&!_.D("Presto")&&(a=function(){var a=window.document.createElement("IFRAME");a.style.display="none";a.src="";window.document.documentElement.appendChild(a);var b=a.contentWindow,a=b.document;a.open();a.write("");a.close();var c="callImmediate"+Math.random(),d="file:"==b.location.protocol?"*":b.location.protocol+"//"+b.location.host,a=(0,_.y)(function(a){if(("*"==d||a.origin==d)&&a.data==c)this.port1.onmessage()},this);b.addEventListener("message",a,!1);this.port1={};this.port2={postMessage:function(){b.postMessage(c,d)}}});if("undefined"!==typeof a&&!_.D("Trident")&&!_.D("MSIE")){var b=new a,c={},d=c;b.port1.onmessage=function(){if(_.q(c.next)){c=c.next;var a=c.Tp;c.Tp=null;a()}};return function(a){d.next={Tp:a};d=d.next;b.port2.postMessage(0)}}return"undefined"!==typeof window.document&&"onreadystatechange"in window.document.createElement("SCRIPT")?function(a){var b=window.document.createElement("SCRIPT");b.onreadystatechange=function(){b.onreadystatechange=null;b.parentNode.removeChild(b);b=null;a();a=null};window.document.documentElement.appendChild(b)}:function(a){_.p.setTimeout(a,0)}};var ic=function(a,b,c){this.sy=c;this.Cv=a;this.Gd=b;this.Ij=0;this.kj=null};ic.prototype.get=function(){var a;0<this.Ij?(this.Ij--,a=this.kj,this.kj=a.next,a.next=null):a=this.Cv();return a};ic.prototype.put=function(a){this.Gd(a);this.Ij<this.sy&&(this.Ij++,a.next=this.kj,this.kj=a)};var jc=function(){this.cl=this.gg=null},lc=new ic(function(){return new kc},function(a){a.reset()},100);jc.prototype.add=function(a,b){var c=lc.get();c.set(a,b);this.cl?this.cl.next=c:this.gg=c;this.cl=c};jc.prototype.remove=function(){var a=null;this.gg&&(a=this.gg,this.gg=this.gg.next,this.gg||(this.cl=null),a.next=null);return a};var kc=function(){this.next=this.scope=this.gm=null};kc.prototype.set=function(a,b){this.gm=a;this.scope=b;this.next=null};kc.prototype.reset=function(){this.next=this.scope=this.gm=null};var rc=function(a,b){mc||nc();oc||(mc(),oc=!0);qc.add(a,b)},mc,nc=function(){if(_.p.Promise&&_.p.Promise.resolve){var a=_.p.Promise.resolve(void 0);mc=function(){a.then(sc)}}else mc=function(){var a=sc;!_.x(_.p.setImmediate)||_.p.Window&&_.p.Window.prototype&&!_.D("Edge")&&_.p.Window.prototype.setImmediate==_.p.setImmediate?(gc||(gc=hc()),gc(a)):_.p.setImmediate(a)}},oc=!1,qc=new jc,sc=function(){for(var a=null;a=qc.remove();){try{a.gm.call(a.scope)}catch(b){fc(b)}lc.put(a)}oc=!1};_.E=function(){this.af=this.af;this.xe=this.xe};_.E.prototype.af=!1;_.E.prototype.N=_.l(20);_.E.prototype.D=_.l(22);_.tc=function(a){_.E.call(this);this.tr=1;this.Sj=[];this.fk=0;this.Ra=[];this.jc={};this.cv=Boolean(a)};_.B(_.tc,_.E);_.tc.prototype.subscribe=function(a,b,c){var d=this.jc[a];d||(d=this.jc[a]=[]);var e=this.tr;this.Ra[e]=a;this.Ra[e+1]=b;this.Ra[e+2]=c;this.tr=e+3;d.push(e);return e};_.tc.prototype.unsubscribe=function(a,b,c){if(a=this.jc[a]){var d=this.Ra;if(a=_.Ub(a,function(a){return d[a+1]==b&&d[a+2]==c}))return this.$o(a)}return!1};_.tc.prototype.$o=function(a){var b=this.Ra[a];if(b){var c=this.jc[b];0!=this.fk?(this.Sj.push(a),this.Ra[a+1]=_.t):(c&&_.Xb(c,a),delete this.Ra[a],delete this.Ra[a+1],delete this.Ra[a+2])}return!!b};_.tc.prototype.zs=function(a,b){var c=this.jc[a];if(c){for(var d=Array(arguments.length-1),e=1,f=arguments.length;e<f;e++)d[e-1]=arguments[e];if(this.cv)for(e=0;e<c.length;e++){var h=c[e];uc(this.Ra[h+1],this.Ra[h+2],d)}else{this.fk++;try{for(e=0,f=c.length;e<f;e++)h=c[e],this.Ra[h+1].apply(this.Ra[h+2],d)}finally{if(this.fk--,0<this.Sj.length&&0==this.fk)for(;c=this.Sj.pop();)this.$o(c)}}}};var uc=function(a,b,c){rc(function(){a.apply(b,c)})};_.tc.prototype.clear=_.l(27);_.tc.prototype.ra=_.l(32);_.tc.prototype.D=_.l(21);_.F=function(a,b,c,d){a.addEventListener?a.addEventListener(b,c,d||!1):a.attachEvent&&a.attachEvent("on"+b,c)};_.vc=function(a,b,c){a.removeEventListener?a.removeEventListener(b,c,!1):a.detachEvent&&a.detachEvent("on"+b,c)};_.wc=function(a,b,c){return Math.min(Math.max(a,b),c)};_.H=function(a,b){this.x=_.q(a)?a:0;this.y=_.q(b)?b:0};_.g=_.H.prototype;_.g.clone=function(){return new _.H(this.x,this.y)};_.g.floor=function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this};_.g.round=function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this};_.g.translate=_.l(35);_.g.scale=_.l(39);_.xc=function(a){_.xc[" "](a);return a};_.xc[" "]=_.t;_.I=function(a,b){this.width=a;this.height=b};_.g=_.I.prototype;_.g.clone=function(){return new _.I(this.width,this.height)};_.g.uc=_.l(40);_.g.Cb=_.l(44);_.g.floor=function(){this.width=Math.floor(this.width);this.height=Math.floor(this.height);return this};_.g.round=function(){this.width=Math.round(this.width);this.height=Math.round(this.height);return this};_.g.scale=_.l(38);_.yc=function(){return _.D("iPhone")&&!_.D("iPod")&&!_.D("iPad")};var Hc,Ic,Kc,Mc;_.zc=dc();_.J=_.D("Trident")||_.D("MSIE");_.Ac=_.D("Edge");_.Bc=_.D("Gecko")&&!(_.sa(_.ac,"WebKit")&&!_.D("Edge"))&&!(_.D("Trident")||_.D("MSIE"))&&!_.D("Edge");_.Cc=_.sa(_.ac,"WebKit")&&!_.D("Edge");_.Dc=_.D("Macintosh");_.Ec=_.D("Android");_.Fc=_.yc();_.Gc=_.D("iPad");Hc=function(){var a=_.ac;if(_.Bc)return/rv\:([^\);]+)(\)|;)/.exec(a);if(_.Ac)return/Edge\/([\d\.]+)/.exec(a);if(_.J)return/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(a);if(_.Cc)return/WebKit\/(\S+)/.exec(a)};Ic=function(){var a=_.p.document;return a?a.documentMode:void 0};_.Jc=function(){if(_.zc&&_.p.opera){var a;var b=_.p.opera.version;try{a=b()}catch(c){a=b}return a}a="";(b=Hc())&&(a=b?b[1]:"");return _.J&&(b=Ic(),b>(0,window.parseFloat)(a))?String(b):a}();Kc={};_.Lc=function(a){return Kc[a]||(Kc[a]=0<=_.va(_.Jc,a))};Mc=_.p.document;_.Nc=Mc&&_.J?Ic()||("CSS1Compat"==Mc.compatMode?(0,window.parseInt)(_.Jc,10):5):void 0;_.Oc=!_.J||9<=Number(_.Nc);!_.Bc&&!_.J||_.J&&9<=Number(_.Nc)||_.Bc&&_.Lc("1.9.1");_.Pc=_.J&&!_.Lc("9");_.Vc=function(a){return a?new _.Tc(_.Uc(a)):pa||(pa=new _.Tc)};_.Wc=function(a,b){return _.v(b)?a.getElementById(b):b};_.Xc=function(a,b,c,d){a=d||a;b=b&&"*"!=b?b.toUpperCase():"";if(a.querySelectorAll&&a.querySelector&&(b||c))return a.querySelectorAll(b+(c?"."+c:""));if(c&&a.getElementsByClassName){a=a.getElementsByClassName(c);if(b){d={};for(var e=0,f=0,h;h=a[f];f++)b==h.nodeName&&(d[e++]=h);d.length=e;return d}return a}a=a.getElementsByTagName(b||"*");if(c){d={};for(f=e=0;h=a[f];f++)b=h.className,"function"==typeof b.split&&_.Vb(b.split(/\s+/),c)&&(d[e++]=h);d.length=e;return d}return a};_.Yc=function(a){for(var b;b=a.firstChild;)a.removeChild(b)};_.Zc=function(a,b){if(!a||!b)return!1;if(a.contains&&1==b.nodeType)return a==b||a.contains(b);if("undefined"!=typeof a.compareDocumentPosition)return a==b||Boolean(a.compareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a};_.Uc=function(a){return 9==a.nodeType?a:a.ownerDocument||a.document};_.Tc=function(a){this.za=a||_.p.document||window.document};_.g=_.Tc.prototype;_.g.lf=_.Vc;_.g.sa=function(a){return _.Wc(this.za,a)};_.g.Tb=_.l(48);_.g.createElement=function(a){return this.za.createElement(a)};_.g.createTextNode=_.l(45);_.g.appendChild=function(a,b){a.appendChild(b)};_.g.ao=_.Yc;_.g.contains=_.Zc;var ad;_.K=function(a,b,c){if(_.v(b))(b=_.$c(a,b))&&(a.style[b]=c);else for(var d in b){c=a;var e=b[d],f=_.$c(c,d);f&&(c.style[f]=e)}};ad={};_.$c=function(a,b){var c=ad[b];if(!c){var d=_.xa(b),c=d;void 0===a.style[d]&&(d=(_.Cc?"Webkit":_.Bc?"Moz":_.J?"ms":_.zc?"O":null)+ya(d),void 0!==a.style[d]&&(c=d));ad[b]=c}return c};_.bd=function(a,b){var c=_.Uc(a);return c.defaultView&&c.defaultView.getComputedStyle&&(c=c.defaultView.getComputedStyle(a,null))?c[b]||c.getPropertyValue(b)||"":""};_.cd=function(a,b){return _.bd(a,b)||(a.currentStyle?a.currentStyle[b]:null)||a.style&&a.style[b]};_.dd=function(a){var b;try{b=a.getBoundingClientRect()}catch(c){return{left:0,top:0,right:0,bottom:0}}_.J&&a.ownerDocument.body&&(a=a.ownerDocument,b.left-=a.documentElement.clientLeft+a.body.clientLeft,b.top-=a.documentElement.clientTop+a.body.clientTop);return b};_.ed=function(a){a=_.dd(a);return new _.H(a.left,a.top)};var hd;_.fd=function(a,b,c){for(var d in a)Object.prototype.hasOwnProperty.call(a,d)&&b.call(c,a[d],d,a)};hd=function(){var a=gd;if(!a)return"";var b=/.*[&#?]google_debug(=[^&]*)?(&.*)?$/;try{var c=b.exec((0,window.decodeURIComponent)(a));if(c)return c[1]&&1<c[1].length?c[1].substring(1):"true"}catch(d){}return""};var kd,id;kd=function(a,b,c,d,e,f){try{if((d?a.pA:Math.random())<(e||a.Jv)){var h=a.fv+b+id(c),h=h.substring(0,2E3);"undefined"===typeof f?_.jd(_.p,h):_.jd(_.p,h,f)}}catch(k){}};id=function(a){var b="";_.fd(a,function(a,d){if(0===a||a)b+="&"+d+"="+(0,window.encodeURIComponent)(String(a))});return b};_.jd=function(a,b,c){a.google_image_requests||(a.google_image_requests=[]);var d=a.document.createElement("img");if(c){var e=function(a){c(a);_.vc(d,"load",e);_.vc(d,"error",e)};_.F(d,"load",e);_.F(d,"error",e)}d.src=b;a.google_image_requests.push(d)};_.L=window.document;_.M=window;var ld,nd;ld=Object.prototype.hasOwnProperty;_.md=function(a,b){for(var c in a)ld.call(a,c)&&b.call(void 0,a[c],c,a)};nd=function(a,b,c,d,e,f){var h;if(!h)a:{if(1===a.nodeType)try{if(1==a.nodeType)h=_.ed(a);else{var k=a.changedTouches?a.changedTouches[0]:a;h=new _.H(k.clientX,k.clientY)}break a}catch(m){}h=new _.H(0,0)}if(window.document.createEvent)k=window.document.createEvent("MouseEvents"),k.initMouseEvent(b,!0,!0,null,0,h.x,h.y,h.x,h.y,d,void 0,e,f,c,null);else if(window.document.createEventObject)k=window.document.createEventObject(),k.Wl="on"+b,k.button=c,k.ctrlKey=d,k.altKey=void 0,k.shiftKey=e,k.metaKey=f,k.clientX=h.x,k.clientY=h.y,k.screenX=h.x,k.screenY=h.y;else return!1;if(a.dispatchEvent)a.dispatchEvent(k);else if(a.fireEvent)a.fireEvent(k.Wl,k);else return!1;return!0};_.od=!!window.google_async_iframe_id;_.pd=_.od&&window.parent||window;_.qd=function(a){a.preventDefault?a.preventDefault():a.returnValue=!1};_.rd=function(a){return a.preventDefault?a.defaultPrevented:!1===a.returnValue};var td=function(a,b){this.Kd=0;this.Js=void 0;this.Fi=this.Pe=this.L=null;this.gj=this.Xl=!1;if(a!=_.t)try{var c=this;a.call(b,function(a){sd(c,2,a)},function(a){sd(c,3,a)})}catch(d){sd(this,3,d)}},ud=function(){this.next=this.context=this.Lf=this.zh=this.Re=null;this.ll=!1};ud.prototype.reset=function(){this.context=this.Lf=this.zh=this.Re=null;this.ll=!1};var vd=new ic(function(){return new ud},function(a){a.reset()},100),wd=function(a,b,c){var d=vd.get();d.zh=a;d.Lf=b;d.context=c;return d},yd=function(a,b,c){xd(a,b,c,null)||rc(_.ia(b,a))},zd=function(a){return new td(function(b,c){a.length||b(void 0);for(var d=0,e;d<a.length;d++)e=a[d],yd(e,b,c)})},Ad=function(a){return new td(function(b,c){var d=a.length,e=[];if(d)for(var f=function(a,c){d--;e[a]=c;0==d&&b(e)},h=function(a){c(a)},k=0,m;k<a.length;k++)m=a[k],yd(m,_.ia(f,k),h);else b(e)})};td.prototype.then=function(a,b,c){return Bd(this,_.x(a)?a:null,_.x(b)?b:null,c)};td.prototype.then=td.prototype.then;td.prototype.$goog_Thenable=!0;var Dd=function(a,b){a.Pe||2!=a.Kd&&3!=a.Kd||Cd(a);a.Fi?a.Fi.next=b:a.Pe=b;a.Fi=b},Bd=function(a,b,c,d){var e=wd(null,null,null);e.Re=new td(function(a,h){e.zh=b?function(c){try{var e=b.call(d,c);a(e)}catch(u){h(u)}}:a;e.Lf=c?function(b){try{var e=c.call(d,b);a(e)}catch(u){h(u)}}:h});e.Re.L=a;Dd(a,e);return e.Re};td.prototype.RA=function(a){this.Kd=0;sd(this,2,a)};td.prototype.SA=function(a){this.Kd=0;sd(this,3,a)};var sd=function(a,b,c){0==a.Kd&&(a==c&&(b=3,c=new TypeError("Promise cannot resolve to itself")),a.Kd=1,xd(c,a.RA,a.SA,a)||(a.Js=c,a.Kd=b,a.L=null,Cd(a),3!=b||Ed(a,c)))},xd=function(a,b,c,d){if(a instanceof td)return Dd(a,wd(b||_.t,c||null,d)),!0;var e;if(a)try{e=!!a.$goog_Thenable}catch(h){e=!1}else e=!1;if(e)return a.then(b,c,d),!0;if(_.fa(a))try{var f=a.then;if(_.x(f))return Fd(a,f,b,c,d),!0}catch(h){return c.call(d,h),!0}return!1},Fd=function(a,b,c,d,e){var f=!1,h=function(a){f||(f=!0,c.call(e,a))},k=function(a){f||(f=!0,d.call(e,a))};try{b.call(a,h,k)}catch(m){k(m)}},Cd=function(a){a.Xl||(a.Xl=!0,rc(a.fw,a))},Gd=function(a){var b=null;a.Pe&&(b=a.Pe,a.Pe=b.next,b.next=null);a.Pe||(a.Fi=null);return b};td.prototype.fw=function(){for(var a=null;a=Gd(this);){var b=this.Kd,c=this.Js;if(3==b&&a.Lf&&!a.ll)for(var d=void 0,d=this;d&&d.gj;d=d.L)d.gj=!1;if(a.Re)a.Re.L=null,Hd(a,b,c);else try{a.ll?a.zh.call(a.context):Hd(a,b,c)}catch(e){Id.call(null,e)}vd.put(a)}this.Xl=!1};var Hd=function(a,b,c){2==b?a.zh.call(a.context,c):a.Lf&&a.Lf.call(a.context,c)},Ed=function(a,b){a.gj=!0;rc(function(){a.gj&&Id.call(null,b)})},Id=fc;var Kd=function(a,b,c){var d="mouseenter_custom"==b,e=Jd(b);return function(f){f||(f=window.event);if(f.type==e){if("mouseenter_custom"==b||"mouseleave_custom"==b){var h;if(h=d?f.relatedTarget||f.fromElement:f.relatedTarget||f.toElement)for(var k=0;k<a.length;k++)if(_.Zc(a[k],h))return}c(f)}}},Jd=function(a){return"mouseenter_custom"==a?"mouseover":"mouseleave_custom"==a?"mouseout":a};var Ld=function(a,b,c,d,e){c="&"+b+"="+c;var f=a.indexOf("&"+d+"=");c=0>f?a+c:a.substring(0,f)+c+a.substring(f);return 2E3<c.length?_.q(e)?Ld(a,b,e,d,void 0):a:c};_.Md="StopIteration"in _.p?_.p.StopIteration:{message:"StopIteration",stack:""};_.Nd=function(){};_.Nd.prototype.next=function(){throw _.Md;};_.Nd.prototype.ng=function(){return this};_.Od=function(a,b){this.Eb={};this.O=[];this.ii=this.X=0;var c=arguments.length;if(1<c){if(c%2)throw Error("Uneven number of arguments");for(var d=0;d<c;d+=2)this.set(arguments[d],arguments[d+1])}else a&&this.addAll(a)};_.g=_.Od.prototype;_.g.ra=_.l(31);_.g.Z=function(){Pd(this);for(var a=[],b=0;b<this.O.length;b++)a.push(this.Eb[this.O[b]]);return a};_.g.zb=function(){Pd(this);return this.O.concat()};_.g.Ua=function(a){return Qd(this.Eb,a)};_.g.Cb=_.l(43);_.g.clear=_.l(26);_.g.remove=function(a){return Qd(this.Eb,a)?(delete this.Eb[a],this.X--,this.ii++,this.O.length>2*this.X&&Pd(this),!0):!1};var Pd=function(a){if(a.X!=a.O.length){for(var b=0,c=0;b<a.O.length;){var d=a.O[b];Qd(a.Eb,d)&&(a.O[c++]=d);b++}a.O.length=c}if(a.X!=a.O.length){for(var e={},c=b=0;b<a.O.length;)d=a.O[b],Qd(e,d)||(a.O[c++]=d,e[d]=1),b++;a.O.length=c}};_.g=_.Od.prototype;_.g.get=function(a,b){return Qd(this.Eb,a)?this.Eb[a]:b};_.g.set=function(a,b){Qd(this.Eb,a)||(this.X++,this.O.push(a),this.ii++);this.Eb[a]=b};_.g.addAll=function(a){var b;a instanceof _.Od?(b=a.zb(),a=a.Z()):(b=_.oa(a),a=_.na(a));for(var c=0;c<b.length;c++)this.set(b[c],a[c])};_.g.forEach=function(a,b){for(var c=this.zb(),d=0;d<c.length;d++){var e=c[d],f=this.get(e);a.call(b,f,e,this)}};_.g.clone=function(){return new _.Od(this)};_.g.ng=function(a){Pd(this);var b=0,c=this.ii,d=this,e=new _.Nd;e.next=function(){if(c!=d.ii)throw Error("The map has changed since the iterator was created");if(b>=d.O.length)throw _.Md;var e=d.O[b++];return a?e:d.Eb[e]};return e};var Qd=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)};var Wd,Yd,Zd,ae,be;_.Rd=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#(.*))?$/;_.Sd=function(a){return a?(0,window.decodeURI)(a):a};_.Vd=function(a,b){return b.match(_.Rd)[a]||null};Wd=function(a,b){if(a)for(var c=a.split("&"),d=0;d<c.length;d++){var e=c[d].indexOf("="),f=null,h=null;0<=e?(f=c[d].substring(0,e),h=c[d].substring(e+1)):f=c[d];b(f,h?(0,window.decodeURIComponent)(h.replace(/\+/g," ")):"")}};_.Xd=function(a){if(a[1]){var b=a[0],c=b.indexOf("#");0<=c&&(a.push(b.substr(c)),a[0]=b=b.substr(0,c));c=b.indexOf("?");0>c?a[1]="?":c==b.length-1&&(a[1]=void 0)}return a.join("")};Yd=function(a,b,c,d){for(var e=c.length;0<=(b=a.indexOf(c,b))&&b<d;){var f=a.charCodeAt(b-1);if(38==f||63==f)if(f=a.charCodeAt(b+e),!f||61==f||38==f||35==f)return b;b+=e+1}return-1};Zd=/#|$/;_.$d=function(a,b){var c=a.search(Zd),d=Yd(a,0,b,c);if(0>d)return null;var e=a.indexOf("&",d);if(0>e||e>c)e=c;d+=b.length+1;return(0,window.decodeURIComponent)(a.substr(d,e-d).replace(/\+/g," "))};ae=/[?&]($|#)/;be=function(a,b,c){for(var d=a.search(Zd),e=0,f,h=[];0<=(f=Yd(a,e,b,d));)h.push(a.substring(e,f)),e=Math.min(a.indexOf("&",f)+1||d,d);h.push(a.substr(e));a=[h.join("").replace(ae,"$1"),"&",b];null!=c&&a.push("=",(0,window.encodeURIComponent)(String(c)));return _.Xd(a)};var ee,fe,he,je,pe,ke,me,le,oe,ne;_.N=function(a,b){this.Wa=this.Je=this.Kb="";this.Nf=null;this.rd=this.Mf="";this.nb=this.iy=!1;var c;if(a instanceof _.N)this.nb=_.q(b)?b:a.nb,_.ce(this,a.Kb),c=a.Je,_.de(this),this.Je=c,ee(this,a.Wa),fe(this,a.Nf),c=a.getPath(),_.de(this),this.Mf=c,_.ge(this,a.Ka.clone()),c=a.rd,_.de(this),this.rd=c;else if(a&&(c=String(a).match(_.Rd))){this.nb=!!b;_.ce(this,c[1]||"",!0);var d=c[2]||"";_.de(this);this.Je=he(d);ee(this,c[3]||"",!0);fe(this,c[4]);d=c[5]||"";_.de(this);this.Mf=he(d,!0);_.ge(this,c[6]||"",!0);c=c[7]||"";_.de(this);this.rd=he(c)}else this.nb=!!b,this.Ka=new _.ie(null,0,this.nb)};_.N.prototype.toString=function(){var a=[],b=this.Kb;b&&a.push(je(b,ke,!0),":");var c=this.Wa;if(c||"file"==b)a.push("//"),(b=this.Je)&&a.push(je(b,ke,!0),"@"),a.push((0,window.encodeURIComponent)(String(c)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),c=this.Nf,null!=c&&a.push(":",String(c));if(c=this.getPath())this.Wa&&"/"!=c.charAt(0)&&a.push("/"),a.push(je(c,"/"==c.charAt(0)?le:me,!0));(c=this.Ka.toString())&&a.push("?",c);(c=this.rd)&&a.push("#",je(c,ne));return a.join("")};_.N.prototype.resolve=function(a){var b=this.clone(),c=!!a.Kb;c?_.ce(b,a.Kb):c=!!a.Je;if(c){var d=a.Je;_.de(b);b.Je=d}else c=!!a.Wa;c?ee(b,a.Wa):c=null!=a.Nf;d=a.getPath();if(c)fe(b,a.Nf);else if(c=!!a.Mf){if("/"!=d.charAt(0))if(this.Wa&&!this.Mf)d="/"+d;else{var e=b.getPath().lastIndexOf("/");-1!=e&&(d=b.getPath().substr(0,e+1)+d)}e=d;if(".."==e||"."==e)d="";else if(-1!=e.indexOf("./")||-1!=e.indexOf("/.")){for(var d=0==e.lastIndexOf("/",0),e=e.split("/"),f=[],h=0;h<e.length;){var k=e[h++];"."==k?d&&h==e.length&&f.push(""):".."==k?((1<f.length||1==f.length&&""!=f[0])&&f.pop(),d&&h==e.length&&f.push("")):(f.push(k),d=!0)}d=f.join("/")}else d=e}c?(_.de(b),b.Mf=d):c=""!==a.Ka.toString();c?_.ge(b,he(a.Ka.toString())):c=!!a.rd;c&&(a=a.rd,_.de(b),b.rd=a);return b};_.N.prototype.clone=function(){return new _.N(this)};_.ce=function(a,b,c){_.de(a);a.Kb=c?he(b,!0):b;a.Kb&&(a.Kb=a.Kb.replace(/:$/,""))};ee=function(a,b,c){_.de(a);a.Wa=c?he(b,!0):b};fe=function(a,b){_.de(a);if(b){b=Number(b);if((0,window.isNaN)(b)||0>b)throw Error("Bad port number "+b);a.Nf=b}else a.Nf=null};_.N.prototype.getPath=function(){return this.Mf};_.ge=function(a,b,c){_.de(a);b instanceof _.ie?(a.Ka=b,a.Ka.qo(a.nb)):(c||(b=je(b,oe)),a.Ka=new _.ie(b,0,a.nb))};_.de=function(a){if(a.iy)throw Error("Tried to modify a read-only Uri");};_.N.prototype.qo=function(a){this.nb=a;this.Ka&&this.Ka.qo(a);return this};he=function(a,b){return a?b?(0,window.decodeURI)(a.replace(/%25/g,"%2525")):(0,window.decodeURIComponent)(a):""};je=function(a,b,c){return _.v(a)?(a=(0,window.encodeURI)(a).replace(b,pe),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),a):null};pe=function(a){a=a.charCodeAt(0);return"%"+(a>>4&15).toString(16)+(a&15).toString(16)};ke=/[#\/\?@]/g;me=/[\#\?:]/g;le=/[\#\?]/g;oe=/[\#\?@]/g;ne=/#/g;_.ie=function(a,b,c){this.X=this.ca=null;this.Xa=a||null;this.nb=!!c};_.qe=function(a){a.ca||(a.ca=new _.Od,a.X=0,a.Xa&&Wd(a.Xa,function(b,c){a.add((0,window.decodeURIComponent)(b.replace(/\+/g," ")),c)}))};_.g=_.ie.prototype;_.g.ra=_.l(30);_.g.add=function(a,b){_.qe(this);this.Xa=null;a=re(this,a);var c=this.ca.get(a);c||this.ca.set(a,c=[]);c.push(b);this.X+=1;return this};_.g.remove=function(a){_.qe(this);a=re(this,a);return this.ca.Ua(a)?(this.Xa=null,this.X-=this.ca.get(a).length,this.ca.remove(a)):!1};_.g.clear=_.l(25);_.g.Cb=_.l(42);_.g.Ua=function(a){_.qe(this);a=re(this,a);return this.ca.Ua(a)};_.g.zb=function(){_.qe(this);for(var a=this.ca.Z(),b=this.ca.zb(),c=[],d=0;d<b.length;d++)for(var e=a[d],f=0;f<e.length;f++)c.push(b[d]);return c};_.g.Z=function(a){_.qe(this);var b=[];if(_.v(a))this.Ua(a)&&(b=_.Yb(b,this.ca.get(re(this,a))));else{a=this.ca.Z();for(var c=0;c<a.length;c++)b=_.Yb(b,a[c])}return b};_.g.set=function(a,b){_.qe(this);this.Xa=null;a=re(this,a);this.Ua(a)&&(this.X-=this.ca.get(a).length);this.ca.set(a,[b]);this.X+=1;return this};_.g.get=function(a,b){var c=a?this.Z(a):[];return 0<c.length?String(c[0]):b};_.se=function(a,b,c){a.remove(b);0<c.length&&(a.Xa=null,a.ca.set(re(a,b),_.Zb(c)),a.X+=c.length)};_.ie.prototype.toString=function(){if(this.Xa)return this.Xa;if(!this.ca)return"";for(var a=[],b=this.ca.zb(),c=0;c<b.length;c++)for(var d=b[c],e=(0,window.encodeURIComponent)(String(d)),d=this.Z(d),f=0;f<d.length;f++){var h=e;""!==d[f]&&(h+="="+(0,window.encodeURIComponent)(String(d[f])));a.push(h)}return this.Xa=a.join("&")};_.ie.prototype.clone=function(){var a=new _.ie;a.Xa=this.Xa;this.ca&&(a.ca=this.ca.clone(),a.X=this.X);return a};var re=function(a,b){var c=String(b);a.nb&&(c=c.toLowerCase());return c};_.ie.prototype.qo=function(a){a&&!this.nb&&(_.qe(this),this.Xa=null,this.ca.forEach(function(a,c){var d=c.toLowerCase();c!=d&&(this.remove(c),_.se(this,d,a))},this));this.nb=a};_.ie.prototype.extend=_.l(50);_.te=_.D("Firefox");_.ue=_.yc()||_.D("iPod");_.ve=_.D("iPad");_.we=_.D("Android")&&!(ec()||_.D("Firefox")||dc()||_.D("Silk"));_.xe=ec();_.ye=_.D("Safari")&&!(ec()||_.D("Coast")||dc()||_.D("Edge")||_.D("Silk")||_.D("Android"))&&!(_.yc()||_.D("iPad")||_.D("iPod"));var ze,Ae,Be,Ce,De,Ge,Fe;ze=function(a){return _.we||_.Ec?a.replace(/https?:\/\/(market.android.com|play.google.com\/store\/apps)\//,"market://"):a};Ae=function(a){return a.replace("?","?"+(0,window.encodeURIComponent)("rct")+"="+(0,window.encodeURIComponent)("j")+"&")};Be="doubleclick.net 2mdn.net dartmotif.net doubleclick.net doubleclick.com gstatic.com app-measurement.com google-analytics.com".split(" ");Ce=function(a){var b=_.Sd(_.Vd(3,a));return b?(0,_.Rb)(Be,function(a){return _.qa(b,a)}):!0};De=function(a){if(a.match(/[\?&]sa=L/)){var b;b=_.Vd(1,a);!b&&_.p.self&&_.p.self.location&&(b=_.p.self.location.protocol,b=b.substr(0,b.length-1));b=b?b.toLowerCase():"";var c=a.match(_.Rd);a=c[5];var d=c[6],c=c[7],e="";a&&(e+=a);d&&(e+="?"+d);c&&(e+="#"+c);a=e;c=window.location.toString();d=_.Sd(_.Vd(3,c));c=_.Vd(1,c);"http"!=b&&"https"!=b&&(c=b);a=Ae(c+"://"+d+(a||""));b=new window.XMLHttpRequest;b.open("GET",a,!1);window.jstiming&&_.x(window.jstiming.report)?(a=new window.jstiming.Timer,b.send(),a.tick&&(a.tick("cr_csr"),window.jstiming.report(a))):b.send();var f;b.responseText&&(b=b.responseText.match(/URL=\'([^\']*)\'/),1<b.length&&(f=b[1].replace(/&amp;/g,"&")));return f}};Ge=function(a){if(!a.Se||!a.Bc||a.cg&&Ce(a.cg)||!_.Ee(a.Bc)&&!Fe(a.Bc)||!a.Wj||!a.cs)return!1;var b=a.cs,c=_.Ee(a.Bc),d=Fe(a.Bc),e=a.Bc,f=a.Se,h=a.cg;if(!f||"L"!=_.$d(f,"sa"))return a=new td(_.t),sd(a,2,void 0),!1;if(c){_.Ee(h)&&(e=h,h=void 0);if(void 0==h)return a.Wj(f),b(e),!0;h=(c=De(f))||h;_.Ee(h)&&(e=h,h=void 0);h&&(h=be(h,"urlloadedinbrowser","false"),a.Wj(h));b(e);return!0}if(d){h=(c=De(f))||h;c=_.$d(h,"referrer");d=_.$d(e,"referrer");Fe(h)&&(e=h,h=void 0);f=[];d&&f.push(d);c&&f.push(c);if(c=f.join("&"))e=be(e,"referrer",c),h&&(h=be(h,"referrer",c));e=ze(e);h&&(h=be(h,"urlloadedinbrowser","false"),a.Wj(h));b(e);return!0}return!1};Fe=function(a){if(!a)return!1;var b=_.Sd(_.Vd(3,a));a=_.Sd(_.Vd(5,a));return"market.android.com"==b||"play.google.com"==b&&"/store/apps/details"==a};_.Ee=function(a){return a?"itunes.apple.com"==_.Sd(_.Vd(3,a)):!1};var He;He={yB:0,mg:1,URL:2,kg:3,jg:4,Hu:5,Du:7,FAVICON:8,mi:9,lg:6,ku:10,tu:11,ru:12,uu:34,cu:13,Wt:14,MB:15,ni:16,Mu:29,au:30,yu:17,Zt:18,bu:19,xB:20,Xt:21,Bu:22,ri:23,li:24,pi:25,oi:26,Yt:27,Au:28,Ju:31,$t:32,fl:33,hu:35,hl:36,dl:37,gl:38,FB:1E3,lu:1001,mu:1002};_.Ie=[11,12,16,18,27,28];var Je=function(a,b,c,d){b=c(d,b);if(!(b instanceof Array))return a;(0,_.C)(b,function(b){if(2!==b.length&&3!==b.length)return a;a=Ld(a,b[0],b[1],"adurl",b[2])});return a},Ke=function(a,b,c){if(_.M.ona){_.qd(a);a=b.href||c.Se;_.M.agss&&(a=_.M.agss(a));if(b=window.u2hgmob){b=a;var d=c.cg,e=c.Bc;if(window.ona&&window.onc){var f=window.ona;window.asogmob&&window.osto&&(f=window.osto);b=Ge({Se:b,cg:d,Bc:e,Wj:window.onc,cs:f})}else b=!1}!b&&(b=c.Ac.match("/play[.]google[.]com/redeem?"))&&(b=c.Ac,"function"==typeof window.oit&&"function"==typeof window.onc?(window.onc(a),window.oit({id:"redemptionId",url:b,packageName:"com.android.vending"}),b=!0):b=!1);if(!b)a:{if(window.ona){b=c.Se;c=c.Ac;window.agss&&(b=window.agss(b));if(c.match(/^https?:\/\/itunes[.]apple[.]com/)){if(window.onc)window.onc(b),window.ona(c);else window.ona(b);b=!0;break a}c=b;if(c.match(/market[.]android[.]com|play[.]google[.]com/)&&c.match(/[\?&]sa=L/)&&!c.match(/googleadservices[.]com/)){if(d=window.location.host){b=1;e=d.split(":");for(d=[];0<b&&e.length;)d.push(e.shift()),b--;e.length&&d.push(e.join(":"));b=d[0];d=d[1];c=new _.N(c);ee(c,b);fe(c,d);c=c.toString()}c=Ae(c);b=new window.XMLHttpRequest;b.open("GET",c,!1);window.jstiming&&_.x(window.jstiming.report)?(d=new window.jstiming.Timer,b.send(),d.tick&&(d.tick("cr_csr"),window.jstiming.report(d))):b.send();b.responseText&&(b=b.responseText.match(/URL=\'([^\']*)\'/),1<b.length&&(c=b[1].replace(/&amp;/g,"&")));c=ze(c)}else c=null;if(c){window.ona(c);b=!0;break a}}b=!1}if(b)return!0;_.M.ona(a);return!0}return!1};_.Le=function(a){this.qa=a;this.gp=[];this.Ci=[];this.Pm={};this.da={};this.Jr=1;this.Ch="data-original-click-url";this.jo="data-landing-url";this.bd={};this.Tm=!1;this.Xi=[]};_.Le.prototype.Nh=_.l(52);var Me=function(a,b,c){var d=b=b.getAttribute(a.Ch);if(d)for(var e=0;e<a.gp.length;e++)d=Je(d,b,a.gp[e],c);return d},Ne=function(a,b,c,d){if(0!=a.Ci.length&&!_.rd(d)){var e=1==d.which&&!d.ctrlKey&&"_blank"!=b.target&&"_new"!=b.target;e&&_.qd(d);for(var f=[],h=0;h<a.Ci.length;h++){var k=a.Ci[h](c);if(k){var m=new td(function(a){_.jd(window,k,a)});f.push(m)}}c=Ad(f);f=new td(function(a){window.setTimeout(a,2E3)});e&&zd([c,f]).then((0,_.y)(_.Le.prototype.Lz,a,b,d))}};_.Le.prototype.Lz=function(a,b){this.Tm=!0;var c=!1;b.target&&(c=nd(b.target,"click",b.button,b.ctrlKey,b.shiftKey,b.metaKey));!a.href||c||Ke(b,a,{Se:a.href,Ac:vb(this.qa),cg:yb(this.qa),Bc:xb(this.qa)})||(_.M.top.location=a.href)};_.Le.prototype.iw=function(a,b,c,d){if(this.Tm)this.Tm=!1;else{d||(d=window.event);_.ma(this.da[c][b],function(a){a(d)});if(a.href){var e=Me(this,a,d.type);e&&(this.bd[b]?a.ping=e:a.href=e)}"click"==c&&Ne(this,a,b,d);Oe(this);"click"!=c||_.rd(d)||Ke(d,a,{Se:a.href,Ac:vb(this.qa),cg:yb(this.qa),Bc:xb(this.qa)})}};var Pe=function(a,b,c,d){a.da[d]||(a.da[d]={});a.da[d][c]||(a.da[d][c]={});_.F(b,d,(0,_.y)(a.iw,a,b,c,d))};_.g=_.Le.prototype;_.g.Fd=function(a,b){for(var c=0;c<a.length;c++){var d=a[c];d.href&&d.setAttribute(this.Ch,d.href);Pe(this,d,b,"mousedown");Pe(this,d,b,"click")}this.Pm[b]=!0};_.g.fi=_.l(54);_.g.Ug=_.l(56);_.g.Yh=_.l(58);_.g.Ph=_.l(60);_.g.queueOnObjectAfterClickModifiers=function(a,b,c,d){this.Xi.push({Ou:a,Wl:b,ew:c,lv:d})};var Oe=function(a){for(var b=0;b<a.Xi.length;b++){var c=a.Xi[b],d=c.Ou,e=c.Wl,f=c.ew;c.lv&&_.rd(f)||d.fireOnObject(e,f)}a.Xi=[]};var Qe,Re,Se;Qe="undefined"!=typeof window.DOMTokenList;Re=function(a,b){if(Qe){var c=a.classList;0==c.contains(b)&&c.toggle(b)}else if(c=a.className){for(var c=c.split(/\s+/),d=!1,e=0;e<c.length&&!d;++e)d=c[e]==b;d||(c.push(b),a.className=c.join(" "))}else a.className=b};Se=function(a,b){if(Qe){var c=a.classList;1==c.contains(b)&&c.toggle(b)}else if((c=a.className)&&!(0>c.indexOf(b))){for(var c=c.split(/\s+/),d=0;d<c.length;++d)c[d]==b&&c.splice(d--,1);a.className=c.join(" ")}};_.Ue=function(a,b,c){(c?Se:Re)(a,b)};_.O=function(a,b,c){this.aa=new _.tc;this.V=a;this.V[0]=[b];this.Ej=[];this.Sg=b.style.display;this.Qb=new _.Le(c);this.qa=c;if(b=window.document.getElementById("common_15click_anchor"))a[20]=[b],this.Fd(20)};_.g=_.O.prototype;_.g.navigationAdPieces=function(){return this.Ej};_.g.Qm=function(){return!0};_.g.hide=function(){for(var a=this.V[0],b=0;b<a.length;b++)a[b].style.display="none"};_.g.reset=function(){for(var a=this.V[0],b=0;b<a.length;b++)a[b].style.display=this.Sg};_.g.has=function(a){return(a=this.V[a])&&0<a.length};_.g.listen=function(a,b,c){var d=this.V[a];if(d){var e=this.Qb,f=Jd(b),h=("click"==b||"mousedown"==b)&&e.Pm[a],k=Kd(d,b,_.ia(c,a,this));e.da[f]||(e.da[f]={});e.da[f][a]||(e.da[f][a]={});var m=e.Jr;e.da[f][a][m]=k;e.Jr=m+1;if(!h)for(e=0;e<d.length;e++)_.F(d[e],f,k);c.rc||(c.rc={});c.rc[b]||(c.rc[b]={});c.rc[b][a]=m}};_.g.unlisten=function(a,b,c){var d;if(c.rc&&c.rc[b]&&c.rc[b][a]){var e=c.rc[b][a];delete c.rc[b][a];d=e}else d=-1;if(c=this.V[a]){var f=this.Qb,e=Jd(b);b=("click"==b||"mousedown"==b)&&f.Pm[a];if(f.da[e]&&f.da[e][a]){var h=f.da[e][a][d];delete f.da[e][a][d];a=h}else a=null;if(a&&!b)for(b=0;b<c.length;b++)_.vc(c[b],e,a)}};_.Ve=function(a,b,c,d,e,f){if(a=a.V[b])for(b=0;b<a.length;b++){var h="click",h=Jd(h);nd(a[b],h,c,d,e,f)}};_.O.prototype.registerClickUrlModifier=function(a){this.Qb.gp.push(a)};_.O.prototype.Nh=_.l(51);_.O.prototype.modifyCssClass=function(a,b,c){if(b&&(a=this.V[a]))for(var d=0;d<a.length;d++)_.Ue(a[d],b,c)};_.O.prototype.getComputedStyle=function(a){return(a=this.V[a])&&0<a.length?window.getComputedStyle(a[0]):null};var We=function(a,b){var c=a.V[b];if(!c||!c[0])return"rgb(255, 255, 255)";c=c[0].parentElement;if(!c)return"rgb(255, 255, 255)";for(var d=/rgba\([ \d]+,[ \d]+,[ \d]+,[ 0\.]+\)/;c;){var e=window.getComputedStyle(c).backgroundColor;if(e&&!d.exec(e)&&"transparent"!=e)return e;c=c.parentElement}return"rgb(255, 255, 255)"};_.g=_.O.prototype;_.g.getAttribute=function(a,b){var c=this.V[a];if(c&&b)for(var d=0;d<c.length;d++){var e=c[d].getAttribute(b);if(e)return e}return null};_.g.setAttribute=function(a,b,c){(a=this.V[a])&&0<a.length&&b&&a[0].setAttribute(b,c)};_.g.removeAttribute=function(a,b){var c=this.V[a];c&&0<c.length&&b&&c[0].removeAttribute(b)};_.g.getBoundingClientRect=function(a){return(a=this.V[a])?a[0].getBoundingClientRect():null};_.g.forEachAdPiece=function(a){var b=this.V;_.ma(He,function(c){b[c]&&0<b[c].length&&a(c)})};_.g.forEachNavigationAdPiece=function(a){for(var b=this.V,c=0;c<this.Ej.length;++c){var d=this.Ej[c];b[d]&&0<b[d].length&&a(d)}};_.g.Fd=function(a){this.V[a]&&this.Qm(a)&&(this.Ej.push(a),this.Qb.Fd(this.V[a],a))};_.g.fi=_.l(53);_.g.Ug=_.l(55);_.g.Yh=_.l(57);_.g.Ph=_.l(59);_.Xe=function(a,b){var c=a.V[b];if(!c)return!1;for(var d=0;d<c.length;d++)if(!c[d].href)return!1;return!0};_.g=_.O.prototype;_.g.getAdData=function(){return this.qa};_.g.creativeConversionUrl=function(){return this.qa.im()};_.g.adGroupCreativeId=function(){var a=this.qa.g[6];return null!=a?a:""};_.g.redirectUrl=function(){return this.qa.dj()};_.g.Ac=function(){return vb(this.qa)};_.g.getIndex=function(){return this.qa.getIndex()};_.g.getWidth=function(){return this.qa.getWidth()};_.g.getHeight=function(){return this.qa.getHeight()};_.g.listenOnObject=function(a,b){this.aa.subscribe(a,b)};_.g.unlistenOnObject=function(a,b){this.aa.unsubscribe(a,b)};_.g.fireOnObject=function(a,b){this.aa.zs(a,b)};_.g.queueOnObjectAfterClickModifiers=function(a,b,c){this.Qb.queueOnObjectAfterClickModifiers(this,a,b,c)};var Ye,Ze;Ye=function(a,b,c){this.Az=a;this.cw=b;this.zo=c;this.Bp=null;this.bw=this.zj;this.WA=!1};Ze=function(a,b,c){this.message=a;this.fileName=b||"";this.lineNumber=c||-1};_.af=function(a,b,c,d,e){var f;try{f=c()}catch(m){var h=a.zo;try{var k=$e(m),h=(e||a.bw).call(a,b,k,void 0,d)}catch(u){a.zj("pAR",u)}if(!h)throw m;}finally{}return f};_.ff=function(a,b,c,d){var e=_.ef;return function(){var f=arguments;return _.af(e,a,function(){return b.apply(c,f)},d)}};Ye.prototype.zj=function(a,b,c,d,e){var f={};f.context=a;b instanceof Ze||(b=$e(b));f.msg=b.message.substring(0,512);b.fileName&&(f.file=b.fileName);0<b.lineNumber&&(f.line=b.lineNumber.toString());a=_.p.document;f.url=a.URL.substring(0,512);f.ref=a.referrer.substring(0,512);if(this.Bp)try{this.Bp(f)}catch(h){}if(d)try{d(f)}catch(h){}kd(this.Az,e||this.cw,f,this.WA,c);return this.zo};var $e=function(a){var b=a.toString();a.name&&-1==b.indexOf(a.name)&&(b+=": "+a.name);a.message&&-1==b.indexOf(a.message)&&(b+=": "+a.message);if(a.stack){var c=a.stack,d=b;try{-1==c.indexOf(d)&&(c=d+"\n"+c);for(var e;c!=e;)e=c,c=c.replace(/((https?:\/..*\/)[^\/:]*:\d+(?:.|\n)*)\2/,"$1");b=c.replace(/\n */g,"\n")}catch(f){b=d}}return new Ze(b,a.fileName,a.lineNumber)};var gf,kf;gf=new function(){this.fv="http"+("http:"===_.M.location.protocol?"":"s")+"://pagead2.googlesyndication.com/pagead/gen_204?id=";this.Jv=.01;this.pA=Math.random()};_.ef=new Ye(gf,"jserror",!0);_.hf=_.ef.zj;_.jf=function(a,b,c){kd(gf,a,b,"jserror"!=a,c,void 0)};kf=function(a){_.ef.zj(a,Error("container is null"),void 0,void 0)};_.lf=function(){this.O=[];this.eg=[]};_.g=_.lf.prototype;_.g.ra=_.l(29);_.g.Z=function(){return this.eg.concat()};_.g.zb=function(){return this.O.concat()};_.g.Ua=function(a){return 0<=(0,_.Nb)(this.O,a)};_.g.clear=_.l(24);_.g.remove=function(a){a=(0,_.Nb)(this.O,a);return 0<=a?(this.O.splice(a,1),this.eg.splice(a,1),!0):!1};_.g.get=function(a,b){var c=(0,_.Nb)(this.O,a);return 0<=c?this.eg[c]:b};_.g.set=function(a,b){var c=(0,_.Nb)(this.O,a);0<=c?this.eg[c]=b:(this.O.push(a),this.eg.push(b))};_.P=function(a,b,c){this.aa=new _.tc;this.ua=a;this.Sg="none";this.ua&&(this.Sg=this.ua.style.display);this.fd=b;this.g=c;this.da={};this.An=[];this.hr=!1;this.pc=[]};_.g=_.P.prototype;_.g.forEachAd=function(a){(0,_.C)(this.fd,a)};_.g.kl=function(a){this.fd.push(a)};_.g.em=function(a){if(a=window.document.getElementById(a))this.ua=a,this.Sg=this.ua.style.display;if(0==this.fd.length)window.css=null;else{window.ImageExpandConstructor&&1==this.fd.length&&new window.ImageExpandConstructor(this,_.Va(this.g));window.IntentfulClickConstructor&&new window.IntentfulClickConstructor(this,ab(this.g).hm(),Hb(ab(this.g)),Ib(ab(this.g)),Jb(ab(this.g)));window.ona&&!_.Wa(this.g)&&(window.ona=null,window.osb=null);if(null!=window.ona&&null!=window.osb){if(pb(kb(this.g))){var b=Boolean(qb(kb(this.g))),c=Boolean(rb(kb(this.g)));window.ona=function(a){window.osb(a,{useFirstPackage:b,useRunningProcess:c})}}window.u2hgmob=Boolean(sb(kb(this.g)));window.asogmob=Boolean(ub(kb(this.g)))}for(a=0;a<this.An.length;++a)this.An[a]();this.hr=!0}};_.g.listenOnContainer=function(a,b){if(this.ua){var c=Kd([this.ua],a,_.ia(b,this));_.F(this.ua,Jd(a),c);this.da[a]||(this.da[a]=new _.lf);this.da[a].set(b,c)}else kf("hdrAsLoc")};_.g.unlistenOnContainer=function(a,b){if(this.ua){var c;this.da[a]&&this.da[a].Ua(b)?(c=this.da[a].get(b),this.da[a].remove(b)):c=null;c&&_.vc(this.ua,Jd(a),c)}else kf("hdrAsUoc")};_.g.listenOnObject=function(a,b){this.aa.subscribe(a,b)};_.g.unlistenOnObject=function(a,b){this.aa.unsubscribe(a,b)};_.g.fireOnObject=function(a,b){b.JC=this;this.aa.zs(a,b)};_.g.registerFinalizeCallback=function(a){this.hr?a():this.An.push(a)};_.g.registerWidget=function(a,b){_.Vb(this.pc,a)||(this.pc[b]=a,a.reset(this))};var mf=function(a){a.ua.style.display="none";for(var b=0;b<a.pc.length;b++)a.pc[b]&&a.pc[b].hide(a)};_.P.prototype.resetAll=function(){this.ua.style.display=this.Sg;for(var a=0;a<this.pc.length;a++)this.pc[a]&&this.pc[a].reset(this)};_.P.prototype.showOnly=function(a){var b=this;mf(this);nf(this,a,function(a){a.show(b)})};var nf=function(a,b,c){a.pc[b]&&c(a.pc[b])};_.P.prototype.isDirectContent=function(){var a=this.g.g[14];return null!=a?a:!1};_.P.prototype.fh=_.l(12);_.of=function(a,b){var c=[];try{if(a.ua.parentNode&&a.ua.parentNode.querySelectorAll)for(var d=a.ua.parentNode.querySelectorAll("*["+b+"]"),e=0;e<d.length;++e)c.push(d[e]);return c}catch(f){return c}};_.g=_.P.prototype;_.g.getEscapedQemQueryId=function(){return this.g.getEscapedQemQueryId()};_.g.getEscapedGwsQueryId=function(){return this.g.getEscapedGwsQueryId()};_.g.getWebProperty=function(){return this.g.getWebProperty()};_.g.getWidth=function(){return this.g.getWidth()};_.g.getHeight=function(){return this.g.getHeight()};_.g.hh=_.l(2);_.g.gh=_.l(4);_.g.kf=_.l(6);_.g.jf=_.l(8);_.g.hf=_.l(10);_.g.getSerializedAdSlotData=function(){return this.g.$()};_.g.getAdsLength=function(){return this.fd.length};_.g.getAd=function(a){return 0<=a&&a<this.fd.length&&this.fd[a].getIndex()==a?this.fd[a]:null};var qf;_.pf=function(a){a=String(a);if(/^\s*$/.test(a)?0:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/(?:"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)[\s\u2028\u2029]*(?=:|,|]|}|$)/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,"")))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);};_.rf=function(a){return(new qf(void 0)).Vc(a)};qf=function(a){this.mk=a};qf.prototype.Vc=function(a){var b=[];sf(this,a,b);return b.join("")};var sf=function(a,b,c){if(null==b)c.push("null");else{if("object"==typeof b){if(_.ea(b)){var d=b;b=d.length;c.push("[");for(var e="",f=0;f<b;f++)c.push(e),e=d[f],sf(a,a.mk?a.mk.call(d,String(f),e):e,c),e=",";c.push("]");return}if(b instanceof String||b instanceof Number||b instanceof Boolean)b=b.valueOf();else{c.push("{");f="";for(d in b)Object.prototype.hasOwnProperty.call(b,d)&&(e=b[d],"function"!=typeof e&&(c.push(f),tf(d,c),c.push(":"),sf(a,a.mk?a.mk.call(b,d,e):e,c),f=","));c.push("}");return}}switch(typeof b){case "string":tf(b,c);break;case "number":c.push((0,window.isFinite)(b)&&!(0,window.isNaN)(b)?String(b):"null");break;case "boolean":c.push(String(b));break;case "function":c.push("null");break;default:throw Error("Unknown type: "+typeof b);}}},uf={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\u000b"},vf=/\uffff/.test("\uffff")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g,tf=function(a,b){b.push('"',a.replace(vf,function(a){var b=uf[a];b||(b="\\u"+(a.charCodeAt(0)|65536).toString(16).substr(1),uf[a]=b);return b}),'"')};var wf=function(a,b){_.F(a,"message",function(a){try{var d=_.pf(a.data);d&&"auto-css"===d.googMsgType&&b(d,a)}catch(e){}})};var yf=function(a){var b;a:{var c=a.match(xf);if(c){b=Number(c[1]);var d=Number(c[2]),c=Number(c[3]);if(0<=b&&255>=b&&0<=d&&255>=d&&0<=c&&255>=c){b=[b,d,c];break a}}b=[]}if(!b.length)throw Error(a+" is not a valid RGB color");return b},zf=function(a){var b=a[0]/255,c=a[1]/255;a=a[2]/255;var d=Math.max(b,c,a),e=Math.min(b,c,a),f=0,h=0,k=.5*(d+e);d!=e&&(d==b?f=60*(c-a)/(d-e):d==c?f=60*(a-b)/(d-e)+120:d==a&&(f=60*(b-c)/(d-e)+240),h=0<k&&.5>=k?(d-e)/(2*k):(d-e)/(2-2*k));return[Math.round(f+360)%360,h,k]},xf=/^(?:rgb)?\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2})\)$/i;var Af=function(a){this.Qg=a;this.ic=[]},Bf=function(a,b){try{var c=zf(yf(a)),d=zf(yf(b)),e,f;e=.5>=c[2]?c[1]*c[2]:c[1]*(1-c[2]);f=.5>=d[2]?d[1]*d[2]:d[1]*(1-d[2]);return.15<=(c[2]-d[2])*(c[2]-d[2])+e*e+f*f-2*e*f*Math.cos(2*(c[0]/360-d[0]/360)*Math.PI)}catch(h){return!1}},Cf=function(a,b){a||(a=0);b||(b=0);return $b(a,b)},Df=function(a,b){for(var c=0;c<a.ic.length;++c)if(Sb(a.Qg,function(a){return b[a]==this.ic[c].style[a]},a))return c;return-1},Ef=function(a,b,c){for(var d={},e=0;e<a.Qg.length;++e){var f=a.Qg[e];d[f]=b[f]}b={style:d,stats:c};d=Df(a,d);0<=d?-1==a.$p(b,a.ic[d])&&(a.ic[d].stats=c):a.ic.push(b)};Af.prototype.log=function(a){for(var b=0;b<this.ic.length&&10>b;++b)_.jf("auto_css",{style:_.rf(this.ic[b]),rank:b,qid:a},1)};Af.prototype.sort=function(){var a=(0,_.y)(this.$p,this);this.ic.sort(a||$b);for(var a=[],b=0;b<this.ic.length;++b){for(var c="",d=0;d<this.Qg.length;++d)var e=this.Qg[d],c=c+(e+": "+this.ic[b].style[e]+" !important; ");a.push(c)}return a};Af.prototype.$p=function(a,b){return this.compare(a.stats,b.stats)};Af.prototype.ck=function(a,b){Ef(this,a,b)};var Ff=function(){Af.call(this,"background-color color font-family font-size font-weight line-height letter-spacing".split(" "))};_.B(Ff,Af);Ff.prototype.ck=function(a,b,c){0!=b[1]&&Bf(a.color,c.bgcolor)&&Ef(this,a,b)};Ff.prototype.compare=function(a,b){return Cf(b[1],a[1])};var Gf=function(){Af.call(this,"background-color color font-family font-size font-weight letter-spacing line-height text-transform text-shadow".split(" "))};_.B(Gf,Af);Gf.prototype.ck=function(a,b,c){0!=b[1]&&Bf(a.color,c.bgcolor)&&Ef(this,a,b)};Gf.prototype.compare=function(a,b){var c=Cf(b[3],a[3]);return 0!=c?c:Cf(b[1],a[1])};var Hf=function(){Af.call(this,["background-color","color"])};_.B(Hf,Af);Hf.prototype.ck=function(a,b){var c;if(c=a["background-color"])c=a["background-color"],c=!("rgba(0, 0, 0, 0)"==c||"transparent"==c);c&&Ef(this,a,b)};Hf.prototype.compare=function(a,b){var c=Cf(b[9],a[9]);return 0!=c?c:Cf(b[1],a[1])};var Jf=function(a,b,c){_.O.call(this,a,b,c);for(a=0;a<If.length;a++)this.Fd(If[a])};_.B(Jf,_.O);var If=[1,2,3,4,8,6,9],Lf=function(a,b){var c=Kf,d={};if(!b)return null;d[0]=[b];for(var e in c){var f=He[e],h=d,k=_.Xc(window.document,null,c[e],b);h[f]=[];for(var m=0;m<k.length;m++)h[f].push(k[m])}return new Jf(d,b,a)};Jf.prototype.Qm=function(a){return _.Xe(this,a)||4==a};var Mf=function(a){var b=a.g[18];if(null!=b&&b)for(a=_.ka(a.g,19),b=0;b<a.length;b++)_.jd(_.M,a[b],void 0)};var Nf=function(a,b){var c=b.g[31];0==(null!=c?c:0)?(a.style.width=b.getWidth()+"px",a.style.height=b.getHeight()+"px"):(a.style.width="100%",a.style.height="100%");a.style.position="absolute";a.style.top="0";a.style.left="0";a.style.overflow="hidden"},Of=function(a){var b="";_.md(a,function(a,d){if(0===a||a)b+="&"+_.ba(d)+"="+_.ba(a)});return b},Pf="UNKNOWN",Qf="UNKNOWN",Rf=null,Sf=function(a,b){var c="//pagead2.googlesyndication.com"+("/pagead/gen_204?id=glaurung"+Of({gqid:Pf,qqid:Qf,com:a})+Of(b)),c=c.substring(0,2E3);_.jd(_.M,c,void 0)},Kf={mg:"ad-title",URL:"ad-url",kg:"ad-body",jg:"ad-button",FAVICON:"ad-favicon",lg:"ad-image",oi:"ad-price",ri:"ad-reviews",li:"ad-app-store-image",pi:"ad-promo-headline",fl:"ad-app-icon",ni:"ad-image-gallery",mi:"ad-background",hl:"ad-logo",dl:"ad-advertiser",gl:"ad-call-to-action",VIDEO:"ad-video"},Tf=function(a,b,c){var d=a.g;_.x(window.initSFVideoFlags)&&(window.initSFVideoFlags(d),a.registerFinalizeCallback(function(){_.x(window.AFMA_ReceiveMessage)&&window.AFMA_ReceiveMessage("onshow",{})}));var e=cb(d);e&&Kb(e)&&(Kf={mg:"title-link",URL:"url-link",kg:"body-link",jg:"button-link",FAVICON:"favicon-link",lg:"image-link",oi:"price",ri:"reviews",li:"app-store",pi:"promo-headline",fl:"app-icon",ni:"image-gallery",mi:"background",hl:"logo",dl:"advertiser",gl:"call-to-action",VIDEO:"video"});e=b.getElementById("adunit");b=b.getElementById("ads");if(!e||!b)return 1;Nf(e,d);try{c(b,a)}catch(h){return Xa(d)&&(Rf=h),2}for(c=0;c<_.la(d.g,0);c++){b=d.getAds(c);var e="taw"+b.getIndex(),f=window.document.getElementById(e);if(!f)return 3;f=Lf(b,f);if(!f)return 1;window.registerAd&&window.registerAd(f,e);wb(b)&&window.initAppPromo&&window.initAppPromo(f);Mf(b);a.kl(f)}return 0};var Uf=function(a,b,c){var d=[];d[0]=[c];d[15]=[b];(b=window.document.getElementById("button_15click_anchor"))&&d[15].push(b);(b=window.document.getElementById("abgc"))&&(d[27]=[b]);(b=window.document.getElementById("cbc"))&&(d[28]=[b]);_.O.call(this,d,c,a);this.Fd(15)};_.B(Uf,_.O);var Vf=function(a,b){var c={};c[0]=[b];_.O.call(this,c,b,a);this.Fd(0)};_.B(Vf,_.O);var Xf=function(a,b,c){_.O.call(this,a,b,c);for(a=0;a<Wf.length;a++)this.Fd(Wf[a])};_.B(Xf,_.O);var Wf=[1,2,4,5,7,8,3,9,6,14,15],Yf={mg:"headline",kg:"description",jg:"button",bu:"logo",lg:"product"};var $f=function(a,b,c){_.O.call(this,a,b,c);for(a=0;a<Zf.length;a++)this.Fd(Zf[a]);this.listen(4,"mouseover",(0,_.y)(this.modifyCssClass,this,0,"onhoverbg",!1));this.listen(4,"mouseout",(0,_.y)(this.modifyCssClass,this,0,"onhoverbg",!0))};_.B($f,_.O);var Zf=[1,2,4,5,7,8,3,9,6,14,15,34,26,24],ag={mg:"rhtitle",kg:"rhbody",URL:"rhurl",jg:"rhbutton",FAVICON:"rhfavicon",Wt:"rhaddress",lg:"rhimage",uu:"rhimagetemplate",ni:"rhimagegallery",Mu:"rhviewimagegallery",au:"rhcloseimagegalleryview",Ju:"rhtrydemobutton",$t:"rhclosetrydemoview",ku:"rhimage-container",tu:"rhexpand-button",ru:"rhimage-collapsed",mi:"rhbackground",cu:"rh-icore-empty",Hu:"rhsitelink",Du:"rhradlink",yu:"rh-multiframe",Zt:"rh-box-breadcrumbs",Xt:"rh-ms-mute-overlay",Bu:"rh-ms-mute-undo",ri:"rhstarratings",li:"rhstoreicon",pi:"rhpromotext",oi:"rhprice",Yt:"abgc",Au:"cbc",hu:"rhdemocountdowntimer",lu:"rhoverlap-imagegallery",mu:"rhoverlap-trydemo"},bg=function(a){var b={};b[0]=[a];for(var c in ag){var d=He[c],e=b,f=_.Xc(window.document,null,ag[c],a);e[d]=[];for(var h=0;h<f.length;h++)e[d].push(f[h])}return b};$f.prototype.Qm=function(a){return _.Xe(this,a)||4==a};var cg=function(a,b,c,d){$f.call(this,a,b,c);(!_.J||_.Lc("10"))&&window.getComputedStyle&&window.postMessage&&(this.Go=[],this.Ap={},this.tA={},this.Iv=this.FA=!1,this.A=d)};_.B(cg,$f);cg.prototype.Qs=function(){wf(window,(0,_.y)(this.gx,this));var a={};a.request=window.name;var b=window.top;a.googMsgType="auto-css";b.postMessage(_.rf(a),"*")};cg.prototype.gx=function(a){if(!this.FA||this.Iv)if(a=a.styles)for(var b=0;b<this.Go.length;++b){var c=this.Go[b];if(this.has(c)){var d=this.Ap[c],e={};e.bgcolor=We(this,c);c=e;for(e=0;e<a.length;++e){var f=a[e];d.ck(f.style,f.stats,c)}d.sort();d.log(this.A.getEscapedQemQueryId())}}};var dg=function(a,b,c,d){c&&(a.Go.push(b),a.Ap[b]=c,a.tA[b]=d)};_.P.prototype.forEachAd=_.P.prototype.forEachAd;_.P.prototype.addAd=_.P.prototype.kl;_.P.prototype.finalize=_.P.prototype.em;_.P.prototype.registerFinalizeCallback=_.P.prototype.registerFinalizeCallback;_.P.prototype.listenOnContainer=_.P.prototype.listenOnContainer;_.P.prototype.unlistenOnContainer=_.P.prototype.unlistenOnContainer;_.P.prototype.registerWidget=_.P.prototype.registerWidget;_.P.prototype.resetAll=_.P.prototype.resetAll;_.P.prototype.showOnly=_.P.prototype.showOnly;_.P.prototype.isDirectContent=_.P.prototype.isDirectContent;_.P.prototype.getEscapedQemQueryId=_.P.prototype.getEscapedQemQueryId;_.P.prototype.getEscapedGwsQueryId=_.P.prototype.getEscapedGwsQueryId;_.P.prototype.getWebProperty=_.P.prototype.getWebProperty;_.P.prototype.getAdsLength=_.P.prototype.getAdsLength;_.P.prototype.getAd=_.P.prototype.getAd;_.P.prototype.listenOnObject=_.P.prototype.listenOnObject;_.P.prototype.unlistenOnObject=_.P.prototype.unlistenOnObject;_.P.prototype.fireOnObject=_.P.prototype.fireOnObject;_.P.prototype.getSerializedAdSlotData=_.P.prototype.getSerializedAdSlotData;_.r("buildAdSlot",function(a){a=new _.P(null,[],new _.Ea(a));_.r("adSlot",a,void 0);return a},void 0);_.O.prototype.modifyCssClass=_.O.prototype.modifyCssClass;_.O.prototype.has=_.O.prototype.has;_.O.prototype.listen=_.O.prototype.listen;_.O.prototype.unlisten=_.O.prototype.unlisten;_.O.prototype.registerClickUrlModifier=_.O.prototype.registerClickUrlModifier;_.O.prototype.hide=_.O.prototype.hide;_.O.prototype.reset=_.O.prototype.reset;_.O.prototype.forEachAdPiece=_.O.prototype.forEachAdPiece;_.O.prototype.getAttribute=_.O.prototype.getAttribute;_.O.prototype.setAttribute=_.O.prototype.setAttribute;_.O.prototype.removeAttribute=_.O.prototype.removeAttribute;_.O.prototype.getBoundingClientRect=_.O.prototype.getBoundingClientRect;_.O.prototype.creativeConversionUrl=_.O.prototype.creativeConversionUrl;_.O.prototype.adGroupCreativeId=_.O.prototype.adGroupCreativeId;_.O.prototype.redirectUrl=_.O.prototype.redirectUrl;_.O.prototype.finalDestinationUrl=_.O.prototype.Ac;_.O.prototype.getIndex=_.O.prototype.getIndex;_.O.prototype.listenOnObject=_.O.prototype.listenOnObject;_.O.prototype.unlistenOnObject=_.O.prototype.unlistenOnObject;_.O.prototype.fireOnObject=_.O.prototype.fireOnObject;_.O.prototype.navigationAdPieces=_.O.prototype.navigationAdPieces;_.O.prototype.queueOnObjectAfterClickModifiers=_.O.prototype.queueOnObjectAfterClickModifiers;_.r("buildGlaurungAds",function(a,b,c){var d=(new Date).getTime(),e=1,f=!1;Rf=null;try{f=Xa(a.g),Pf=a.getEscapedGwsQueryId(),Qf=a.getEscapedQemQueryId(),e=Tf(a,b,c)}catch(h){f&&(Rf=h),e=1}a=(new Date).getTime();b={};b.r=e;b.d=a-d;Sf("bridge",b);return e},void 0);_.r("glaurungError",function(){return Rf},void 0);_.r("glaurungBridge.log",Sf,void 0);_.r("glaurungBridge.getGlaurungAdPieceClassNames",function(){return{TITLE:Kf.mg,URL:Kf.URL,BODY:Kf.kg,ACTION_BUTTON:Kf.jg,FAVICON:Kf.FAVICON,IMAGE_EXTENSION:Kf.lg,PRICE:Kf.oi,REVIEWS:Kf.ri,APP_STORE_IMAGE:Kf.li,PROMO_HEADLINE:Kf.pi,APP_ICON:Kf.fl,IMAGE_GALLERY:Kf.ni,BACKGROUND_ACTION_AREA:Kf.mi,LOGO:Kf.hl,ADVERTISER:Kf.dl,CALL_TO_ACTION:Kf.gl,VIDEO:Kf.VIDEO}},void 0);_.r("buildImageAd",function(a,b){if(0>b||b>=_.la(a.g.g,0))return null;var c=a.g.getAds(b),d=_.L.getElementById("google_image_div"),e=_.L.getElementById("aw0");return d&&e?new Uf(c,e,d):null},void 0);_.r("buildTemplateAd",function(a){var b;a=new _.Ja(a);var c={},d=window.document.getElementById("adContent");if(d){c[0]=[d];for(b in Yf){var e=He[b],f=c,h=_.Xc(window.document,null,Yf[b],d);f[e]=[];for(var k=0;k<h.length;k++)f[e].push(h[k])}b=new Xf(c,d,a)}else b=null;return b},void 0);_.r("buildRichmediaAd",function(a,b){if(0>b||b>=_.la(a.g.g,0))return null;var c=a.g.getAds(b),d=_.L.getElementById("google_richmedia_div");return d?new Vf(c,d):null},void 0);_.r("buildTextAd",function(a,b){var c=a.g;if(!(0>b||b>=_.la(c.g,0))){var d=null,d=eb(c).g[0];if(null!=d&&d){var e=a.g;if(0>b||b>=_.la(e.g,0))d=null;else{var d=a.g.getAds(b),f=window.document.getElementById("taw"+b);if(f)var h=bg(f),d=new cg(h,f,d,a);else d=null;d?(e=eb(e),f=e.g[2],dg(d,1,new Gf,null!=f?f:0),f=e.g[3],dg(d,2,new Ff,null!=f?f:0),f=e.g[4],dg(d,3,new Ff,null!=f?f:0),f=e.g[5],dg(d,4,new Hf,null!=f?f:0),f=e.g[6],e=d,f=null!=f?f:0,0<f?window.setTimeout((0,_.y)(e.Qs,e),f):e.Qs()):d=null}}else 0>b||b>=_.la(a.g.g,0)?d=null:(d=a.g.getAds(b),(e=window.document.getElementById("taw"+b))?(f=bg(e),d=new $f(f,e,d)):d=null);d&&(window.registerAd&&window.registerAd(d,"taw"+b),a.kl(d),c=c.getAds(b),e=c.g[11],null!=e&&e&&window.registerAdPing&&window.registerAdPing(d),null!=Cb(c).g[2]&&window.init_ctc&&(e=Cb(c),null!=e.g[1]?(f=e.g[1],window.init_ctc_gv(d,e.dj(),null!=f?f:"",Eb(e))):window.init_ctc(d,e.dj(),Eb(e))),wb(c)&&window.initAppPromo&&window.initAppPromo(d))}},void 0);_.r("buildAutoCssBodySorter",function(){return new Ff},void 0);_.r("buildAutoCssTitleSorter",function(){return new Gf},void 0);_.r("buildAutoCssButtonSorter",function(){return new Hf},void 0);if(_.L&&_.L.URL){var gd=_.L.URL,eg=!(gd&&0<hd().length);_.ef.zo=eg};_.fg=function(a){if(a.classList)return a.classList;a=a.className;return _.v(a)&&a.match(/\S+/g)||[]};_.gg=function(a,b){return a.classList?a.classList.contains(b):_.Vb(_.fg(a),b)};_.hg=function(a,b){a.classList?a.classList.add(b):_.gg(a,b)||(a.className+=0<a.className.length?" "+b:b)};_.ig=function(a){this.za=a};_.jg=/\s*;\s*/;_.g=_.ig.prototype;_.g.set=function(a,b,c,d,e,f){if(/[;=\s]/.test(a))throw Error('Invalid cookie name "'+a+'"');if(/[;\r\n]/.test(b))throw Error('Invalid cookie value "'+b+'"');_.q(c)||(c=-1);e=e?";domain="+e:"";d=d?";path="+d:"";f=f?";secure":"";c=0>c?"":0==c?";expires="+(new Date(1970,1,1)).toUTCString():";expires="+(new Date((0,_.A)()+1E3*c)).toUTCString();this.za.cookie=a+"="+b+e+d+c+f};_.g.get=function(a,b){for(var c=a+"=",d=(this.za.cookie||"").split(_.jg),e=0,f;f=d[e];e++){if(0==f.lastIndexOf(c,0))return f.substr(c.length);if(f==a)return""}return b};_.g.remove=function(a,b,c){var d=this.Ua(a);this.set(a,"",0,b,c);return d};_.g.zb=function(){return _.kg(this).keys};_.g.Z=function(){return _.kg(this).values};_.g.Cb=_.l(41);_.g.ra=_.l(28);_.g.Ua=function(a){return _.q(this.get(a))};_.g.clear=_.l(23);_.kg=function(a){a=(a.za.cookie||"").split(_.jg);for(var b=[],c=[],d,e,f=0;e=a[f];f++)d=e.indexOf("="),-1==d?(b.push(""),c.push(e)):(b.push(e.substring(0,d)),c.push(e.substring(d+1)));return{keys:b,values:c}};_.lg=new _.ig(window.document);_.lg.QB=3950;})(window.hydra=window.hydra||{});
module.exports = { siteMetadata: { title: `Gatsby Default Starter`, description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`, author: `@gatsbyjs`, }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `markdown-pages`, path: `${__dirname}/src/markdown-pages`, }, }, `gatsby-transformer-remark`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#663399`, theme_color: `#663399`, display: `minimal-ui`, icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline // `gatsby-plugin-offline`, ], }
// flow-typed signature: f774286d0767c4c3567504beb8d21333 // flow-typed version: <<STUB>>/eslint-plugin-promise_v4.0.1/flow_v0.91.0 /** * This is an autogenerated libdef stub for: * * 'eslint-plugin-promise' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'eslint-plugin-promise' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'eslint-plugin-promise/rules/always-return' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/avoid-new' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/catch-or-return' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/get-docs-url' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/has-promise-callback' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/is-callback' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/is-inside-callback' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/is-inside-promise' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/is-named-callback' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/is-promise' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/promise-statics' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-callback-in-promise' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-native' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-nesting' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-new-statics' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-promise-in-callback' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-return-in-finally' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-return-wrap' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/param-names' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/prefer-await-to-callbacks' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/prefer-await-to-then' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/valid-params' { declare module.exports: any; } // Filename aliases declare module 'eslint-plugin-promise/index' { declare module.exports: $Exports<'eslint-plugin-promise'>; } declare module 'eslint-plugin-promise/index.js' { declare module.exports: $Exports<'eslint-plugin-promise'>; } declare module 'eslint-plugin-promise/rules/always-return.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/always-return'>; } declare module 'eslint-plugin-promise/rules/avoid-new.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/avoid-new'>; } declare module 'eslint-plugin-promise/rules/catch-or-return.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/catch-or-return'>; } declare module 'eslint-plugin-promise/rules/lib/get-docs-url.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/get-docs-url'>; } declare module 'eslint-plugin-promise/rules/lib/has-promise-callback.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/has-promise-callback'>; } declare module 'eslint-plugin-promise/rules/lib/is-callback.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/is-callback'>; } declare module 'eslint-plugin-promise/rules/lib/is-inside-callback.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/is-inside-callback'>; } declare module 'eslint-plugin-promise/rules/lib/is-inside-promise.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/is-inside-promise'>; } declare module 'eslint-plugin-promise/rules/lib/is-named-callback.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/is-named-callback'>; } declare module 'eslint-plugin-promise/rules/lib/is-promise.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/is-promise'>; } declare module 'eslint-plugin-promise/rules/lib/promise-statics.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/promise-statics'>; } declare module 'eslint-plugin-promise/rules/no-callback-in-promise.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-callback-in-promise'>; } declare module 'eslint-plugin-promise/rules/no-native.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-native'>; } declare module 'eslint-plugin-promise/rules/no-nesting.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-nesting'>; } declare module 'eslint-plugin-promise/rules/no-new-statics.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-new-statics'>; } declare module 'eslint-plugin-promise/rules/no-promise-in-callback.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-promise-in-callback'>; } declare module 'eslint-plugin-promise/rules/no-return-in-finally.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-return-in-finally'>; } declare module 'eslint-plugin-promise/rules/no-return-wrap.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-return-wrap'>; } declare module 'eslint-plugin-promise/rules/param-names.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/param-names'>; } declare module 'eslint-plugin-promise/rules/prefer-await-to-callbacks.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/prefer-await-to-callbacks'>; } declare module 'eslint-plugin-promise/rules/prefer-await-to-then.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/prefer-await-to-then'>; } declare module 'eslint-plugin-promise/rules/valid-params.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/valid-params'>; }
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyExportExpressionDependency = require("./HarmonyExportExpressionDependency"); const HarmonyExportHeaderDependency = require("./HarmonyExportHeaderDependency"); const HarmonyExportSpecifierDependency = require("./HarmonyExportSpecifierDependency"); const HarmonyExportImportedSpecifierDependency = require("./HarmonyExportImportedSpecifierDependency"); const HarmonyImportDependency = require("./HarmonyImportDependency"); const HarmonyModulesHelpers = require("./HarmonyModulesHelpers"); module.exports = class HarmonyExportDependencyParserPlugin { apply(parser) { parser.plugin("export", statement => { const dep = new HarmonyExportHeaderDependency(statement.declaration && statement.declaration.range, statement.range); dep.loc = Object.create(statement.loc); dep.loc.index = -1; parser.state.current.addDependency(dep); return true; }); parser.plugin("export import", (statement, source) => { const dep = new HarmonyImportDependency(source, HarmonyModulesHelpers.getNewModuleVar(parser.state, source), statement.range); dep.loc = Object.create(statement.loc); dep.loc.index = -1; parser.state.current.addDependency(dep); parser.state.lastHarmonyImport = dep; return true; }); parser.plugin("export expression", (statement, expr) => { const dep = new HarmonyExportExpressionDependency(parser.state.module, expr.range, statement.range); dep.loc = Object.create(statement.loc); dep.loc.index = -1; parser.state.current.addDependency(dep); return true; }); parser.plugin("export declaration", statement => {}); parser.plugin("export specifier", (statement, id, name, idx) => { const rename = parser.scope.renames[`$${id}`]; let dep; const harmonyNamedExports = parser.state.harmonyNamedExports = parser.state.harmonyNamedExports || new Set(); harmonyNamedExports.add(name); if(rename === "imported var") { const settings = parser.state.harmonySpecifier[`$${id}`]; dep = new HarmonyExportImportedSpecifierDependency(parser.state.module, settings[0], settings[1], settings[2], name, harmonyNamedExports, null); } else { const immutable = statement.declaration && isImmutableStatement(statement.declaration); const hoisted = statement.declaration && isHoistedStatement(statement.declaration); dep = new HarmonyExportSpecifierDependency(parser.state.module, id, name, !immutable || hoisted ? -2 : (statement.range[1] + 0.5), immutable); } dep.loc = Object.create(statement.loc); dep.loc.index = idx; parser.state.current.addDependency(dep); return true; }); parser.plugin("export import specifier", (statement, source, id, name, idx) => { const harmonyNamedExports = parser.state.harmonyNamedExports = parser.state.harmonyNamedExports || new Set(); let harmonyStarExports = null; if(name) { harmonyNamedExports.add(name); } else { harmonyStarExports = parser.state.harmonyStarExports = parser.state.harmonyStarExports || []; } const dep = new HarmonyExportImportedSpecifierDependency(parser.state.module, parser.state.lastHarmonyImport, HarmonyModulesHelpers.getModuleVar(parser.state, source), id, name, harmonyNamedExports, harmonyStarExports && harmonyStarExports.slice()); if(harmonyStarExports) { harmonyStarExports.push(dep); } dep.loc = Object.create(statement.loc); dep.loc.index = idx; parser.state.current.addDependency(dep); return true; }); } }; function isImmutableStatement(statement) { if(statement.type === "FunctionDeclaration") return true; if(statement.type === "ClassDeclaration") return true; if(statement.type === "VariableDeclaration" && statement.kind === "const") return true; return false; } function isHoistedStatement(statement) { if(statement.type === "FunctionDeclaration") return true; return false; }
import DS from 'ember-data'; import Ember from 'ember'; var Retry = DS.Model.extend({ queue: DS.attr('string'), "class": DS.attr('string'), args: DS.attr(), failed_at: DS.attr('date'), error_message: DS.attr('string'), retry: DS.attr('boolean'), retry_count: DS.attr('number'), parsed_args: Ember.computed('args', function() { return JSON.stringify(this.get('args')); }) }); export default Retry;
/** * videojs-errors * @version 3.1.0 * @copyright 2017 Brightcove, Inc. * @license Apache-2.0 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('video.js')) : typeof define === 'function' && define.amd ? define(['video.js'], factory) : (global.videojsErrors = factory(global.videojs)); }(this, (function (videojs) { 'use strict'; videojs = videojs && videojs.hasOwnProperty('default') ? videojs['default'] : videojs; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; var empty = {}; var empty$1 = (Object.freeze || Object)({ 'default': empty }); var minDoc = ( empty$1 && empty ) || empty$1; var topLevel = typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : {}; var doccy; if (typeof document !== 'undefined') { doccy = document; } else { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } } var document_1 = doccy; var FlashObj = videojs.getComponent('Flash'); var defaultDismiss = !videojs.browser.IS_IPHONE; // Video.js 5/6 cross-compatibility. var registerPlugin = videojs.registerPlugin || videojs.plugin; // Default options for the plugin. var defaults = { header: '', code: '', message: '', timeout: 45 * 1000, dismiss: defaultDismiss, progressDisabled: false, errors: { '1': { type: 'MEDIA_ERR_ABORTED', headline: 'The video download was cancelled' }, '2': { type: 'MEDIA_ERR_NETWORK', headline: 'The video connection was lost, please confirm you are ' + 'connected to the internet' }, '3': { type: 'MEDIA_ERR_DECODE', headline: 'The video is bad or in a format that cannot be played on your browser' }, '4': { type: 'MEDIA_ERR_SRC_NOT_SUPPORTED', headline: 'This video is either unavailable or not supported in this browser' }, '5': { type: 'MEDIA_ERR_ENCRYPTED', headline: 'The video you are trying to watch is encrypted and we do not know how ' + 'to decrypt it' }, 'unknown': { type: 'MEDIA_ERR_UNKNOWN', headline: 'An unanticipated problem was encountered, check back soon and try again' }, '-1': { type: 'PLAYER_ERR_NO_SRC', headline: 'No video has been loaded' }, '-2': { type: 'PLAYER_ERR_TIMEOUT', headline: 'Could not download the video' }, 'PLAYER_ERR_DOMAIN_RESTRICTED': { headline: 'This video is restricted from playing on your current domain' }, 'PLAYER_ERR_IP_RESTRICTED': { headline: 'This video is restricted at your current IP address' }, 'PLAYER_ERR_GEO_RESTRICTED': { headline: 'This video is restricted from playing in your current geographic region' }, 'FLASHLS_ERR_CROSS_DOMAIN': { headline: 'The video could not be loaded: crossdomain access denied.' } } }; var initPlugin = function initPlugin(player, options) { var monitor = void 0; var waiting = void 0; var isStalling = void 0; var listeners = []; var updateErrors = function updateErrors(updates) { options.errors = videojs.mergeOptions(options.errors, updates); // Create `code`s from errors which don't have them (based on their keys). Object.keys(options.errors).forEach(function (k) { var err = options.errors[k]; if (!err.type) { err.type = k; } }); }; // Make sure we flesh out initially-provided errors. updateErrors(); // clears the previous monitor timeout and sets up a new one var resetMonitor = function resetMonitor() { // at this point the player has recovered player.clearTimeout(waiting); if (isStalling) { isStalling = false; player.removeClass('vjs-waiting'); } // start the loading spinner if player has stalled waiting = player.setTimeout(function () { // player already has an error // or is not playing under normal conditions if (player.error() || player.paused() || player.ended()) { return; } isStalling = true; player.addClass('vjs-waiting'); }, 1000); player.clearTimeout(monitor); monitor = player.setTimeout(function () { // player already has an error // or is not playing under normal conditions if (player.error() || player.paused() || player.ended()) { return; } player.error({ code: -2, type: 'PLAYER_ERR_TIMEOUT' }); }, options.timeout); // clear out any existing player timeout // playback has recovered if (player.error() && player.error().code === -2) { player.error(null); } }; // clear any previously registered listeners var cleanup = function cleanup() { var listener = void 0; while (listeners.length) { listener = listeners.shift(); player.off(listener[0], listener[1]); } player.clearTimeout(monitor); player.clearTimeout(waiting); }; // creates and tracks a player listener if the player looks alive var healthcheck = function healthcheck(type, fn) { var check = function check() { // if there's an error do not reset the monitor and // clear the error unless time is progressing if (!player.error()) { // error if using Flash and its API is unavailable var tech = player.$('.vjs-tech'); if (tech && tech.type === 'application/x-shockwave-flash' && !tech.vjs_getProperty) { player.error({ code: -2, type: 'PLAYER_ERR_TIMEOUT' }); return; } // playback isn't expected if the player is paused if (player.paused()) { return resetMonitor(); } // playback isn't expected once the video has ended if (player.ended()) { return resetMonitor(); } } fn.call(this); }; player.on(type, check); listeners.push([type, check]); }; var onPlayStartMonitor = function onPlayStartMonitor() { var lastTime = 0; cleanup(); // if no playback is detected for long enough, trigger a timeout error resetMonitor(); healthcheck(['timeupdate', 'adtimeupdate'], function () { var currentTime = player.currentTime(); // playback is operating normally or has recovered if (currentTime !== lastTime) { lastTime = currentTime; resetMonitor(); } }); if (!options.progressDisabled) { healthcheck('progress', resetMonitor); } }; var onPlayNoSource = function onPlayNoSource() { if (!player.currentSrc()) { player.error({ code: -1, type: 'PLAYER_ERR_NO_SRC' }); } }; var onErrorHandler = function onErrorHandler() { var details = ''; var error = player.error(); var content = document_1.createElement('div'); var dialogContent = ''; // In the rare case when `error()` does not return an error object, // defensively escape the handler function. if (!error) { return; } error = videojs.mergeOptions(error, options.errors[error.code || error.type || 0]); if (error.message) { details = '<div class="vjs-attention">Mulai Sekarang Untuk Melanjutkan!</div>'+ '\n <div class="vjs-errors-message">' + player.localize(error.message) + '</div>\n </div>'; } // if (error.code === 4 && FlashObj && !FlashObj.isSupported()) { // var flashMessage = player.localize('If you are using an older browser please try upgrading or installing Flash.'); // details += '<span class="vjs-errors-flashmessage">' + flashMessage + '</span>'; // } var display = player.getChild('errorDisplay'); content.className = 'vjs-errors-dialog'; content.id = 'vjs-errors-dialog'; dialogContent = details; var closeable = display.closeable(!('dismiss' in error) || error.dismiss); // We should get a close button if (closeable) { dialogContent += '<div class="vjs-errors-ok-button-container">\n <button class="vjs-errors-ok-button">' + this.localize('DAFTAR') + '</button>\n </div>'; content.innerHTML = dialogContent; display.fillWith(content); // Get the close button inside the error display display.contentEl().firstChild.appendChild(display.getChild('closeButton').el()); var okButton = display.el().querySelector('.vjs-errors-ok-button'); player.on(okButton, 'click', function () { window.location.replace("https://www.cilsy.id/member/signup"); }); } else { content.innerHTML = dialogContent; display.fillWith(content); } if (player.currentWidth() <= 600 || player.currentHeight() <= 250) { display.addClass('vjs-xs'); } display.one('modalclose', function () { return player.error(null); }); }; var onDisposeHandler = function onDisposeHandler() { cleanup(); player.removeClass('vjs-errors'); player.off('play', onPlayStartMonitor); player.off('play', onPlayNoSource); player.off('dispose', onDisposeHandler); player.off(['aderror', 'error'], onErrorHandler); }; var reInitPlugin = function reInitPlugin(newOptions) { onDisposeHandler(); initPlugin(player, videojs.mergeOptions(defaults, newOptions)); }; reInitPlugin.extend = function (errors) { return updateErrors(errors); }; reInitPlugin.getAll = function () { return videojs.mergeOptions(options.errors); }; reInitPlugin.disableProgress = function (disabled) { options.progressDisabled = disabled; onPlayStartMonitor(); }; player.on('play', onPlayStartMonitor); player.on('play', onPlayNoSource); player.on('dispose', onDisposeHandler); player.on(['aderror', 'error'], onErrorHandler); player.ready(function () { player.addClass('vjs-errors'); }); player.errors = reInitPlugin; }; var errors = function errors(options) { initPlugin(this, videojs.mergeOptions(defaults, options)); }; ['extend', 'getAll', 'disableProgress'].forEach(function (k) { errors[k] = function () { videojs.log.warn('The errors.' + k + '() method is not available until the plugin has been initialized!'); }; }); // Register the plugin with video.js. registerPlugin('errors', errors); return errors; })));
import React from 'react' import {Hero} from "./hero"; import {CallToActionGrid} from "./callToActionGrid"; export const SliceZone = ({body}) => { return ( <div> {body.map((bodyContent, i) => { if (bodyContent.type === 'hero2') { return ( <Hero key={i} backgroundImage={bodyContent.primary.background_image.url} title={bodyContent.primary.hero_title} content={bodyContent.primary.hero_content} /> ) } else if (bodyContent.type === 'call_to_action_grid') { return ( <CallToActionGrid key={i} callToActionGrid={bodyContent.fields} title={bodyContent.primary.section_title} /> ) } else { return null } })} </div> ) }
// # Settings API // RESTful API for the Setting resource var _ = require('lodash'), dataProvider = require('../models'), Promise = require('bluebird'), config = require('../config'), canThis = require('../permissions').canThis, errors = require('../errors'), utils = require('./utils'), docName = 'settings', settings, updateSettingsCache, settingsFilter, filterPaths, readSettingsResult, settingsResult, canEditAllSettings, populateDefaultSetting, hasPopulatedDefaults = false, /** * ## Cache * Holds cached settings * @private * @type {{}} */ settingsCache = {}; /** * ### Update Settings Cache * Maintain the internal cache of the settings object * @public * @param settings * @returns {Settings} */ updateSettingsCache = function (settings) { settings = settings || {}; if (!_.isEmpty(settings)) { _.map(settings, function (setting, key) { settingsCache[key] = setting; }); return Promise.resolve(settingsCache); } return dataProvider.Settings.findAll() .then(function (result) { settingsCache = readSettingsResult(result.models); return settingsCache; }); }; // ## Helpers /** * ### Settings Filter * Filters an object based on a given filter object * @private * @param settings * @param filter * @returns {*} */ settingsFilter = function (settings, filter) { return _.object(_.filter(_.pairs(settings), function (setting) { if (filter) { return _.some(filter.split(','), function (f) { return setting[1].type === f; }); } return true; })); }; /** * ### Filter Paths * Normalizes paths read by require-tree so that the apps and themes modules can use them. Creates an empty * array (res), and populates it with useful info about the read packages like name, whether they're active * (comparison with the second argument), and if they have a package.json, that, otherwise false * @private * @param {object} paths as returned by require-tree() * @param {array/string} active as read from the settings object * @returns {Array} of objects with useful info about apps / themes */ filterPaths = function (paths, active) { var pathKeys = Object.keys(paths), res = [], item; // turn active into an array (so themes and apps can be checked the same) if (!Array.isArray(active)) { active = [active]; } _.each(pathKeys, function (key) { //do not include hidden files or _messages if (key.indexOf('.') !== 0 && key !== '_messages' && key !== 'README.md' ) { item = { name: key }; if (paths[key].hasOwnProperty('package.json')) { item.package = paths[key]['package.json']; } else { item.package = false; } if (_.indexOf(active, key) !== -1) { item.active = true; } res.push(item); } }); return res; }; /** * ### Read Settings Result * @private * @param settingsModels * @returns {Settings} */ readSettingsResult = function (settingsModels) { var settings = _.reduce(settingsModels, function (memo, member) { if (!memo.hasOwnProperty(member.attributes.key)) { memo[member.attributes.key] = member.attributes; } return memo; }, {}), themes = config.paths.availableThemes, apps = config.paths.availableApps, res; if (settings.activeTheme && themes) { res = filterPaths(themes, settings.activeTheme.value); settings.availableThemes = { key: 'availableThemes', value: res, type: 'theme' }; } if (settings.activeApps && apps) { res = filterPaths(apps, JSON.parse(settings.activeApps.value)); settings.availableApps = { key: 'availableApps', value: res, type: 'app' }; } return settings; }; /** * ### Settings Result * @private * @param settings * @param type * @returns {{settings: *}} */ settingsResult = function (settings, type) { var filteredSettings = _.values(settingsFilter(settings, type)), result = { settings: filteredSettings, meta: {} }; if (type) { result.meta.filters = { type: type }; } return result; }; /** * ### Populate Default Setting * @private * @param key * @param type * @returns Promise(Setting) */ populateDefaultSetting = function (key) { // Call populateDefault and update the settings cache return dataProvider.Settings.populateDefault(key).then(function (defaultSetting) { // Process the default result and add to settings cache var readResult = readSettingsResult([defaultSetting]); // Add to the settings cache return updateSettingsCache(readResult).then(function () { // Try to update theme with the new settings // if we're in the middle of populating, this might not work return config.theme.update(settings, config.url).then(function () { return; }, function () { return; }); }).then(function () { // Get the result from the cache with permission checks }); }).catch(function (err) { // Pass along NotFoundError if (typeof err === errors.NotFoundError) { return Promise.reject(err); } // TODO: Different kind of error? return Promise.reject(new errors.NotFoundError('Problem finding setting: ' + key)); }); }; /** * ### Can Edit All Settings * Check that this edit request is allowed for all settings requested to be updated * @private * @param settingsInfo * @returns {*} */ canEditAllSettings = function (settingsInfo, options) { var checkSettingPermissions = function (setting) { if (setting.type === 'core' && !(options.context && options.context.internal)) { return Promise.reject( new errors.NoPermissionError('Attempted to access core setting from external request') ); } return canThis(options.context).edit.setting(setting.key).catch(function () { return Promise.reject(new errors.NoPermissionError('You do not have permission to edit settings.')); }); }, checks = _.map(settingsInfo, function (settingInfo) { var setting = settingsCache[settingInfo.key]; if (!setting) { // Try to populate a default setting if not in the cache return populateDefaultSetting(settingInfo.key).then(function (defaultSetting) { // Get the result from the cache with permission checks return checkSettingPermissions(defaultSetting); }); } return checkSettingPermissions(setting); }); return Promise.all(checks); }; /** * ## Settings API Methods * * **See:** [API Methods](index.js.html#api%20methods) */ settings = { /** * ### Browse * @param options * @returns {*} */ browse: function browse(options) { // First, check if we have populated the settings from default-settings yet if (!hasPopulatedDefaults) { return dataProvider.Settings.populateDefaults().then(function () { hasPopulatedDefaults = true; return settings.browse(options); }); } options = options || {}; var result = settingsResult(settingsCache, options.type); // If there is no context, return only blog settings if (!options.context) { return Promise.resolve(_.filter(result.settings, function (setting) { return setting.type === 'blog'; })); } // Otherwise return whatever this context is allowed to browse return canThis(options.context).browse.setting().then(function () { // Omit core settings unless internal request if (!options.context.internal) { result.settings = _.filter(result.settings, function (setting) { return setting.type !== 'core'; }); } return result; }); }, /** * ### Read * @param options * @returns {*} */ read: function read(options) { if (_.isString(options)) { options = { key: options }; } var getSettingsResult = function () { var setting = settingsCache[options.key], result = {}; result[options.key] = setting; if (setting.type === 'core' && !(options.context && options.context.internal)) { return Promise.reject( new errors.NoPermissionError('Attempted to access core setting from external request') ); } if (setting.type === 'blog') { return Promise.resolve(settingsResult(result)); } return canThis(options.context).read.setting(options.key).then(function () { return settingsResult(result); }, function () { return Promise.reject(new errors.NoPermissionError('You do not have permission to read settings.')); }); }; // If the setting is not already in the cache if (!settingsCache[options.key]) { // Try to populate the setting from default-settings file return populateDefaultSetting(options.key).then(function () { // Get the result from the cache with permission checks return getSettingsResult(); }); } // Get the result from the cache with permission checks return getSettingsResult(); }, /** * ### Edit * Update properties of a post * @param {{settings: }} object Setting or a single string name * @param {{id (required), include,...}} options (optional) or a single string value * @return {Promise(Setting)} Edited Setting */ edit: function edit(object, options) { options = options || {}; var self = this, type; // Allow shorthand syntax where a single key and value are passed to edit instead of object and options if (_.isString(object)) { object = { settings: [{ key: object, value: options }]}; } //clean data _.each(object.settings, function (setting) { if (!_.isString(setting.value)) { setting.value = JSON.stringify(setting.value); } }); type = _.find(object.settings, function (setting) { return setting.key === 'type'; }); if (_.isObject(type)) { type = type.value; } object.settings = _.reject(object.settings, function (setting) { return setting.key === 'type' || setting.key === 'availableThemes' || setting.key === 'availableApps'; }); return canEditAllSettings(object.settings, options).then(function () { return utils.checkObject(object, docName).then(function (checkedData) { options.user = self.user; return dataProvider.Settings.edit(checkedData.settings, options); }).then(function (result) { var readResult = readSettingsResult(result); return updateSettingsCache(readResult).then(function () { return config.theme.update(settings, config.url); }).then(function () { return settingsResult(readResult, type); }); }); }); } }; module.exports = settings; module.exports.updateSettingsCache = updateSettingsCache;
import { h, Component } from 'preact' // eslint-disable-line no-unused-vars import { connect } from 'preact-redux' import style from './style.css' class ENVTable extends Component { isHighlight (env) { const serviceDescription = this.props.selectedServiceDescriptions[this.props.selectedServiceDescriptionIndex] if (serviceDescription) { return serviceDescription.envVars[env.name] } return false } getEnvs () { const envs = [] const envMap = new Map() for (const serviceDescription of this.props.selectedServiceDescriptions) { const { envVars } = serviceDescription for (const key of Object.keys(envVars)) { if (!envMap.has(key)) { envMap.set(key, envVars[key]) } } } for (const [key, value] of envMap) { envs.push({ name: key, ...value }) } return envs } render (props, state) { const envs = this.getEnvs() if (envs.length === 0) { return null } return ( <div className="full-width"> <h2 className="ui header">ENV Vars</h2> <table className="ui fixed table"> <thead> <tr> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> {envs.map((env, i) => ( <tr className={this.isHighlight(env) ? style.active : style.inactive} key={i}> <td>{env.name}</td> <td>{env.description}</td> </tr> ))} </tbody> </table> </div> ) } } const mapStateToProps = state => ({ selectedServiceDescriptions: state.serviceDescription.selectedServiceDescriptions, selectedServiceDescriptionIndex: state.serviceDescription.selectedServiceDescriptionIndex }) export default connect( mapStateToProps, undefined )(ENVTable)
dojo.require("dojo.cal.iCalendar");dojo.deprecated("dojo.icalendar","use dojo.cal.iCalendar isntead","0.5");
var a00967 = [ [ "LatencyBudget", "a00967.html#a540c495026117b9741761f1be2c1ed4d", null ], [ "LatencyBudget", "a00967.html#a6734c1771923de7b2a4ccc7a9c751d60", null ], [ "duration", "a00967.html#a4288a7bb32dea7b2f5a5b92a1117dccf", null ], [ "duration", "a00967.html#a603d2257f6a870ffc99b54cb4c152897", null ], [ "operator!=", "a00967.html#a9b22715713bc0bfc10af93eeaeda80f4", null ], [ "operator->", "a00967.html#a948a6f4576c26fe7e44c551a56f4d038", null ], [ "operator->", "a00967.html#a0147b1dea8bdb0987505033b7025470c", null ], [ "operator==", "a00967.html#a34fd669d0051ad90b89d98a323d2d96a", null ] ];
import React from "react"; import PropTypes from "prop-types"; import { Route, Switch } from "react-router-dom"; import "./styles.scss"; import Auth from "components/Auth"; import Footer from "components/Footer"; import Navigation from "components/Navigation"; import Feed from "components/Feed"; import Explore from "components/Explore"; import Search from "components/Search"; import Profile from "components/Profile"; // import EditProfile from "components/EditProfile"; const App = props => [ props.isLoggedIn ? <Navigation key={5} /> : null, props.isLoggedIn ? <PrivateRoutes key={2} /> : <PublicRoutes key={2} />, <Footer key={3} /> ]; App.propTypes = { isLoggedIn: PropTypes.bool.isRequired }; const PrivateRoutes = props => ( <Switch> <Route exact path="/" component={Feed} /> <Route path="/explore" component={Explore} /> <Route path="/search/:searchTerm" component={Search} /> <Route path="/profile" component={Profile} /> {/* <Route path="/accounts/edit" component={EditProfile} /> */} </Switch> ); const PublicRoutes = props => ( <Switch> <Route exact path="/" component={Auth} /> <Route path="/recover" render={() => "recover password"} /> </Switch> ); export default App;
/*! ========================================================= * Lucknow Wedding Studio - v1.0.0 ========================================================= * Product Page: https://www.creative-tim.com/product/paper-kit-react * Copyright 2019 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/paper-kit-react/blob/master/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import React from "react"; import { Link } from "react-router-dom"; // nodejs library that concatenates strings import classnames from "classnames"; // reactstrap components import { Collapse, NavbarBrand, Navbar, NavItem, NavLink, Nav, Container } from "reactstrap"; function ExamplesNavbar() { const [navbarColor, setNavbarColor] = React.useState("navbar-transparent"); const [navbarCollapse, setNavbarCollapse] = React.useState(false); const toggleNavbarCollapse = () => { setNavbarCollapse(!navbarCollapse); document.documentElement.classList.toggle("nav-open"); }; React.useEffect(() => { const updateNavbarColor = () => { if ( document.documentElement.scrollTop > 299 || document.body.scrollTop > 299 ) { setNavbarColor(""); } else if ( document.documentElement.scrollTop < 300 || document.body.scrollTop < 300 ) { setNavbarColor("navbar-transparent"); } }; window.addEventListener("scroll", updateNavbarColor); return function cleanup() { window.removeEventListener("scroll", updateNavbarColor); }; }); return ( <Navbar className={classnames("fixed-top", navbarColor)} color-on-scroll="300" expand="lg" > <Container> <div className="navbar-translate"> <NavbarBrand data-placement="bottom" to="/index" target="_blank" title="Coded by Creative Tim" tag={Link} > Paper Kit 2 </NavbarBrand> <button aria-expanded={navbarCollapse} className={classnames("navbar-toggler navbar-toggler", { toggled: navbarCollapse })} onClick={toggleNavbarCollapse} > <span className="navbar-toggler-bar bar1" /> <span className="navbar-toggler-bar bar2" /> <span className="navbar-toggler-bar bar3" /> </button> </div> <Collapse className="justify-content-end" navbar isOpen={navbarCollapse} > <Nav navbar> <NavItem> <NavLink to="/index" tag={Link}> <i className="nc-icon nc-layout-11" /> Components </NavLink> </NavItem> <NavItem> <NavLink href="https://demos.creative-tim.com/paper-kit-react/#/documentation?ref=pkr-examples-navbar" target="_blank" > <i className="nc-icon nc-book-bookmark" /> Documentation </NavLink> </NavItem> <NavItem> <NavLink data-placement="bottom" href="https://twitter.com/CreativeTim?ref=creativetim" target="_blank" title="Follow us on Twitter" > <i className="fa fa-twitter" /> <p className="d-lg-none">Twitter</p> </NavLink> </NavItem> <NavItem> <NavLink data-placement="bottom" href="https://www.facebook.com/CreativeTim?ref=creativetim" target="_blank" title="Like us on Facebook" > <i className="fa fa-facebook-square" /> <p className="d-lg-none">Facebook</p> </NavLink> </NavItem> <NavItem> <NavLink data-placement="bottom" href="https://www.instagram.com/CreativeTimOfficial?ref=creativetim" target="_blank" title="Follow us on Instagram" > <i className="fa fa-instagram" /> <p className="d-lg-none">Instagram</p> </NavLink> </NavItem> <NavItem> <NavLink data-placement="bottom" href="https://www.github.com/CreativeTimOfficial?ref=creativetim" target="_blank" title="Star on GitHub" > <i className="fa fa-github" /> <p className="d-lg-none">GitHub</p> </NavLink> </NavItem> </Nav> </Collapse> </Container> </Navbar> ); } export default ExamplesNavbar;
const { Schema } = require('mongoose') module.exports = new Schema({ _id: String, money: Number })
function define_pesquisa() { let pesquisa = document.getElementById("search").value; console.log(pesquisa); document.cookie = `pesquisa = ${pesquisa}`; window.location.href = "pesquisa.php"; }; function define_categoria(valor) { console.log(valor); document.cookie = `categoriaClicada = ${valor}`; window.location.href = "pesquisa.php"; }; function define_anuncio(valor) { console.log(valor); document.cookie = `anuncioClicado = ${valor}`; }; function define_proposta(valor) { console.log(valor); document.cookie = `propostaClicada = ${valor}`; };
'use strict'; // Assumption: the LED is off when the program is started var Gpio = require('../').Gpio, led = new Gpio(17, { mode: Gpio.OUTPUT, alert: true }); (function () { var startTick; // Use alerts to determine how long the LED was turned on led.on('alert', function (level, tick) { var endTick, diff; if (level == 1) { startTick = tick; } else { endTick = tick; diff = (endTick >> 0) - (startTick >> 0); // Unsigned 32 bit arithmetic console.log(diff); } }); }()); // Turn the LED on for 15 microseconds once per second setInterval(function () { led.trigger(15, 1); }, 1000);
define([], function() { var strings = { "_jP9TaPNRkCXWU4OplNcN+w": { "AriaWebPartOrSectionEnterTemplate": "{0}. Veebiosas {1} liikumiseks vajutage sisestusklahvi Enter. Veebiosa sees saate tööriistariba aktiveerida klahvidega Alt + F10. Fookuse viimiseks atribuudipaanile kasutage klahve Alt + P ning veebiosast {1} väljumiseks vajutage paoklahvi Esc. ", "CanvasZoneAriaGoToToolbar": "Fookuse viimiseks veebiossa vajutage sisestusklahvi Enter. Pärast veebiossa liikumist vajutage tagasi tööriistaribale naasmiseks paoklahvi Esc.", "CanvasZoneAriaGoToWebPart": "Veebiosa tööriistaribale liikumiseks vajutage sisestusklahvi Enter. Siia naasmiseks vajutage paoklahvi Esc.", "CanvasZoneAriaWebpartName": "Veebiosa {0}", "DeleteZoneConfirmationDialogMessage": "Kas soovite kindlasti selle jaotise ja kogu selle sisu kustutada?", "DeleteConfirmationDialogTitle": "Kustutamise kinnitus", "DeleteConfirmationDialogMessage": "Kas soovite kindlasti selle veebiosa kustutada?", "TextWebPartDisplayName": "Tekst", "ToolbarNavigationArrowKeys": "Tööriistaribal saate liikuda nooleklahvidega.", "ToolboxAriaLoadingAlert": "Tööriistakast laadib veebiosi.", "ToolboxAriaLoadingFinishedAlert": "Tööriistakast viis veebiosade laadimise lõpule.", "ToolboxErrorMessage": "Veebiosade toomisel ilmnes tõrge. Kõik veebiosad ei pruugi saadaval olla.", "ToolboxHintTitle": "Uue veebiosa lisamine", "ToolboxNavigationArrowKeys": "{0} Liikumiseks kasutage vasak- ja paremnoolt. Valitud veebiosa lisamiseks vajutage sisestusklahvi Enter.", "CanvasItems": "Tööriistaribal on {0} üksust.||Tööriistaribal on {0} üksus. ||Tööriistaribal on {0} üksust.", "CanvasItemsInterval": "0||1||2-", "ToolboxSectionHeader": "Jaotise paigutus", "ToolboxOneColumnPart": "Üks veerg", "ToolboxTwoColumnPart": "Kaks veergu", "ToolboxThreeColumnPart": "Kolm veergu", "ToolboxOneThirdRightColumnPart": "Kolmandikulaiune parem veerg", "ToolboxOneThirdLeftColumnPart": "Kolmandikulaiune vasak veerg", "ToolboxFullWidthColumnPart": "Täislaiusega jaotis", "ToolboxVerticalColumnPart": "Vertikaalne jaotis", "ToolboxVerticalColumnToolTipText": "Vertikaalset jaotist ei saa lisada, kuna see juba on olemas või lehel on täislaiusega veerg.", "ToolboxFullWidthColumnTooltipText": "Täislaiusega jaotist ei saa lisada, kuna lehel on vertikaalne jaotis.", "SectionPropertyPaneTitle": "Jaotis", "SectionPropertyPaneColumnGroupName": "Paigutussuvandid", "ToolbarSelectZone": "Vali jaotis", "WebPartAriaLabel": "veebiosa", "SectionContextualAriaLabel": "{0}, {1} jaotis, milles sisaldub {2}", "SectionAriaLabel": "jaotis", "WebPartsInSectionLabel": "{0}, {1}", "ToolboxHintSectionTitleOnlyLayouts": "Uue jaotise lisamine", "ToolboxHintTitleWithLayout": "Uue veebiosa lisamine {0}", "ToolboxHintColumnOne": "esimesse veergu", "ToolboxHintColumnTwo": "teise veergu", "ToolboxHintColumnThree": "kolmandasse veergu", "EmptySectionAriaLabel": "veebiosa pole", "SectionPositionAriaLabel": "Jaotis {0} kokku {1} jaotisest", "DeleteConfirmationLabel": "{0} on kustutatud.", "SectionBackgroundPropertyColumnGroupName": "Jaotise taust", "SectionBackgroundNeutralButtonLabel": "Neutraalne", "SectionBackgroundSoftButtonLabel": "Õrn", "SectionBackgroundStrongButtonLabel": "Tugev", "SectionBackgroundNoneButtonLabel": "Pole", "CanvasVerticalSectionZoneLabel": "Vertikaalse veerupaigutusega jaotis", "YammerHighlightsWebpartTitle": "Esiletõstud", "ToolbarDuplicateSectionTitle": "Duplicate section", "ToolbarDuplicateWebPartTitle": "Duplicate web part" }, "_n7GTqRbrtzGOgRYtCYt3Jw": { "FormattingBarMoreButtonTitle": "Rohkem", "TextWebPartPlaceholder": "Lisage tekst siia." }, "_EJ1q3VoG+8ZXJZ4MxzV0eA": { "WebpartToolbarConfigButtonTitle": "Redigeeri veebiosa", "WebpartToolbarMoveButtonTitle": "Teisalda veebiosa", "WebpartToolbarDeleteButtonTitle": "Kustuta veebiosa", "ToolboxHintTitleWithLayout": "Uue veebiosa lisamine {0}", "ToolboxHintColumnOne": "esimesse veergu", "ToolboxHintColumnTwo": "teise veergu", "ToolboxHintColumnThree": "kolmandasse veergu" }, "_kfkx9h4IuXbYoZ4SdLEjrQ": { "ZoneToolbarConfigButtonTitle": "Redigeeri jaotist", "ZoneToolbarMoveButtonTitle": "Teisalda jaotis", "ZoneToolbarDeleteButtonTitle": "Kustuta jaotis", "ToolboxNavigationArrowKeys": "{0} Liikumiseks kasutage vasak- ja paremnoolt. Valitud veebiosa lisamiseks vajutage sisestusklahvi Enter." }, "_bKMsmDAqUqbOL6h9rxYuIw": { "FormattingBarClearFormattingButtonTitle": "Eemalda kogu vorming", "FormattingBarNormalTextButtonTitle": "Tavatekst", "FormattingBarHeading2ButtonTitle": "Pealkiri 1", "FormattingBarHeading3ButtonTitle": "Pealkiri 2", "FormattingBarHeading4ButtonTitle": "Pealkiri 3", "FormattingBarQuoteButtonTitle": "Tsitaat", "ToolbarNavigationArrowKeys": "Tööriistaribal saate liikuda nooleklahvidega.", "RTESettingsText": "Teksti- ja tabelivorming", "FontDropDownText": "Fondi laad", "ParagraphGroupText": "Lõik", "FontSizeDropDownLabel": "Fondi suurus", "TableGroup": "Tabel", "InsertAndDeleteGroupLabel": "Lisamine ja kustutamine", "FontColorLabel": "Fondi värv", "StandardColorLabel": "Standardvärvid", "DefaultColorLabel": "Automaatne", "RedDarkLabel": "Tumepunane", "RedLabel": "Punane", "YellowLabel": "Kollane", "GreenLightLabel": "Heleroheline", "GreenLabel": "Roheline", "GreenDarkLabel": "Tumeroheline", "BlueLightLabel": "Helesinine", "BlueLabel": "Sinine", "BlueDarkLabel": "Tumesinine", "PurpleLabel": "Lilla", "HightlightLabel": "Esiletõstuvärv", "HightlightColorsLabel": "Esiletõstuvärvid", "PinkLabel": "Roosa", "OrangeLabel": "Oranž", "RemoveHighlightColor": "Värvita", "HyperlinkGroupLabel": "Hüperlink", "TealLabel": "Rohekassinine", "MagentaLabel": "Magenta", "AquaLabel": "Akvamariinsinine", "MaroonLabel": "Kastanpruun", "GoldLabel": "Kuldne", "GreyLabel": "Hall", "DarkGreyLabel": "Tumehall", "BlackLabel": "Must", "ThemeColorGroupLabel": "Kujunduse värvid", "ThemeDarkerLabel": "Kujunduse tumedam värv", "ThemeDarkLabel": "Kujunduse tume värv", "ThemeDarkAltLabel": "Kujunduse tume alternatiivvärv", "ThemePrimaryLabel": "Kujunduse põhivärv", "ThemeSecondaryLabel": "Kujunduse teine värv", "NeutralDarkLabel": "Neutraalne tume värv", "NeutralPrimaryLabel": "Neutraalne põhivärv", "NeutralPrimaryAltLabel": "Neutraalne esmane alternatiivvärv", "NeutralSecondaryLabel": "Neutraalne teine värv", "NeutralTertiaryLabel": "Neutraalne kolmas värv", "TableStylesGroupLabel": "Tabelilaadid", "AlignTableGroupLabel": "Tabeli joondus", "FormattingBarPreButtonTitle": "Püsisammuga", "PropertyPaneButtonAriaLabel": "Rühm {0}, {1}" }, "_UeXD60TZFDaB0+z1tiJy0w": { "CloseButtonAriaLabel": "Sule", "YesButtonLabel": "Jah", "NoButtonLabel": "Ei", "DialogDescription": "{0} dialoog {1}" }, "_+b5qGTPD+RXDByAXIV1Ykg": { "DragIconFallbackRTEText": "Tekst", "DragZoneHandleTitle": "Teisaldusrežiimi sisenemiseks vajutage sisestusklahvi Enter või tühikuklahvi", "DragZoneMoveStarted": "Ülespoole nihutamiseks vajutage ülesnooleklahvi ja allapoole nihutamiseks allanooleklahvi. Teisalduse kinnitamiseks vajutage sisestusklahvi Enter. Teisalduse tühistamiseks vajutage paoklahvi Esc.", "DragZoneMoveComplete": "Veebiosa on teisaldatud asukohast {0} asukohta {1}. ", "DragZoneMoveCompleteZone": "Jaotis on teisaldatud asukohast {0} asukohta {1}", "DragZoneMoveCancelled": "Teisaldamine on tühistatud.", "DragZoneMoveNotAllowedAriaLabel": "Selles suunas ei saa rohkem edasi liikuda või sellesse jaotisse teisaldamine pole lubatud", "DragZoneMoveNotAllowed": "Teisaldamine pole lubatud", "DragZoneMoveInsideLevelControl": "Asukoht {0}", "DragZoneMoveInsideLevelSection": "Veerg {0}, asukoht {1}", "DragZoneMoveInsideLevelZone": "Jaotis {0}, veerg {1}, asukoht {2}" }, "_aldiWWnENoBI4mn+VYF4ZA": { "Title": "Brauseriakna laiuse suurendamine", "Subtitle": "Kitsas brauseriaknas pole redigeerimine saadaval. Kui soovite edasi redigeerida, tehke brauseriaken laiemaks." }, "_/GZrHjuQO4erDQbBRI2XSA": { "DialogTitle": "Lingi lisamine", "UrlTextFieldLabel": "Aadress", "UrlTextFieldAriaLabel": "Lingitav veebiaadress", "UrlTextFieldError": "Seda lingitüüpi ei toetata.", "TitleTextFieldLabel": "Kuvatav tekst", "RecentPagesLabel": "Viimatised lehed sellel saidil", "SearchForPagesLabel": "Selle saidi lehed, mis vastavad teie otsingule", "RecentSpacesLabel": "Most recent spaces on this site", "SearchForSpacesLabel": "Spaces on this site that match your search", "NoResultLabel": "Otsingule ei vasta ükski üksus", "TryAgainLabel": "Proovige mõnda muud märksõna", "OpenLinkInNewTabLabel": "Ava link uuel vahekaardil", "SaveButtonLabel": "Salvesta", "CancelButtonLabel": "Loobu", "UnlinkButtonLabel": "Eemalda link", "TitleSuggestionsColumnName": "Pealkiri", "EditorSuggestionsColumnName": "Muutja:", "ModifiedSuggestionsColumnName": "Muudetud", "PageContentContainsSearchText": "Lehe sisust leiti \"{0}\"", "CurrentPage": "(praegune leht)", "SearchTextFieldLabel": "Otsing", "SearchPagesTextFieldPlaceholder": "Sisestage selle saidi lehtede otsimiseks märksõnad", "SearchSpacesTextFieldPlaceholder": "Enter keywords to search for spaces on this site", "DialogAriaDescription": "Saate lisada lingi praeguse saidi lehele või mõne muu saidi lehele.", "SuggestionsListAriaLabel": "Valige leht loendist \"{0}\". Lehtedel liikumiseks vajutage üles- või allanooleklahvi. Lehe valimiseks vajutage tühikuklahvi. Kui leht on valitud, kasutatakse lehe linki lingi sisestusväljal. Kui kuvatava teksti sisestusväljal teksti pole, kasutatakse lehe pealkirja.", "SaveButtonDisabledScreenReaderAlert": "Salvestamisnupp pole saadaval, kuna lisatud on sobimatu veebiaadress.", "SaveButtonEnabledScreenReaderAlert": "Salvestamisnupp on saadaval.", "PageIsSelectedScreenReaderAlert": "Valitud on leht {0}.", "IsSearching": "Otsimine...", "SearchResultsShowing": "Kuvatakse otsingutulemid. Otsingutulemite loendile liikumiseks vajutage tabeldusklahvi Tab.", "RecentPagesShowing": "Kuvatakse viimatiste lehtede loend. Viimatiste lehtede loendile liikumiseks vajutage tabeldusklahvi Tab." }, "_4SOrKBlkyRLkXWcT6txoow": { "ToolboxSearchAccessibleLabelTemplate": "Veebiosa otsimiseks tippige tekst siia. {0}", "ToolboxSearchEscapeAccessibleLabel": "Olemasoleva otsingu tühjendamiseks vajutage paoklahvi (Esc).", "ToolboxSearchLabel": "Otsing" }, "_NS+5Kf9zpnH1/LStsp+Tfw": { "ToolboxCategoryTextMediaAndContent": "Tekst, meediumid ja sisu", "ToolboxCategoryDiscovery": "Tuvastamine", "ToolboxCategoryCommunicationAndCollaboration": "Suhtlus ja koostöö", "ToolboxCategoryPlanningAndProcess": "Plaanimine ja töötlus", "ToolboxCategoryBusinessIntelligence": "Äri ja teave", "ToolboxCategorySiteTools": "Saidi tööriistad", "ToolboxCategoryConnectors": "Konnektorid", "ToolboxCategoryOther": "Muud", "ToolboxGroupNameFeatured": "Esiletõstetud", "ToolboxGroupNameAlphabetical": "Kõik A–Y", "ToolboxGroupNameSection": "Jaotise paigutus" }, "_RRzf46hnc4+fBX8RHyocNg": { "TextWebPartDisplayName": "Tekst", "TextWebpartDescription": "Siin saate teksti lisada ja vormindada" }, "_6tOZemhV08aF1IgNDNeiwQ": { "ToolboxGroupNameFullWidth": "Saate lisada ühe nendest veebiosadest sellesse täislaiuses veergu" }, "_2TT4IG31kAjRqhD0h5kPOg": { "ToolboxGroupSeeAllButtonLabel": "Kuva kõik", "ToolboxGroupSeeAllButtonAriaLabel": "Kuva kõik kategooria {0} veebiosad.", "ToolboxGroupAriaLabel": "Kategooria {0} loend. Loendis liikumiseks kasutage vasak- või paremnooleklahvi." }, "_WVn4QXYnL8WpGCqr2C9ySA": { "ToolboxCategoryAllCategory": "Kõik kategooriate kaupa", "ToolboxCategorySortingCategory": "Kogu sisu A–Y", "ToolboxCategorySearchResults": "Otsingutulemid", "ToolboxCollapseButtonDescription": "Saate suure tööriistakasti asemel kasutada väikest tööriistakasti", "NoResultLabel": "Teie otsingule vastavaid üksusi ei leitud", "TryAgainLabel": "Proovige mõnda muud märksõna", "LargeToolboxAriaTitle": "Veebiosa laiendatud tööriistakast.", "ToolboxCollapseButtonAriaLabel": "Ahenda.", "DropDownMenuAriaLabel": "Kuvatakse kategooria {0} veebiosad.", "SwitchCategoryAlert": "Muudetud kategooriaks {0}.", "BackButtonAriaLabel": "Tagasi eelmisse vaatesse." }, "_z2ZwCbA+UxeGBoG5w1HCOA": { "SearchResultAlert": "Tööriistakastis on {0} üksust.|| Tööriistakastis on {0} üksus.||Tööriistakastis on {0} üksust.", "SearchResultAlertIntervals": "0||1||2-" }, "_CZsUWMvZilAKKAfwQSdzKQ": { "ToolboxExpandButtonTitle": "Laienda suurema hulga veebiosade kuvamiseks", "ToolboxNoItemsFound": "Teie otsingule vastavaid tulemeid pole.", "ToolboxExpandButtonAriaLabel": "Laienda." }, "_acoNwVeh/QF9PsLoQfUb2A": { "FormattingBarAlignCenterButtonTitle": "Joonda keskele", "FormattingBarAlignLeftButtonTitle": "Joonda vasakule", "FormattingBarAlignRightButtonTitle": "Joonda paremale", "FormattingBarBoldButtonTitle": "Paks kiri ({0}+B)", "FormattingBarBulletListButtonTitle": "Täpploend", "FormattingBarClearFormattingButtonTitle": "Eemalda kogu vorming", "FormattingBarConfirmAction": "Toiming {0} on tehtud.", "FormattingBarConfirmActionOnSelection": "Toiming {0} on tehtud valitud tekstil: {1}", "FormattingBarNormalTextButtonTitle": "Tavatekst", "FormattingBarHeading2ButtonTitle": "Pealkiri 1", "FormattingBarHeading3ButtonTitle": "Pealkiri 2", "FormattingBarHeading4ButtonTitle": "Pealkiri 3", "FormattingBarQuoteButtonTitle": "Tsitaat", "FormattingBarItalicButtonTitle": "Kursiiv ({0}+I)", "FormattingBarLinkButtonTitle": "Hüperlink ({0}+K)", "FormattingBarNumberedListButtonTitle": "Numberloend", "FormattingBarUnderlineButtonTitle": "Allakriipsutus ({0}+U)", "FormattingBarUnlinkButtonTitle": "Eemalda link", "UndoButtonTitle": "Võta tagasi ({0}+Z)", "RedoButtonTitle": "Tee uuesti ({0}+Y)", "FormattingBarAccessibleLabel": "Vorming", "LinkDialogErrorNotSupportedLink": "Seda lingitüüpi ei toetata.", "LinkDialogTextFieldAriaLabel": "Lingitav veebiaadress", "LinkDialogTextFieldLabel": "Veebiaadress:", "LinkDialogDisplayTextFieldLabel": "Kuvatav tekst:", "LinkDialogTitle": "Lingi lisamine", "RichTextEditorAriaLabel": "Tekstiredaktor. Tööriistaribade avamiseks kasutage klahvikombinatsiooni Alt + F10.", "RichTextEditorTitle": "Tekstiredaktor", "RichTextEditorIframeTitle": "{0} {1}", "RichTextLinkDialogCancelButtonLabel": "Loobu", "RichTextLinkDialogSaveButtonLabel": "Salvesta", "RichTextNavigationAltF10Keys": "{0} {1}", "ToolbarNavigationArrowKeys": "Tööriistaribal saate liikuda nooleklahvidega.", "ToolbarNavigationTabKeys": "Ühelt tööriistaribalt teisele liikumiseks vajutage tabeldusklahvi.", "ToolbarNavigationShiftTabKey": "Tekstiväljale tagasi liikumiseks kasutage klahvikombinatsiooni Shift + Tab", "ImagesInTableNotSupported": "Pilti ei saa kleepida tabeli sisse. Proovige pilt kleepida väljapoole tabelit.", "MultiImagePasteInIENotSupported": "Tabeli sees või tekstiga mähitud pilte ei saa kleepida. Kopeerige ainult pilt, mis ei ole tabeli või tekstiga, ja proovige uuesti.", "InvalidImageSource": "Pilte ei saa kleepida, kuna allikat pole olemas või see ei sobi. Proovige kleepida mõnest muust asukohast.", "CloseWarningText": "Sule hoiatus {0} ", "LoadingText": "Kleepimine...", "AddRowAboveText": "Lisa üles", "AddRowBelowText": "Lisa alla", "DeleteRowText": "Kustuta rida", "AddColumnLeftText": "Lisa vasakule", "AddColumnRightText": "Lisa paremale", "AddRowAboveShortcutText": "{0} ({1}+Shift+A)", "AddRowBelowShortcutText": "{0} ({1}+Shift+Z)", "DeleteRowShortcutText": "{0} ({1}+Shift+D)", "StrikeThroughButtonLabel": "Läbikriipsutus", "SuperscriptButtonLabel": "Ülaindeks", "SubscriptButtonLabel": "Allindeks", "JustifyButtonLabel": "Rööpjoonda", "IncreaseIndentButtonLabel": "Suurenda taanet", "DecreaseIndentButtonLabel": "Vähenda taanet", "FontSizeDropDownLabel": "Fondi suurus", "TableTitle": "Tabel", "TableButtonLabel": "Lisa tabel", "InsertRowBeforeButtonLabel": "Lisa üles", "InsertRowAfterButtonLabel": "Lisa alla", "InsertColumnLeftButtonLabel": "Lisa vasakule", "InsertColumnRightButtonLabel": "Lisa paremale", "DeleteRowButtonLabel": "Kustuta rida", "DeleteColumnButtonLabel": "Kustuta veerg", "DeleteTableButtonLabel": "Kustuta tabel", "FontColorLabel": "Fondi värv", "HightlightLabel": "Esiletõstuvärv", "SimpleTableButtonLabel": "Lihtne", "TableWithHeaderBorderLabel": "Tagasihoidlik päis", "TableWithFilledHeaderLabel": "Päis", "TableWithBandedRowsLabel": "Vahelduvad read", "TableWithBandedRowsAndColumnsLabel": "Veerupäis", "SimpleTableButtonThemeLabel": "Kujunduse värvid, lihtne", "TableWithHeaderBorderThemeLabel": "Kujunduse värvid, päis, vaevumärgatav", "TableWithFilledHeaderThemeLabel": "Kujunduse värvid, päis", "TableWithBandedRowsThemeLabel": "Kujunduse värvid, iga teine rida", "TableWithBandedRowsAndColumnsThemeLabel": "Kujunduse värvid, veerupäis", "AlignTableLeftLabel": "Joonda tabel vasakule", "AlignTableCenterLabel": "Joonda tabel keskele", "AlignTableRightLabel": "Joonda tabel paremale", "RTEPagePickerSaveAction": "Link {0} on lisatud.", "RTEPagePickerUnlinkAction": "Link {0} on eemaldatud.", "FormattingBarPreButtonTitle": "Püsisammuga", "CommandShortcutOnMac": "⌘", "ControlShortcutOnWin": "Ctrl" }, "_1Ou/gGCxybOVkfKauk4ZuQ": { "RelativeDateTime_DayAndTime": "{0} kl {1}" }, "_a3W+FXOqBm43qmT906SM6g": { "DialogCloseButtonLabel": "Sule", "GenericErrorTitle": "Toimingut ei saanud lõpule viia ", "DialogSaveButtonLabel": "Salvesta", "DialogYesButtonLabel": "Jah", "DialogNoButtonLabel": "Ei" }, "_hMVyVJ8VXd7+VBXtkz5V0w": { "CloseButtonAriaLabel": "Sule" }, "_tkE1T1OGzhOW2Gh5iEm/nQ": { "FileTypeIconAlternateText": "{0}-fail." }, "_NAR8NFw8cblGJm9t5CjqOw": { "SuccessfullyLoadedText": "Silumismanifestid on laaditud.", "ErrorLoadingText": "Silumismanifestide laadimine nurjus: {0}" }, "_vd/LT/qfiQhbHFfeM1GtlA": { "FetchFailedError": "Veebiosade toomine nurjus tõrkega \"{0}\". Vahemällu salvestatud tööjärgu renderdamine võib nurjuda.", "CanvasInitializationError": "Lõuendi lähtestamine nurjus tõrkega \"{0}\".", "UnknownError": "Ilmnes tundmatu tõrge \"{0}\"." }, "_FQya7ZjwIyrOEutOa+omIA": { "Title": "Hoiatus", "SubText": "Teie veebiosa ei kuvata tööriistakastis. Veenduge, et \"gulp serve\" töötab veebiosaprojektis. Kui \"gulp serve\" töötab, värskendage lehte.", "OkButtonText": "OK", "ClickHerePrefix": "Klõpsake ", "ClickHereLink": "siin", "ClickHereSuffix": " lisateabe saamiseks." }, "_1JArBGDet5Uj9pJOV/9sFw": { "UrlTextBoxPlaceholder": "Sisestage mobiilieelvaate tööriistas kuvamiseks URL.", "ScreenReaderMobilePreviewEntered": "Olete avanud mobiilieelvaate tööriista. Kui soovite kuvada mõne teise lehe eelvaate, sisestage URL vastavale tekstiväljale. Tööriista sulgemiseks ja Workbenchi naasmiseks vajutage paoklahvi (Esc).", "ScreenReaderDevicePickerEntered": "Valige vasak- ja paremnooleklahvide abil seade, et muuta eelvaatekuva suurust.", "ScreenReaderDevicePickerSelectionChanged": "Selle seadme valimiseks vajutage sisestusklahvi.", "Width": "Laius", "Height": "Kõrgus" }, "_8EVKOH1av6NjR/ZNfdafrw": { "WebPartData": "Veebiosa andmed", "ClassicPages": "Klassikalised lehed", "ModernPages": "Uudsed lehed", "Close": "Sule", "WebPartDataHelpInfoLink": "Lisateavet SharePointi kliendipoolsest veebiosast pärit SharePointi varade ettevalmistuse kohta" }, "_IusqdbcSoVYQiit3+QRSxw": { "Office365Title": "Office 365", "SharePointWorkbenchTitle": "SharePoint Workbench", "ScreenReaderDisplayModeSwitchToEditMode": "Eelvaaterežiimi asemel on aktiveeritud redigeerimisrežiim.", "ScreenReaderDisplayModeSwitchToReadMode": "Redigeerimisrežiimi asemel on aktiveeritud eelvaaterežiim." }, "_nCtJlVOXBHa59LgYtajnjA": { "Save": "Salvesta", "SaveAltText": "Saate salvestada praeguse Workbenchi oleku.", "Discard": "Hülga", "DiscardAltText": "Saate hüljata praeguse Workbenchi oleku.", "Mobile": "Mobiiltelefon", "MobleAltText": "Saate avada mobiiltelefonide jaoks ette nähtud eelvaatetööriista.", "Tablet": "Tahvelarvuti", "TabletAltText": "Saate avada tahvelarvutite jaoks ette nähtud eelvaatetööriista.", "Preview": "Eelvaade", "PreviewAltText": "Saate aktiveerida redigeerimisrežiimi asemel eelvaaterežiimi.", "Edit": "Redigeeri", "EditAltText": "Saate aktiveerida redigeerimisrežiimi.", "WebPartData": "Veebiosa andmed", "WebPartDataAltText": "Serialiseeritud veebiosa andmete kuvamine." } }; strings.default = strings; return strings; });
import './App.css'; // import Header from './components/Header.jsx'; import Footer from './components/Footer.jsx'; import CakeCupCake from './components/cakecupcake.jsx'; import Nav from '../src/components/Nav'; import About from '../src/components/About'; import Contact from '../src/components/Contact'; import {BrowserRouter as Router, Switch, Route} from 'react-router-dom' function App() { return ( <Router></Router> <div> <Nav /> <About /> <Contact /> <CakeCupCake /> <Footer /> </div> ); } export default App;
/** * Copyright (c) 2019 Paul Armstrong */ module.exports = { preset: '../../config/jest.js', displayName: 'with-mariadb', testEnvironment: 'node', rootDir: './', roots: ['<rootDir>/src'] };
import React, { useState } from 'react' import { fetchPost } from '../util/fetch_helpers' const GenerateTokenForm = ({ election, setTokenData}) => { const [count, setCount] = useState(1) const [loading, setLoading] = useState(false) const onSubmit = e => { e.preventDefault() setLoading(true) fetchPost( `/api/admin/elections/${election.get('slug')}/tokens`, { count: count }) .then(res => setTokenData(res)) .catch(console.log) .then(() => setLoading(false)) } return ( <form onSubmit={onSubmit}> <label className="label">Generate tokens</label> <div className="field has-addons"> <div className="control"> <input className="input" type="number" value={count} onChange={e => setCount(e.target.value)} /> </div> <div className="control"> <button className="button is-primary" disabled={loading}> Generate </button> </div> </div> </form> ) } export default GenerateTokenForm
const {promisify} = require('util'); const {stopDaemon} = require('./'); /** Stop the Lightning daemon { lnd: <LND GRPC API Object> } */ module.exports = promisify(stopDaemon);
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @file Get initial data and define sankey view's series model * @author Deqing Li(annong035@gmail.com) */ import SeriesModel from '../../model/Series'; import createGraphFromNodeEdge from '../helper/createGraphFromNodeEdge'; import {encodeHTML} from '../../util/format'; var SankeySeries = SeriesModel.extend({ type: 'series.sankey', layoutInfo: null, /** * Init a graph data structure from data in option series * * @param {Object} option the object used to config echarts view * @return {module:echarts/data/List} storage initial data */ getInitialData: function (option) { var links = option.edges || option.links; var nodes = option.data || option.nodes; if (nodes && links) { var graph = createGraphFromNodeEdge(nodes, links, this, true); return graph.data; } }, setNodePosition: function (dataIndex, localPosition) { var dataItem = this.option.data[dataIndex]; dataItem.localX = localPosition[0]; dataItem.localY = localPosition[1]; }, /** * Return the graphic data structure * * @return {module:echarts/data/Graph} graphic data structure */ getGraph: function () { return this.getData().graph; }, /** * Get edge data of graphic data structure * * @return {module:echarts/data/List} data structure of list */ getEdgeData: function () { return this.getGraph().edgeData; }, /** * @override */ formatTooltip: function (dataIndex, multipleSeries, dataType) { // dataType === 'node' or empty do not show tooltip by default if (dataType === 'edge') { var params = this.getDataParams(dataIndex, dataType); var rawDataOpt = params.data; var html = rawDataOpt.source + ' -- ' + rawDataOpt.target; if (params.value) { html += ' : ' + params.value; } return encodeHTML(html); } else if (dataType === 'node') { var node = this.getGraph().getNodeByIndex(dataIndex); var value = node.getLayout().value; var name = this.getDataParams(dataIndex, dataType).data.name; if (value) { var html = name + ' : ' + value; } return encodeHTML(html); } return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries); }, optionUpdated: function () { var option = this.option; if (option.focusNodeAdjacency === true) { option.focusNodeAdjacency = 'allEdges'; } }, defaultOption: { zlevel: 0, z: 2, coordinateSystem: 'view', layout: null, // The position of the whole view left: '5%', top: '5%', right: '20%', bottom: '5%', // Value can be 'vertical' orient: 'horizontal', // The dx of the node nodeWidth: 20, // The vertical distance between two nodes nodeGap: 8, // Control if the node can move or not draggable: true, // Value can be 'inEdges', 'outEdges', 'allEdges', true (the same as 'allEdges'). focusNodeAdjacency: false, // The number of iterations to change the position of the node layoutIterations: 32, label: { show: true, position: 'right', color: '#000', fontSize: 12 }, levels: [], // Value can be 'left' or 'right' nodeAlign: 'justify', itemStyle: { borderWidth: 1, borderColor: '#333' }, lineStyle: { color: '#314656', opacity: 0.2, curveness: 0.5 }, emphasis: { label: { show: true }, lineStyle: { opacity: 0.6 } }, animationEasing: 'linear', animationDuration: 1000 } }); export default SankeySeries;
import { prisma } from "../../../../generated/prisma-client"; import { ROOM_FRAGMENT } from "../../../fragments"; export default { Query: { seeRooms: (_, args, { request, isAuthenticated }) => { isAuthenticated(request); const { user } = request; return prisma .rooms({ where: { participants_some: { id: user.id, }, }, }) .$fragment(ROOM_FRAGMENT); }, }, };
/*! @license * Shaka Player * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.Player'); goog.require('goog.asserts'); goog.require('shaka.Deprecate'); goog.require('shaka.log'); goog.require('shaka.media.AdaptationSetCriteria'); goog.require('shaka.media.BufferingObserver'); goog.require('shaka.media.DrmEngine'); goog.require('shaka.media.ExampleBasedCriteria'); goog.require('shaka.media.ManifestParser'); goog.require('shaka.media.MediaSourceEngine'); goog.require('shaka.media.MediaSourcePlayhead'); goog.require('shaka.media.MetaSegmentIndex'); goog.require('shaka.media.ClosedCaptionParser'); goog.require('shaka.media.PlayRateController'); goog.require('shaka.media.Playhead'); goog.require('shaka.media.PlayheadObserverManager'); goog.require('shaka.media.PreferenceBasedCriteria'); goog.require('shaka.media.RegionObserver'); goog.require('shaka.media.RegionTimeline'); goog.require('shaka.media.SegmentIndex'); goog.require('shaka.media.SrcEqualsPlayhead'); goog.require('shaka.media.StreamingEngine'); goog.require('shaka.media.TimeRangesUtils'); goog.require('shaka.net.NetworkingEngine'); goog.require('shaka.routing.Walker'); goog.require('shaka.text.SimpleTextDisplayer'); goog.require('shaka.text.TextEngine'); goog.require('shaka.text.UITextDisplayer'); goog.require('shaka.text.WebVttGenerator'); goog.require('shaka.util.AbortableOperation'); goog.require('shaka.util.BufferUtils'); goog.require('shaka.util.ConfigUtils'); goog.require('shaka.util.Error'); goog.require('shaka.util.EventManager'); goog.require('shaka.util.FakeEvent'); goog.require('shaka.util.FakeEventTarget'); goog.require('shaka.util.Functional'); goog.require('shaka.util.IDestroyable'); goog.require('shaka.util.LanguageUtils'); goog.require('shaka.util.ManifestParserUtils'); goog.require('shaka.util.MediaReadyState'); goog.require('shaka.util.MimeUtils'); goog.require('shaka.util.ObjectUtils'); goog.require('shaka.util.Platform'); goog.require('shaka.util.PlayerConfiguration'); goog.require('shaka.util.PublicPromise'); goog.require('shaka.util.Stats'); goog.require('shaka.util.StreamUtils'); goog.require('shaka.util.Timer'); goog.requireType('shaka.media.IClosedCaptionParser'); goog.requireType('shaka.media.PresentationTimeline'); goog.requireType('shaka.routing.Node'); goog.requireType('shaka.routing.Payload'); /** * @event shaka.Player.ErrorEvent * @description Fired when a playback error occurs. * @property {string} type * 'error' * @property {!shaka.util.Error} detail * An object which contains details on the error. The error's * <code>category</code> and <code>code</code> properties will identify the * specific error that occurred. In an uncompiled build, you can also use the * <code>message</code> and <code>stack</code> properties to debug. * @exportDoc */ /** * @event shaka.Player.StateChangeEvent * @description Fired when the player changes load states. * @property {string} type * 'onstatechange' * @property {string} state * The name of the state that the player just entered. * @exportDoc */ /** * @event shaka.Player.StateIdleEvent * @description Fired when the player has stopped changing states and will * remain idle until a new state change request (e.g. <code>load</code>, * <code>attach</code>, etc.) is made. * @property {string} type * 'onstateidle' * @property {string} state * The name of the state that the player stopped in. * @exportDoc */ /** * @event shaka.Player.EmsgEvent * @description Fired when a non-typical emsg is found in a segment. * @property {string} type * 'emsg' * @property {shaka.extern.EmsgInfo} detail * An object which contains the content of the emsg box. * @exportDoc */ /** * @event shaka.Player.DownloadFailed * @description Fired when a download has failed, for any reason. * 'downloadfailed' * @property {!shaka.extern.Request} request * @property {?shaka.util.Error} error * @param {number} httpResponseCode * @param {boolean} aborted * @exportDoc */ /** * @event shaka.Player.DownloadHeadersReceived * @description Fired when the networking engine has received the headers for * a download, but before the body has been downloaded. * If the HTTP plugin being used does not track this information, this event * will default to being fired when the body is received, instead. * @property {!Object.<string, string>} headers * @property {!shaka.extern.Request} request * @property {!shaka.net.NetworkingEngine.RequestType} type * 'downloadheadersreceived' * @exportDoc */ /** * @event shaka.Player.DrmSessionUpdateEvent * @description Fired when the CDM has accepted the license response. * @property {string} type * 'drmsessionupdate' * @exportDoc */ /** * @event shaka.Player.TimelineRegionAddedEvent * @description Fired when a media timeline region is added. * @property {string} type * 'timelineregionadded' * @property {shaka.extern.TimelineRegionInfo} detail * An object which contains a description of the region. * @exportDoc */ /** * @event shaka.Player.TimelineRegionEnterEvent * @description Fired when the playhead enters a timeline region. * @property {string} type * 'timelineregionenter' * @property {shaka.extern.TimelineRegionInfo} detail * An object which contains a description of the region. * @exportDoc */ /** * @event shaka.Player.TimelineRegionExitEvent * @description Fired when the playhead exits a timeline region. * @property {string} type * 'timelineregionexit' * @property {shaka.extern.TimelineRegionInfo} detail * An object which contains a description of the region. * @exportDoc */ /** * @event shaka.Player.BufferingEvent * @description Fired when the player's buffering state changes. * @property {string} type * 'buffering' * @property {boolean} buffering * True when the Player enters the buffering state. * False when the Player leaves the buffering state. * @exportDoc */ /** * @event shaka.Player.LoadingEvent * @description Fired when the player begins loading. The start of loading is * defined as when the user has communicated intent to load content (i.e. * <code>Player.load</code> has been called). * @property {string} type * 'loading' * @exportDoc */ /** * @event shaka.Player.LoadedEvent * @description Fired when the player ends the load. * @property {string} type * 'loaded' * @exportDoc */ /** * @event shaka.Player.UnloadingEvent * @description Fired when the player unloads or fails to load. * Used by the Cast receiver to determine idle state. * @property {string} type * 'unloading' * @exportDoc */ /** * @event shaka.Player.TextTrackVisibilityEvent * @description Fired when text track visibility changes. * @property {string} type * 'texttrackvisibility' * @exportDoc */ /** * @event shaka.Player.TracksChangedEvent * @description Fired when the list of tracks changes. For example, this will * happen when new tracks are added/removed or when track restrictions change. * @property {string} type * 'trackschanged' * @exportDoc */ /** * @event shaka.Player.AdaptationEvent * @description Fired when an automatic adaptation causes the active tracks * to change. Does not fire when the application calls * <code>selectVariantTrack()</code>, <code>selectTextTrack()</code>, * <code>selectAudioLanguage()</code>, or <code>selectTextLanguage()</code>. * @property {string} type * 'adaptation' * @property {shaka.extern.Track} oldTrack * @property {shaka.extern.Track} newTrack * @exportDoc */ /** * @event shaka.Player.VariantChangedEvent * @description Fired when a call from the application caused a variant change. * Can be triggered by calls to <code>selectVariantTrack()</code> or * <code>selectAudioLanguage()</code>. Does not fire when an automatic * adaptation causes a variant change. * @property {string} type * 'variantchanged' * @property {shaka.extern.Track} oldTrack * @property {shaka.extern.Track} newTrack * @exportDoc */ /** * @event shaka.Player.TextChangedEvent * @description Fired when a call from the application caused a text stream * change. Can be triggered by calls to <code>selectTextTrack()</code> or * <code>selectTextLanguage()</code>. * @property {string} type * 'textchanged' * @exportDoc */ /** * @event shaka.Player.ExpirationUpdatedEvent * @description Fired when there is a change in the expiration times of an * EME session. * @property {string} type * 'expirationupdated' * @exportDoc */ /** * @event shaka.Player.LargeGapEvent * @description Fired when the playhead enters a large gap. If the * <code>streaming.jumpLargeGaps</code> configuration is set, the default * action of this event is to jump the gap; this can be prevented by calling * <code>preventDefault()</code> on the event object. * @property {string} type * 'largegap' * @property {number} currentTime * The current time of the playhead. * @property {number} gapSize * The size of the gap, in seconds. * @exportDoc */ /** * @event shaka.Player.ManifestParsedEvent * @description Fired after the manifest has been parsed, but before anything * else happens. The manifest may contain streams that will be filtered out, * at this stage of the loading process. * @property {string} type * 'manifestparsed' * @exportDoc */ /** * @event shaka.Player.MetadataEvent * @description Triggers after metadata associated with the stream is found. * Usually they are metadata of type ID3. * @property {string} type * 'metadata' * @property {number} startTime * The time that describes the beginning of the range of the metadata to * which the cue applies. * @property {?number} endTime * The time that describes the end of the range of the metadata to which * the cue applies. * @property {string} metadataType * Type of metadata. Eg: org.id3 or org.mp4ra * @property {shaka.extern.ID3Metadata} payload * The metadata itself * @exportDoc */ /** * @event shaka.Player.StreamingEvent * @description Fired after the manifest has been parsed and track information * is available, but before streams have been chosen and before any segments * have been fetched. You may use this event to configure the player based on * information found in the manifest. * @property {string} type * 'streaming' * @exportDoc */ /** * @event shaka.Player.AbrStatusChangedEvent * @description Fired when the state of abr has been changed. * (Enabled or disabled). * @property {string} type * 'abrstatuschanged' * @property {boolean} newStatus * The new status of the application. True for 'is enabled' and * false otherwise. * @exportDoc */ /** * @event shaka.Player.RateChangeEvent * @description Fired when the video's playback rate changes. * This allows the PlayRateController to update it's internal rate field, * before the UI updates playback button with the newest playback rate. * @property {string} type * 'ratechange' * @exportDoc */ /** * @event shaka.Player.SessionDataEvent * @description Fired when the manifest parser find info about session data. * Specification: https://tools.ietf.org/html/rfc8216#section-4.3.4.4 * @property {string} type * 'sessiondata' * @property {string} id * The id of the session data. * @property {string} uri * The uri with the session data info. * @property {string} language * The language of the session data. * @property {string} value * The value of the session data. * @exportDoc */ /** * @summary The main player object for Shaka Player. * * @implements {shaka.util.IDestroyable} * @export */ shaka.Player = class extends shaka.util.FakeEventTarget { /** * @param {HTMLMediaElement=} mediaElement * When provided, the player will attach to <code>mediaElement</code>, * similar to calling <code>attach</code>. When not provided, the player * will remain detached. * @param {function(shaka.Player)=} dependencyInjector Optional callback * which is called to inject mocks into the Player. Used for testing. */ constructor(mediaElement, dependencyInjector) { super(); /** @private {shaka.Player.LoadMode} */ this.loadMode_ = shaka.Player.LoadMode.NOT_LOADED; /** @private {HTMLMediaElement} */ this.video_ = null; /** @private {HTMLElement} */ this.videoContainer_ = null; /** * Since we may not always have a text displayer created (e.g. before |load| * is called), we need to track what text visibility SHOULD be so that we * can ensure that when we create the text displayer. When we create our * text displayer, we will use this to show (or not show) text as per the * user's requests. * * @private {boolean} */ this.isTextVisible_ = false; /** @private {shaka.util.EventManager} */ this.eventManager_ = new shaka.util.EventManager(); /** @private {shaka.net.NetworkingEngine} */ this.networkingEngine_ = null; /** @private {shaka.media.DrmEngine} */ this.drmEngine_ = null; /** @private {shaka.media.MediaSourceEngine} */ this.mediaSourceEngine_ = null; /** @private {shaka.media.Playhead} */ this.playhead_ = null; /** * The playhead observers are used to monitor the position of the playhead * and some other source of data (e.g. buffered content), and raise events. * * @private {shaka.media.PlayheadObserverManager} */ this.playheadObservers_ = null; /** * This is our control over the playback rate of the media element. This * provides the missing functionality that we need to provide trick play, * for example a negative playback rate. * * @private {shaka.media.PlayRateController} */ this.playRateController_ = null; // We use the buffering observer and timer to track when we move from having // enough buffered content to not enough. They only exist when content has // been loaded and are not re-used between loads. /** @private {shaka.util.Timer} */ this.bufferPoller_ = null; /** @private {shaka.media.BufferingObserver} */ this.bufferObserver_ = null; /** @private {shaka.media.RegionTimeline} */ this.regionTimeline_ = null; /** @private {shaka.media.StreamingEngine} */ this.streamingEngine_ = null; /** @private {shaka.extern.ManifestParser} */ this.parser_ = null; /** @private {?shaka.extern.ManifestParser.Factory} */ this.parserFactory_ = null; /** @private {?shaka.extern.Manifest} */ this.manifest_ = null; /** @private {?string} */ this.assetUri_ = null; /** @private {shaka.extern.AbrManager} */ this.abrManager_ = null; /** * The factory that was used to create the abrManager_ instance. * @private {?shaka.extern.AbrManager.Factory} */ this.abrManagerFactory_ = null; /** * Contains an ID for use with creating streams. The manifest parser should * start with small IDs, so this starts with a large one. * @private {number} */ this.nextExternalStreamId_ = 1e9; /** @private {?shaka.extern.PlayerConfiguration} */ this.config_ = this.defaultConfig_(); /** * The TextDisplayerFactory that was last used to make a text displayer. * Stored so that we can tell if a new type of text displayer is desired. * @private {?shaka.extern.TextDisplayer.Factory} */ this.lastTextFactory_; /** @private {{width: number, height: number}} */ this.maxHwRes_ = {width: Infinity, height: Infinity}; /** @private {shaka.util.Stats} */ this.stats_ = null; /** @private {!shaka.media.AdaptationSetCriteria} */ this.currentAdaptationSetCriteria_ = new shaka.media.PreferenceBasedCriteria( this.config_.preferredAudioLanguage, this.config_.preferredVariantRole, this.config_.preferredAudioChannelCount); /** @private {string} */ this.currentTextLanguage_ = this.config_.preferredTextLanguage; /** @private {string} */ this.currentTextRole_ = this.config_.preferredTextRole; /** @private {boolean} */ this.currentTextForced_ = this.config_.preferForcedSubs; /** @private {!Array.<function():(!Promise|undefined)>} */ this.cleanupOnUnload_ = []; /** * This playback start position will be used when * <code>updateStartTime()</code> has been called to provide an updated * start position during the media loading process. * * @private {?number} */ this.updatedStartTime_ = null; if (dependencyInjector) { dependencyInjector(this); } this.networkingEngine_ = this.createNetworkingEngine(); this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS); /** @private {shaka.extern.IAdManager} */ this.adManager_ = null; if (shaka.Player.adManagerFactory_) { this.adManager_ = shaka.util.Functional.callFactory(shaka.Player.adManagerFactory_); } // If the browser comes back online after being offline, then try to play // again. this.eventManager_.listen(window, 'online', () => { this.retryStreaming(); }); /** @private {shaka.routing.Node} */ this.detachNode_ = {name: 'detach'}; /** @private {shaka.routing.Node} */ this.attachNode_ = {name: 'attach'}; /** @private {shaka.routing.Node} */ this.unloadNode_ = {name: 'unload'}; /** @private {shaka.routing.Node} */ this.parserNode_ = {name: 'manifest-parser'}; /** @private {shaka.routing.Node} */ this.manifestNode_ = {name: 'manifest'}; /** @private {shaka.routing.Node} */ this.mediaSourceNode_ = {name: 'media-source'}; /** @private {shaka.routing.Node} */ this.drmNode_ = {name: 'drm-engine'}; /** @private {shaka.routing.Node} */ this.loadNode_ = {name: 'load'}; /** @private {shaka.routing.Node} */ this.srcEqualsDrmNode_ = {name: 'src-equals-drm-engine'}; /** @private {shaka.routing.Node} */ this.srcEqualsNode_ = {name: 'src-equals'}; const AbortableOperation = shaka.util.AbortableOperation; const actions = new Map(); actions.set(this.attachNode_, (has, wants) => { return AbortableOperation.notAbortable(this.onAttach_(has, wants)); }); actions.set(this.detachNode_, (has, wants) => { return AbortableOperation.notAbortable(this.onDetach_(has, wants)); }); actions.set(this.unloadNode_, (has, wants) => { return AbortableOperation.notAbortable(this.onUnload_(has, wants)); }); actions.set(this.mediaSourceNode_, (has, wants) => { const p = this.onInitializeMediaSourceEngine_(has, wants); return AbortableOperation.notAbortable(p); }); actions.set(this.parserNode_, (has, wants) => { const p = this.onInitializeParser_(has, wants); return AbortableOperation.notAbortable(p); }); actions.set(this.manifestNode_, (has, wants) => { // This action is actually abortable, so unlike the other callbacks, this // one will return an abortable operation. return this.onParseManifest_(has, wants); }); actions.set(this.drmNode_, (has, wants) => { const p = this.onInitializeDrm_(has, wants); return AbortableOperation.notAbortable(p); }); actions.set(this.loadNode_, (has, wants) => { return AbortableOperation.notAbortable(this.onLoad_(has, wants)); }); actions.set(this.srcEqualsDrmNode_, (has, wants) => { const p = this.onInitializeSrcEqualsDrm_(has, wants); return AbortableOperation.notAbortable(p); }); actions.set(this.srcEqualsNode_, (has, wants) => { return this.onSrcEquals_(has, wants); }); /** @private {shaka.routing.Walker.Implementation} */ const walkerImplementation = { getNext: (at, has, goingTo, wants) => { return this.getNextStep_(at, has, goingTo, wants); }, enterNode: (node, has, wants) => { this.dispatchEvent(this.makeEvent_( /* name= */ shaka.Player.EventName.OnStateChange, /* data= */ {'state': node.name})); const action = actions.get(node); return action(has, wants); }, handleError: async (has, error) => { shaka.log.warning('The walker saw an error:'); if (error instanceof shaka.util.Error) { shaka.log.warning('Error Code:', error.code); } else { shaka.log.warning('Error Message:', error.message); shaka.log.warning('Error Stack:', error.stack); } // Regardless of what state we were in, if there is an error, we unload. // This ensures that any initialized system will be torn-down and we // will go back to a safe foundation. We assume that the media element // is always safe to use after an error. await this.onUnload_(has, shaka.Player.createEmptyPayload_()); // There are only two nodes that come before we start loading content, // attach and detach. If we have a media element, it means we were // attached to the element, and we can safely return to the attach state // (we assume that the video element is always re-usable). We favor // returning to the attach node since it means that the app won't need // to re-attach if it saw an error. return has.mediaElement ? this.attachNode_ : this.detachNode_; }, onIdle: (node) => { this.dispatchEvent(this.makeEvent_( /* name= */ shaka.Player.EventName.OnStateIdle, /* data= */ {'state': node.name})); }, }; /** @private {shaka.routing.Walker} */ this.walker_ = new shaka.routing.Walker( this.detachNode_, shaka.Player.createEmptyPayload_(), walkerImplementation); // Even though |attach| will start in later interpreter cycles, it should be // the LAST thing we do in the constructor because conceptually it relies on // player having been initialized. if (mediaElement) { this.attach(mediaElement, /* initializeMediaSource= */ true); } } /** * @param {!shaka.Player.EventName} name * @param {Object=} data * @return {!shaka.util.FakeEvent} * @private */ makeEvent_(name, data) { return new shaka.util.FakeEvent(name, data); } /** * After destruction, a Player object cannot be used again. * * @override * @export */ async destroy() { // Make sure we only execute the destroy logic once. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) { return; } // Mark as "dead". This should stop external-facing calls from changing our // internal state any more. This will stop calls to |attach|, |detach|, etc. // from interrupting our final move to the detached state. this.loadMode_ = shaka.Player.LoadMode.DESTROYED; // Because we have set |loadMode_| to |DESTROYED| we can't call |detach|. We // must talk to |this.walker_| directly. const events = this.walker_.startNewRoute((currentPayload) => { return { node: this.detachNode_, payload: shaka.Player.createEmptyPayload_(), interruptible: false, }; }); // Wait until the detach has finished so that we don't interrupt it by // calling |destroy| on |this.walker_|. To avoid failing here, we always // resolve the promise. await new Promise((resolve) => { events.onStart = () => { shaka.log.info('Preparing to destroy walker...'); }; events.onEnd = () => { resolve(); }; events.onCancel = () => { goog.asserts.assert(false, 'Our final detach call should never be cancelled.'); resolve(); }; events.onError = () => { goog.asserts.assert(false, 'Our final detach call should never see an error'); resolve(); }; events.onSkip = () => { goog.asserts.assert(false, 'Our final detach call should never be skipped'); resolve(); }; }); await this.walker_.destroy(); // Tear-down the event manager to ensure messages stop moving around. if (this.eventManager_) { this.eventManager_.release(); this.eventManager_ = null; } this.abrManagerFactory_ = null; this.abrManager_ = null; this.config_ = null; this.stats_ = null; this.videoContainer_ = null; if (this.networkingEngine_) { await this.networkingEngine_.destroy(); this.networkingEngine_ = null; } } /** * Registers a plugin callback that will be called with * <code>support()</code>. The callback will return the value that will be * stored in the return value from <code>support()</code>. * * @param {string} name * @param {function():*} callback * @export */ static registerSupportPlugin(name, callback) { shaka.Player.supportPlugins_[name] = callback; } /** * Set a factory to create an ad manager during player construction time. * This method needs to be called bafore instantiating the Player class. * * @param {!shaka.extern.IAdManager.Factory} factory * @export */ static setAdManagerFactory(factory) { shaka.Player.adManagerFactory_ = factory; } /** * Return whether the browser provides basic support. If this returns false, * Shaka Player cannot be used at all. In this case, do not construct a * Player instance and do not use the library. * * @return {boolean} * @export */ static isBrowserSupported() { if (!window.Promise) { shaka.log.alwaysWarn('A Promise implementation or polyfill is required'); } if (!window.TextDecoder || !window.TextEncoder) { shaka.log.alwaysWarn( 'A TextDecoder/TextEncoder implementation or polyfill is required'); } // Basic features needed for the library to be usable. const basicSupport = !!window.Promise && !!window.Uint8Array && !!window.TextDecoder && !!window.TextEncoder && // eslint-disable-next-line no-restricted-syntax !!Array.prototype.forEach; if (!basicSupport) { return false; } // We do not support IE if (shaka.util.Platform.isIE()) { return false; } // We do not support iOS 9, 10, or 11, nor those same versions of desktop // Safari. const safariVersion = shaka.util.Platform.safariVersion(); if (safariVersion && safariVersion < 12) { return false; } // DRM support is not strictly necessary, but the APIs at least need to be // there. Our no-op DRM polyfill should handle that. // TODO(#1017): Consider making even DrmEngine optional. const drmSupport = shaka.media.DrmEngine.isBrowserSupported(); if (!drmSupport) { return false; } // If we have MediaSource (MSE) support, we should be able to use Shaka. if (shaka.util.Platform.supportsMediaSource()) { return true; } // If we don't have MSE, we _may_ be able to use Shaka. Look for native HLS // support, and call this platform usable if we have it. return shaka.util.Platform.supportsMediaType('application/x-mpegurl'); } /** * Probes the browser to determine what features are supported. This makes a * number of requests to EME/MSE/etc which may result in user prompts. This * should only be used for diagnostics. * * <p> * NOTE: This may show a request to the user for permission. * * @see https://bit.ly/2ywccmH * @param {boolean=} promptsOkay * @return {!Promise.<shaka.extern.SupportType>} * @export */ static async probeSupport(promptsOkay=true) { goog.asserts.assert(shaka.Player.isBrowserSupported(), 'Must have basic support'); let drm = {}; if (promptsOkay) { drm = await shaka.media.DrmEngine.probeSupport(); } const manifest = shaka.media.ManifestParser.probeSupport(); const media = shaka.media.MediaSourceEngine.probeSupport(); const ret = { manifest: manifest, media: media, drm: drm, }; const plugins = shaka.Player.supportPlugins_; for (const name in plugins) { ret[name] = plugins[name](); } return ret; } /** * Tell the player to use <code>mediaElement</code> for all <code>load</code> * requests until <code>detach</code> or <code>destroy</code> are called. * * <p> * Calling <code>attach</code> with <code>initializedMediaSource=true</code> * will tell the player to take the initial load step and initialize media * source. * * <p> * Calls to <code>attach</code> will interrupt any in-progress calls to * <code>load</code> but cannot interrupt calls to <code>attach</code>, * <code>detach</code>, or <code>unload</code>. * * @param {!HTMLMediaElement} mediaElement * @param {boolean=} initializeMediaSource * @return {!Promise} * @export */ attach(mediaElement, initializeMediaSource = true) { // Do not allow the player to be used after |destroy| is called. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) { return Promise.reject(this.createAbortLoadError_()); } const payload = shaka.Player.createEmptyPayload_(); payload.mediaElement = mediaElement; // If the platform does not support media source, we will never want to // initialize media source. if (!shaka.util.Platform.supportsMediaSource()) { initializeMediaSource = false; } const destination = initializeMediaSource ? this.mediaSourceNode_ : this.attachNode_; // Do not allow this route to be interrupted because calls after this attach // call will depend on the media element being attached. const events = this.walker_.startNewRoute((currentPayload) => { return { node: destination, payload: payload, interruptible: false, }; }); // List to the events that can occur with our request. events.onStart = () => shaka.log.info('Starting attach...'); return this.wrapWalkerListenersWithPromise_(events); } /** * Tell the player to stop using its current media element. If the player is: * <ul> * <li>detached, this will do nothing, * <li>attached, this will release the media element, * <li>loading, this will abort loading, unload, and release the media * element, * <li>playing content, this will stop playback, unload, and release the * media element. * </ul> * * <p> * Calls to <code>detach</code> will interrupt any in-progress calls to * <code>load</code> but cannot interrupt calls to <code>attach</code>, * <code>detach</code>, or <code>unload</code>. * * @return {!Promise} * @export */ detach() { // Do not allow the player to be used after |destroy| is called. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) { return Promise.reject(this.createAbortLoadError_()); } // Tell the walker to go "detached", but do not allow it to be interrupted. // If it could be interrupted it means that our media element could fall out // of sync. const events = this.walker_.startNewRoute((currentPayload) => { return { node: this.detachNode_, payload: shaka.Player.createEmptyPayload_(), interruptible: false, }; }); events.onStart = () => shaka.log.info('Starting detach...'); return this.wrapWalkerListenersWithPromise_(events); } /** * Tell the player to either return to: * <ul> * <li>detached (when it does not have a media element), * <li>attached (when it has a media element and * <code>initializedMediaSource=false</code>) * <li>media source initialized (when it has a media element and * <code>initializedMediaSource=true</code>) * </ul> * * <p> * Calls to <code>unload</code> will interrupt any in-progress calls to * <code>load</code> but cannot interrupt calls to <code>attach</code>, * <code>detach</code>, or <code>unload</code>. * * @param {boolean=} initializeMediaSource * @return {!Promise} * @export */ unload(initializeMediaSource = true) { // Do not allow the player to be used after |destroy| is called. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) { return Promise.reject(this.createAbortLoadError_()); } // If the platform does not support media source, we will never want to // initialize media source. if (!shaka.util.Platform.supportsMediaSource()) { initializeMediaSource = false; } // Since we are going either to attached or detached (through unloaded), we // can't allow it to be interrupted or else we could lose track of what // media element we are suppose to use. // // Using the current payload, we can determine which node we want to go to. // If we have a media element, we want to go back to attached. If we have no // media element, we want to go back to detached. const payload = shaka.Player.createEmptyPayload_(); const events = this.walker_.startNewRoute((currentPayload) => { // When someone calls |unload| we can either be before attached or // detached (there is nothing stopping someone from calling |detach| when // we are already detached). // // If we are attached to the correct element, we can tear down the // previous playback components and go to the attached media source node // depending on whether or not the caller wants to pre-init media source. // // If we don't have a media element, we assume that we are already at the // detached node - but only the walker knows that. To ensure we are // actually there, we tell the walker to go to detach. While this is // technically unnecessary, it ensures that we are in the state we want // to be in and ready for the next request. let destination = null; if (currentPayload.mediaElement && initializeMediaSource) { destination = this.mediaSourceNode_; } else if (currentPayload.mediaElement) { destination = this.attachNode_; } else { destination = this.detachNode_; } goog.asserts.assert(destination, 'We should have picked a destination.'); // Copy over the media element because we want to keep using the same // element - the other values don't matter. payload.mediaElement = currentPayload.mediaElement; return { node: destination, payload: payload, interruptible: false, }; }); events.onStart = () => shaka.log.info('Starting unload...'); return this.wrapWalkerListenersWithPromise_(events); } /** * Provides a way to update the stream start position during the media loading * process. Can for example be called from the <code>manifestparsed</code> * event handler to update the start position based on information in the * manifest. * * @param {number} startTime * @export */ updateStartTime(startTime) { this.updatedStartTime_ = startTime; } /** * Tell the player to load the content at <code>assetUri</code> and start * playback at <code>startTime</code>. Before calling <code>load</code>, * a call to <code>attach</code> must have succeeded. * * <p> * Calls to <code>load</code> will interrupt any in-progress calls to * <code>load</code> but cannot interrupt calls to <code>attach</code>, * <code>detach</code>, or <code>unload</code>. * * @param {string} assetUri * @param {?number=} startTime * When <code>startTime</code> is <code>null</code> or * <code>undefined</code>, playback will start at the default start time (0 * for VOD and liveEdge for LIVE). * @param {string=} mimeType * @return {!Promise} * @export */ load(assetUri, startTime, mimeType) { this.updatedStartTime_ = null; // Do not allow the player to be used after |destroy| is called. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) { return Promise.reject(this.createAbortLoadError_()); } // We dispatch the loading event when someone calls |load| because we want // to surface the user intent. this.dispatchEvent(this.makeEvent_(shaka.Player.EventName.Loading)); // Right away we know what the asset uri and start-of-load time are. We will // fill-in the rest of the information later. const payload = shaka.Player.createEmptyPayload_(); payload.uri = assetUri; payload.startTimeOfLoad = Date.now() / 1000; if (mimeType) { payload.mimeType = mimeType; } // Because we allow |startTime| to be optional, it means that it will be // |undefined| when not provided. This means that we need to re-map // |undefined| to |null| while preserving |0| as a meaningful value. if (startTime !== undefined) { payload.startTime = startTime; } // TODO: Refactor to determine whether it's a manifest or not, and whether // or not we can play it. Then we could return a better error than // UNABLE_TO_GUESS_MANIFEST_TYPE for WebM in Safari. const useSrcEquals = this.shouldUseSrcEquals_(payload); const destination = useSrcEquals ? this.srcEqualsNode_ : this.loadNode_; // Allow this request to be interrupted, this will allow other requests to // cancel a load and quickly start a new load. const events = this.walker_.startNewRoute((currentPayload) => { if (currentPayload.mediaElement == null) { // Because we return null, this "new route" will not be used. return null; } // Keep using whatever media element we have right now. payload.mediaElement = currentPayload.mediaElement; return { node: destination, payload: payload, interruptible: true, }; }); // Stats are for a single playback/load session. Stats must be initialized // before we allow calls to |updateStateHistory|. this.stats_ = new shaka.util.Stats(); // Load's request is a little different, so we can't use our normal // listeners-to-promise method. It is the only request where we may skip the // request, so we need to set the on skip callback to reject with a specific // error. events.onStart = () => shaka.log.info('Starting load of ' + assetUri + '...'); return new Promise((resolve, reject) => { events.onSkip = () => reject(new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.PLAYER, shaka.util.Error.Code.NO_VIDEO_ELEMENT)); events.onEnd = () => { resolve(); // We dispatch the loaded event when the load promise is resolved this.dispatchEvent(this.makeEvent_(shaka.Player.EventName.Loaded)); }; events.onCancel = () => reject(this.createAbortLoadError_()); events.onError = (e) => reject(e); }); } /** * Check if src= should be used to load the asset at |uri|. Assume that media * source is the default option, and that src= is for special cases. * * @param {shaka.routing.Payload} payload * @return {boolean} * |true| if the content should be loaded with src=, |false| if the content * should be loaded with MediaSource. * @private */ shouldUseSrcEquals_(payload) { const Platform = shaka.util.Platform; // If we are using a platform that does not support media source, we will // fall back to src= to handle all playback. if (!Platform.supportsMediaSource()) { return true; } // The most accurate way to tell the player how to load the content is via // MIME type. We can fall back to features of the URI if needed. let mimeType = payload.mimeType; const uri = payload.uri || ''; // If we don't have a MIME type, try to guess based on the file extension. // TODO: Too generic to belong to ManifestParser now. Refactor. if (!mimeType) { // Try using the uri extension. const extension = shaka.media.ManifestParser.getExtension(uri); mimeType = shaka.Player.SRC_EQUAL_EXTENSIONS_TO_MIME_TYPES_[extension]; } // TODO: The load graph system has a design limitation that requires routing // destination to be chosen synchronously. This means we can only make the // right choice about src= consistently if we have a well-known file // extension or API-provided MIME type. Detection of MIME type from a HEAD // request (as is done for manifest types) can't be done yet. if (mimeType) { // If we have a MIME type, check if the browser can play it natively. // This will cover both single files and native HLS. const mediaElement = payload.mediaElement || Platform.anyMediaElement(); const canPlayNatively = mediaElement.canPlayType(mimeType) != ''; // If we can't play natively, then src= isn't an option. if (!canPlayNatively) { return false; } const canPlayMediaSource = shaka.media.ManifestParser.isSupported(uri, mimeType); // If MediaSource isn't an option, the native option is our only chance. if (!canPlayMediaSource) { return true; } // If we land here, both are feasible. goog.asserts.assert(canPlayNatively && canPlayMediaSource, 'Both native and MSE playback should be possible!'); // We would prefer MediaSource in some cases, and src= in others. For // example, Android has native HLS, but we'd prefer our own MediaSource // version there. // Native HLS can be preferred on any platform via this flag: if (this.config_.streaming.preferNativeHls) { return true; } // For Safari, we have an older flag which only applies to this one // browser: if (Platform.isApple()) { return this.config_.streaming.useNativeHlsOnSafari; } // In all other cases, we prefer MediaSource. return false; } // Unless there are good reasons to use src= (single-file playback or native // HLS), we prefer MediaSource. So the final return value for choosing src= // is false. return false; } /** * This should only be called by the load graph when it is time to attach to * a media element. The only times this may be called are when we are being * asked to re-attach to the current media element, or attach to a new media * element while not attached to a media element. * * This method assumes that it is safe for it to execute, the load-graph is * responsible for ensuring all assumptions are true. * * Attaching to a media element is defined as: * - Registering error listeners to the media element. * - Caching the video element for use outside of the load graph. * * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {!Promise} * @private */ onAttach_(has, wants) { // If we don't have a media element yet, it means we are entering // "attach" from another node. // // If we have a media element, it should match |wants.mediaElement| // because it means we are going from "attach" to "attach". // // These constraints should be maintained and guaranteed by the routing // logic in |getNextStep_|. goog.asserts.assert( has.mediaElement == null || has.mediaElement == wants.mediaElement, 'The routing logic failed. MediaElement requirement failed.'); if (has.mediaElement == null) { has.mediaElement = wants.mediaElement; const onError = (error) => this.onVideoError_(error); this.eventManager_.listen(has.mediaElement, 'error', onError); } this.video_ = has.mediaElement; return Promise.resolve(); } /** * This should only be called by the load graph when it is time to detach from * a media element. The only times this may be called are when we are being * asked to detach from the current media element, or detach when we are * already detached. * * This method assumes that it is safe for it to execute, the load-graph is * responsible for ensuring all assumptions are true. * * Detaching from a media element is defined as: * - Removing error listeners from the media element. * - Dropping the cached reference to the video element. * * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {!Promise} * @private */ onDetach_(has, wants) { // If we are going from "detached" to "detached" we wouldn't have // a media element to detach from. if (has.mediaElement) { this.eventManager_.unlisten(has.mediaElement, 'error'); has.mediaElement = null; } // Clear our cached copy of the media element. this.video_ = null; return Promise.resolve(); } /** * This should only be called by the load graph when it is time to unload all * currently initialized playback components. Unlike the other load actions, * this action is built to be more general. We need to do this because we * don't know what state the player will be in before unloading (including * after an error occurred in the middle of a transition). * * This method assumes that any component could be |null| and should be safe * to call from any point in the load graph. * * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {!Promise} * @private */ async onUnload_(has, wants) { // Set the load mode to unload right away so that all the public methods // will stop using the internal components. We need to make sure that we // are not overriding the destroyed state because we will unload when we are // destroying the player. if (this.loadMode_ != shaka.Player.LoadMode.DESTROYED) { this.loadMode_ = shaka.Player.LoadMode.NOT_LOADED; } // Run any general cleanup tasks now. This should be here at the top, right // after setting loadMode_, so that internal components still exist as they // did when the cleanup tasks were registered in the array. const cleanupTasks = this.cleanupOnUnload_.map((cb) => cb()); this.cleanupOnUnload_ = []; await Promise.all(cleanupTasks); // Dispatch the unloading event. this.dispatchEvent(this.makeEvent_(shaka.Player.EventName.Unloading)); // Remove everything that has to do with loading content from our payload // since we are releasing everything that depended on it. has.mimeType = null; has.startTime = null; has.uri = null; // In most cases we should have a media element. The one exception would // be if there was an error and we, by chance, did not have a media element. if (has.mediaElement) { this.eventManager_.unlisten(has.mediaElement, 'loadedmetadata'); this.eventManager_.unlisten(has.mediaElement, 'playing'); this.eventManager_.unlisten(has.mediaElement, 'pause'); this.eventManager_.unlisten(has.mediaElement, 'ended'); this.eventManager_.unlisten(has.mediaElement, 'ratechange'); } // Some observers use some playback components, shutting down the observers // first ensures that they don't try to use the playback components // mid-destroy. if (this.playheadObservers_) { this.playheadObservers_.release(); this.playheadObservers_ = null; } if (this.bufferPoller_) { this.bufferPoller_.stop(); this.bufferPoller_ = null; } // Stop the parser early. Since it is at the start of the pipeline, it // should be start early to avoid is pushing new data downstream. if (this.parser_) { await this.parser_.stop(); this.parser_ = null; this.parserFactory_ = null; } // Abr Manager will tell streaming engine what to do, so we need to stop // it before we destroy streaming engine. Unlike with the other components, // we do not release the instance, we will reuse it in later loads. if (this.abrManager_) { await this.abrManager_.stop(); } // Streaming engine will push new data to media source engine, so we need // to shut it down before destroy media source engine. if (this.streamingEngine_) { await this.streamingEngine_.destroy(); this.streamingEngine_ = null; } if (this.playRateController_) { this.playRateController_.release(); this.playRateController_ = null; } // Playhead is used by StreamingEngine, so we can't destroy this until after // StreamingEngine has stopped. if (this.playhead_) { this.playhead_.release(); this.playhead_ = null; } // Media source engine holds onto the media element, and in order to detach // the media keys (with drm engine), we need to break the connection between // media source engine and the media element. if (this.mediaSourceEngine_) { await this.mediaSourceEngine_.destroy(); this.mediaSourceEngine_ = null; } if (this.adManager_) { this.adManager_.onAssetUnload(); } // In order to unload a media element, we need to remove the src attribute // and then load again. When we destroy media source engine, this will be // done for us, but for src=, we need to do it here. // // DrmEngine requires this to be done before we destroy DrmEngine itself. if (has.mediaElement && has.mediaElement.src) { // TODO: Investigate this more. Only reproduces on Firefox 69. // Introduce a delay before detaching the video source. We are seeing // spurious Promise rejections involving an AbortError in our tests // otherwise. await new Promise( (resolve) => new shaka.util.Timer(resolve).tickAfter(0.1)); has.mediaElement.removeAttribute('src'); has.mediaElement.load(); // Remove all track nodes while (has.mediaElement.lastChild) { has.mediaElement.removeChild(has.mediaElement.firstChild); } } if (this.drmEngine_) { await this.drmEngine_.destroy(); this.drmEngine_ = null; } this.assetUri_ = null; this.bufferObserver_ = null; if (this.manifest_) { for (const variant of this.manifest_.variants) { for (const stream of [variant.audio, variant.video]) { if (stream && stream.segmentIndex) { stream.segmentIndex.release(); } } } for (const stream of this.manifest_.textStreams) { if (stream.segmentIndex) { stream.segmentIndex.release(); } } } this.manifest_ = null; this.stats_ = new shaka.util.Stats(); // Replace with a clean stats object. this.lastTextFactory_ = null; // Make sure that the app knows of the new buffering state. this.updateBufferState_(); } /** * This should only be called by the load graph when it is time to initialize * media source engine. The only time this may be called is when we are * attached to the same media element as in the request. * * This method assumes that it is safe for it to execute. The load-graph is * responsible for ensuring all assumptions are true. * * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * * @return {!Promise} * @private */ async onInitializeMediaSourceEngine_(has, wants) { goog.asserts.assert( shaka.util.Platform.supportsMediaSource(), 'We should not be initializing media source on a platform that does ' + 'not support media source.'); goog.asserts.assert( has.mediaElement, 'We should have a media element when initializing media source.'); goog.asserts.assert( has.mediaElement == wants.mediaElement, '|has| and |wants| should have the same media element when ' + 'initializing media source.'); goog.asserts.assert( this.mediaSourceEngine_ == null, 'We should not have a media source engine yet.'); const closedCaptionsParser = new shaka.media.ClosedCaptionParser(); // When changing text visibility we need to update both the text displayer // and streaming engine because we don't always stream text. To ensure that // text displayer and streaming engine are always in sync, wait until they // are both initialized before setting the initial value. const textDisplayerFactory = this.config_.textDisplayFactory; const textDisplayer = shaka.util.Functional.callFactory(textDisplayerFactory); this.lastTextFactory_ = textDisplayerFactory; const mediaSourceEngine = this.createMediaSourceEngine( has.mediaElement, closedCaptionsParser, textDisplayer, (metadata, offset, endTime) => { this.processTimedMetadataMediaSrc_(metadata, offset, endTime); }); // Wait for media source engine to finish opening. This promise should // NEVER be rejected as per the media source engine implementation. await mediaSourceEngine.open(); // Wait until it is ready to actually store the reference. this.mediaSourceEngine_ = mediaSourceEngine; } /** * Create the parser for the asset located at |wants.uri|. This should only be * called as part of the load graph. * * This method assumes that it is safe for it to execute, the load-graph is * responsible for ensuring all assumptions are true. * * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {!Promise} * @private */ async onInitializeParser_(has, wants) { goog.asserts.assert( has.mediaElement, 'We should have a media element when initializing the parser.'); goog.asserts.assert( has.mediaElement == wants.mediaElement, '|has| and |wants| should have the same media element when ' + 'initializing the parser.'); goog.asserts.assert( this.networkingEngine_, 'Need networking engine when initializing the parser.'); goog.asserts.assert( this.config_, 'Need player config when initializing the parser.'); // We are going to "lock-in" the mime type and uri since they are // what we are going to use to create our parser and parse the manifest. has.mimeType = wants.mimeType; has.uri = wants.uri; goog.asserts.assert( has.uri, 'We should have an asset uri when initializing the parsing.'); // Store references to things we asserted so that we don't need to reassert // them again later. const assetUri = has.uri; const networkingEngine = this.networkingEngine_; // Save the uri so that it can be used outside of the load-graph. this.assetUri_ = assetUri; // Create the parser that we will use to parse the manifest. this.parserFactory_ = await shaka.media.ManifestParser.getFactory( assetUri, networkingEngine, this.config_.manifest.retryParameters, has.mimeType); goog.asserts.assert(this.parserFactory_, 'Must have manifest parser'); this.parser_ = shaka.util.Functional.callFactory(this.parserFactory_); const manifestConfig = shaka.util.ObjectUtils.cloneObject(this.config_.manifest); // Don't read video segments if the player is attached to an audio element if (wants.mediaElement && wants.mediaElement.nodeName === 'AUDIO') { manifestConfig.disableVideo = true; } this.parser_.configure(manifestConfig); } /** * Parse the manifest at |has.uri| using the parser that should have already * been created. This should only be called as part of the load graph. * * This method assumes that it is safe for it to execute, the load-graph is * responsible for ensuring all assumptions are true. * * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {!shaka.util.AbortableOperation} * @private */ onParseManifest_(has, wants) { goog.asserts.assert( has.mimeType == wants.mimeType, '|has| and |wants| should have the same mime type when parsing.'); goog.asserts.assert( has.uri == wants.uri, '|has| and |wants| should have the same uri when parsing.'); goog.asserts.assert( has.uri, '|has| should have a valid uri when parsing.'); goog.asserts.assert( has.uri == this.assetUri_, '|has.uri| should match the cached asset uri.'); goog.asserts.assert( this.networkingEngine_, 'Need networking engine to parse manifest.'); goog.asserts.assert( this.config_, 'Need player config to parse manifest.'); goog.asserts.assert( this.parser_, '|this.parser_| should have been set in an earlier step.'); // Store references to things we asserted so that we don't need to reassert // them again later. const assetUri = has.uri; const networkingEngine = this.networkingEngine_; // This will be needed by the parser once it starts parsing, so we will // initialize it now even through it appears a little out-of-place. this.regionTimeline_ = new shaka.media.RegionTimeline(() => this.seekRange()); this.regionTimeline_.setListeners(/* onRegionAdded= */ (region) => { this.onRegionEvent_(shaka.Player.EventName.TimelineRegionAdded, region); if (this.adManager_) { this.adManager_.onDashTimedMetadata(region); } }); // TODO (#1391): Once filterManifest_ is async, remove this eslint disable. /* eslint-disable require-await */ const playerInterface = { networkingEngine: networkingEngine, filter: async (manifest) => this.filterManifest_(manifest), makeTextStreamsForClosedCaptions: (manifest) => { return this.makeTextStreamsForClosedCaptions_(manifest); }, // Called when the parser finds a timeline region. This can be called // before we start playback or during playback (live/in-progress // manifest). onTimelineRegionAdded: (region) => this.regionTimeline_.addRegion(region), onEvent: (event) => this.dispatchEvent(event), onError: (error) => this.onError_(error), isLowLatencyMode: () => this.isLowLatencyMode_(), isAutoLowLatencyMode: () => this.isAutoLowLatencyMode_(), enableLowLatencyMode: () => { this.configure('streaming.lowLatencyMode', true); }, }; /* eslint-enable require-await */ const startTime = Date.now() / 1000; return new shaka.util.AbortableOperation(/* promise= */ (async () => { this.manifest_ = await this.parser_.start(assetUri, playerInterface); // This event is fired after the manifest is parsed, but before any // filtering takes place. const event = this.makeEvent_(shaka.Player.EventName.ManifestParsed); this.dispatchEvent(event); // We require all manifests to have at least one variant. if (this.manifest_.variants.length == 0) { throw new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.NO_VARIANTS); } // Make sure that all variants are either: audio-only, video-only, or // audio-video. shaka.Player.filterForAVVariants_(this.manifest_); const now = Date.now() / 1000; const delta = now - startTime; this.stats_.setManifestTime(delta); })(), /* onAbort= */ () => { shaka.log.info('Aborting parser step...'); return this.parser_.stop(); }); } /** * This should only be called by the load graph when it is time to initialize * drmEngine. The only time this may be called is when we are attached a * media element and have parsed a manifest. * * The load-graph is responsible for ensuring all assumptions made by this * method are valid before executing it. * * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {!Promise} * @private */ async onInitializeDrm_(has, wants) { goog.asserts.assert( has.mimeType == wants.mimeType, 'The load graph should have ensured the mime types matched.'); goog.asserts.assert( has.uri == wants.uri, 'The load graph should have ensured the uris matched'); goog.asserts.assert( this.networkingEngine_, '|onInitializeDrm_| should never be called after |destroy|'); goog.asserts.assert( this.config_, '|onInitializeDrm_| should never be called after |destroy|'); goog.asserts.assert( this.manifest_, '|this.manifest_| should have been set in an earlier step.'); goog.asserts.assert( has.mediaElement, 'We should have a media element when initializing the DRM Engine.'); const startTime = Date.now() / 1000; let firstEvent = true; this.drmEngine_ = this.createDrmEngine({ netEngine: this.networkingEngine_, onError: (e) => { this.onError_(e); }, onKeyStatus: (map) => { this.onKeyStatus_(map); }, onExpirationUpdated: (id, expiration) => { this.onExpirationUpdated_(id, expiration); }, onEvent: (e) => { this.dispatchEvent(e); if (e.type == shaka.Player.EventName.DrmSessionUpdate && firstEvent) { firstEvent = false; const now = Date.now() / 1000; const delta = now - startTime; this.stats_.setDrmTime(delta); } }, }); this.drmEngine_.configure(this.config_.drm); await this.drmEngine_.initForPlayback( this.manifest_.variants, this.manifest_.offlineSessionIds); await this.drmEngine_.attach(has.mediaElement); // Now that we have drm information, filter the manifest (again) so that we // can ensure we only use variants with the selected key system. await this.filterManifest_(this.manifest_); } /** * This should only be called by the load graph when it is time to load all * playback components needed for playback. The only times this may be called * is when we are attached to the same media element as in the request. * * This method assumes that it is safe for it to execute, the load-graph is * responsible for ensuring all assumptions are true. * * Loading is defined as: * - Attaching all playback-related listeners to the media element * - Initializing playback and observers * - Initializing ABR Manager * - Initializing Streaming Engine * - Starting playback at |wants.startTime| * * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @private */ async onLoad_(has, wants) { goog.asserts.assert( has.mimeType == wants.mimeType, '|has| and |wants| should have the same mime type when loading.'); goog.asserts.assert( has.uri == wants.uri, '|has| and |wants| should have the same uri when loading.'); goog.asserts.assert( has.mediaElement, 'We should have a media element when loading.'); goog.asserts.assert( !isNaN(wants.startTimeOfLoad), '|wants| should tell us when the load was originally requested'); // Since we are about to start playback, we will lock in the start time as // something we are now depending on. has.startTime = wants.startTime; // If updateStartTime() has been called since load() was invoked use the // requested startTime if (this.updatedStartTime_ != null) { has.startTime = this.updatedStartTime_; this.updatedStartTime_ = null; } // Store a reference to values in |has| after asserting so that closure will // know that they will still be non-null between calls to await. const mediaElement = has.mediaElement; const assetUri = has.uri; // Save the uri so that it can be used outside of the load-graph. this.assetUri_ = assetUri; this.playRateController_ = new shaka.media.PlayRateController({ getRate: () => has.mediaElement.playbackRate, getDefaultRate: () => has.mediaElement.defaultPlaybackRate, setRate: (rate) => { has.mediaElement.playbackRate = rate; }, movePlayhead: (delta) => { has.mediaElement.currentTime += delta; }, }); const updateStateHistory = () => this.updateStateHistory_(); const onRateChange = () => this.onRateChange_(); this.eventManager_.listen(mediaElement, 'playing', updateStateHistory); this.eventManager_.listen(mediaElement, 'pause', updateStateHistory); this.eventManager_.listen(mediaElement, 'ended', updateStateHistory); this.eventManager_.listen(mediaElement, 'ratechange', onRateChange); const abrFactory = this.config_.abrFactory; if (!this.abrManager_ || this.abrManagerFactory_ != abrFactory) { this.abrManagerFactory_ = abrFactory; this.abrManager_ = shaka.util.Functional.callFactory(abrFactory); if (typeof this.abrManager_.playbackRateChanged != 'function') { shaka.Deprecate.deprecateFeature(4, 'AbrManager', 'Please use an AbrManager with playbackRateChanged function.'); this.abrManager_.playbackRateChanged = (rate) => {}; } this.abrManager_.configure(this.config_.abr); } // Copy preferred languages from the config again, in case the config was // changed between construction and playback. this.currentAdaptationSetCriteria_ = new shaka.media.PreferenceBasedCriteria( this.config_.preferredAudioLanguage, this.config_.preferredVariantRole, this.config_.preferredAudioChannelCount); this.currentTextLanguage_ = this.config_.preferredTextLanguage; this.currentTextRole_ = this.config_.preferredTextRole; this.currentTextForced_ = this.config_.preferForcedSubs; shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline, this.config_.playRangeStart, this.config_.playRangeEnd); this.abrManager_.init((variant, clearBuffer, safeMargin) => { return this.switch_(variant, clearBuffer, safeMargin); }); this.playhead_ = this.createPlayhead(has.startTime); this.playheadObservers_ = this.createPlayheadObserversForMSE_(); // We need to start the buffer management code near the end because it will // set the initial buffering state and that depends on other components // being initialized. const rebufferThreshold = Math.max( this.manifest_.minBufferTime, this.config_.streaming.rebufferingGoal); this.startBufferManagement_(rebufferThreshold); // If the content is multi-codec and the browser can play more than one of // them, choose codecs now before we initialize streaming. shaka.util.StreamUtils.chooseCodecsAndFilterManifest( this.manifest_, this.config_.preferredVideoCodecs, this.config_.preferredAudioCodecs, this.config_.preferredAudioChannelCount, this.config_.preferredDecodingAttributes); this.streamingEngine_ = this.createStreamingEngine(); this.streamingEngine_.configure(this.config_.streaming); // Set the load mode to "loaded with media source" as late as possible so // that public methods won't try to access internal components until // they're all initialized. We MUST switch to loaded before calling // "streaming" so that they can access internal information. this.loadMode_ = shaka.Player.LoadMode.MEDIA_SOURCE; // The event must be fired after we filter by restrictions but before the // active stream is picked to allow those listening for the "streaming" // event to make changes before streaming starts. this.dispatchEvent(this.makeEvent_(shaka.Player.EventName.Streaming)); // Pick the initial streams to play. // however, we would skip switch to initial variant // if user already pick variant track (via selectVariantTrack api) let initialVariant = null; const activeVariantTrack = this.getVariantTracks().find((t) => t.active); if (!activeVariantTrack) { initialVariant = this.chooseVariant_(); goog.asserts.assert(initialVariant, 'Must choose an initial variant!'); this.switchVariant_(initialVariant, /* fromAdaptation= */ true, /* clearBuffer= */ false, /* safeMargin= */ 0); // Now that we have initial streams, we may adjust the start time to align // to a segment boundary. if (this.config_.streaming.startAtSegmentBoundary) { const startTime = this.playhead_.getTime(); const adjustedTime = await this.adjustStartTime_(initialVariant, startTime); this.playhead_.setStartTime(adjustedTime); } // Since the first streams just became active, send an adaptation event. this.onAdaptation_(null, shaka.util.StreamUtils.variantToTrack(initialVariant)); } // Decide if text should be shown automatically. // similar to video/audio track, we would skip switch initial text track // if user already pick text track (via selectTextTrack api) const activeTextTrack = this.getTextTracks().find((t) => t.active); if (!activeTextTrack) { const initialTextStream = this.chooseTextStream_(); if (initialTextStream) { this.addTextStreamToSwitchHistory_( initialTextStream, /* fromAdaptation= */ true); } if (initialVariant) { this.setInitialTextState_(initialVariant, initialTextStream); } // Don't initialize with a text stream unless we should be streaming text. if (initialTextStream && this.shouldStreamText_()) { this.streamingEngine_.switchTextStream(initialTextStream); } } // Start streaming content. This will start the flow of content down to // media source. await this.streamingEngine_.start(); if (this.config_.abr.enabled) { this.abrManager_.enable(); this.onAbrStatusChanged_(); } // Re-filter the manifest after streams have been chosen. this.filterManifestByCurrentVariant_(); // Dispatch a 'trackschanged' event now that all initial filtering is done. this.onTracksChanged_(); // Now that we've filtered out variants that aren't compatible with the // active one, update abr manager with filtered variants. // NOTE: This may be unnecessary. We've already chosen one codec in // chooseCodecsAndFilterManifest_ before we started streaming. But it // doesn't hurt, and this will all change when we start using // MediaCapabilities and codec switching. // TODO(#1391): Re-evaluate with MediaCapabilities and codec switching. this.updateAbrManagerVariants_(); const hasPrimary = this.manifest_.variants.some((v) => v.primary); if (!this.config_.preferredAudioLanguage && !hasPrimary) { shaka.log.warning('No preferred audio language set. We have chosen an ' + 'arbitrary language initially'); } // Wait for the 'loadedmetadata' event to measure load() latency. this.eventManager_.listenOnce(mediaElement, 'loadedmetadata', () => { const now = Date.now() / 1000; const delta = now - wants.startTimeOfLoad; this.stats_.setLoadLatency(delta); }); } /** * This should only be called by the load graph when it is time to initialize * drmEngine for src= playbacks. * * The load-graph is responsible for ensuring all assumptions made by this * method are valid before executing it. * * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {!Promise} * @private */ async onInitializeSrcEqualsDrm_(has, wants) { const ContentType = shaka.util.ManifestParserUtils.ContentType; goog.asserts.assert( this.networkingEngine_, '|onInitializeSrcEqualsDrm_| should never be called after |destroy|'); goog.asserts.assert( this.config_, '|onInitializeSrcEqualsDrm_| should never be called after |destroy|'); const startTime = Date.now() / 1000; let firstEvent = true; this.drmEngine_ = this.createDrmEngine({ netEngine: this.networkingEngine_, onError: (e) => { this.onError_(e); }, onKeyStatus: (map) => { this.onKeyStatus_(map); }, onExpirationUpdated: (id, expiration) => { this.onExpirationUpdated_(id, expiration); }, onEvent: (e) => { this.dispatchEvent(e); if (e.type == shaka.Player.EventName.DrmSessionUpdate && firstEvent) { firstEvent = false; const now = Date.now() / 1000; const delta = now - startTime; this.stats_.setDrmTime(delta); } }, }); this.drmEngine_.configure(this.config_.drm); const uri = wants.uri || ''; const extension = shaka.media.ManifestParser.getExtension(uri); let mimeType = shaka.Player.SRC_EQUAL_EXTENSIONS_TO_MIME_TYPES_[extension]; if (mimeType == 'application/x-mpegurl' && shaka.util.Platform.isApple()) { mimeType = 'application/vnd.apple.mpegurl'; } if (!mimeType) { mimeType = 'video/mp4'; } // TODO: Instead of feeding DrmEngine with Variants, we should refactor // DrmEngine so that it takes a minimal config derived from Variants. In // cases like this one or in removal of stored content, the details are // largely unimportant. We should have a saner way to initialize DrmEngine. // That would also insulate DrmEngine from manifest changes in the future. // For now, that is time-consuming and this synthetic Variant is easy, so // I'm putting it off. Since this is only expected to be used for native // HLS in Safari, this should be safe. -JCP /** @type {shaka.extern.Variant} */ const variant = { id: 0, language: 'und', primary: false, audio: null, video: { id: 0, originalId: null, createSegmentIndex: () => Promise.resolve(), segmentIndex: null, mimeType: wants.mimeType ? shaka.util.MimeUtils.getBasicType(wants.mimeType) : mimeType, codecs: wants.mimeType ? shaka.util.MimeUtils.getCodecs(wants.mimeType) : '', encrypted: true, drmInfos: [], // Filled in by DrmEngine config. keyIds: new Set(), language: 'und', label: null, type: ContentType.VIDEO, primary: false, trickModeVideo: null, emsgSchemeIdUris: null, roles: [], forced: false, channelsCount: null, audioSamplingRate: null, spatialAudio: false, closedCaptions: null, }, bandwidth: 100, allowedByApplication: true, allowedByKeySystem: true, decodingInfos: [], }; this.drmEngine_.setSrcEquals(/* srcEquals= */ true); await this.drmEngine_.initForPlayback( [variant], /* offlineSessionIds= */ []); await this.drmEngine_.attach(has.mediaElement); } /** * This should only be called by the load graph when it is time to set-up the * media element to play content using src=. The only times this may be called * is when we are attached to the same media element as in the request. * * This method assumes that it is safe for it to execute, the load-graph is * responsible for ensuring all assumptions are true. * * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {!shaka.util.AbortableOperation} * * @private */ onSrcEquals_(has, wants) { goog.asserts.assert( has.mediaElement, 'We should have a media element when loading.'); goog.asserts.assert( wants.uri, '|has| should have a valid uri when loading.'); goog.asserts.assert( !isNaN(wants.startTimeOfLoad), '|wants| should tell us when the load was originally requested'); goog.asserts.assert( this.video_ == has.mediaElement, 'The video element should match our media element'); // Lock-in the values that we are using so that the routing logic knows what // we have. has.uri = wants.uri; has.startTime = wants.startTime; // Save the uri so that it can be used outside of the load-graph. this.assetUri_ = has.uri; this.playhead_ = new shaka.media.SrcEqualsPlayhead(has.mediaElement); if (has.startTime != null) { this.playhead_.setStartTime(has.startTime); } this.playRateController_ = new shaka.media.PlayRateController({ getRate: () => has.mediaElement.playbackRate, getDefaultRate: () => has.mediaElement.defaultPlaybackRate, setRate: (rate) => { has.mediaElement.playbackRate = rate; }, movePlayhead: (delta) => { has.mediaElement.currentTime += delta; }, }); // We need to start the buffer management code near the end because it will // set the initial buffering state and that depends on other components // being initialized. const rebufferThreshold = this.config_.streaming.rebufferingGoal; this.startBufferManagement_(rebufferThreshold); // Add all media element listeners. const updateStateHistory = () => this.updateStateHistory_(); const onRateChange = () => this.onRateChange_(); this.eventManager_.listen(has.mediaElement, 'playing', updateStateHistory); this.eventManager_.listen(has.mediaElement, 'pause', updateStateHistory); this.eventManager_.listen(has.mediaElement, 'ended', updateStateHistory); this.eventManager_.listen(has.mediaElement, 'ratechange', onRateChange); // Wait for the 'loadedmetadata' event to measure load() latency, but only // if preload is set in a way that would result in this event firing // automatically. See https://github.com/google/shaka-player/issues/2483 if (this.video_.preload != 'none') { this.eventManager_.listenOnce(this.video_, 'loadedmetadata', () => { const now = Date.now() / 1000; const delta = now - wants.startTimeOfLoad; this.stats_.setLoadLatency(delta); }); } // The audio tracks are only available on Safari at the moment, but this // drives the tracks API for Safari's native HLS. So when they change, // fire the corresponding Shaka Player event. if (this.video_.audioTracks) { this.eventManager_.listen( this.video_.audioTracks, 'addtrack', () => this.onTracksChanged_()); this.eventManager_.listen( this.video_.audioTracks, 'removetrack', () => this.onTracksChanged_()); this.eventManager_.listen( this.video_.audioTracks, 'change', () => this.onTracksChanged_()); } if (this.video_.textTracks) { this.eventManager_.listen(this.video_.textTracks, 'addtrack', (e) => { const trackEvent = /** @type {!TrackEvent} */(e); if (trackEvent.track) { const track = trackEvent.track; goog.asserts.assert(track instanceof TextTrack, 'Wrong track type!'); switch (track.kind) { case 'metadata': this.processTimedMetadataSrcEqls_(track); break; case 'chapters': this.processChaptersTrack_(track); break; default: this.onTracksChanged_(); break; } } }); this.eventManager_.listen( this.video_.textTracks, 'removetrack', () => this.onTracksChanged_()); this.eventManager_.listen( this.video_.textTracks, 'change', () => this.onTracksChanged_()); } // By setting |src| we are done "loading" with src=. We don't need to set // the current time because |playhead| will do that for us. has.mediaElement.src = has.uri; // Tizen 3 / WebOS won't load anything unless you call load() explicitly, // no matter the value of the preload attribute. This is harmful on some // other platforms by triggering unbounded loading of media data, but is // necessary here. if (shaka.util.Platform.isTizen() || shaka.util.Platform.isWebOS()) { has.mediaElement.load(); } // Set the load mode last so that we know that all our components are // initialized. this.loadMode_ = shaka.Player.LoadMode.SRC_EQUALS; // The event doesn't mean as much for src= playback, since we don't control // streaming. But we should fire it in this path anyway since some // applications may be expecting it as a life-cycle event. this.dispatchEvent(this.makeEvent_(shaka.Player.EventName.Streaming)); // The "load" Promise is resolved when we have loaded the metadata. If we // wait for the full data, that won't happen on Safari until the play button // is hit. const fullyLoaded = new shaka.util.PublicPromise(); shaka.util.MediaReadyState.waitForReadyState(this.video_, HTMLMediaElement.HAVE_METADATA, this.eventManager_, () => { fullyLoaded.resolve(); }); // This flag is used below in the language preference setup to check if this // load was canceled before the necessary events fire. let unloaded = false; this.cleanupOnUnload_.push(() => { unloaded = true; }); // We can't switch to preferred languages, though, until the data is loaded. shaka.util.MediaReadyState.waitForReadyState(this.video_, HTMLMediaElement.HAVE_CURRENT_DATA, this.eventManager_, async () => { // If we have moved on to another piece of content while waiting for // the above event, we should not change tracks here. if (unloaded) { return; } this.setupPreferredAudioOnSrc_(); // Applying the text preference too soon can result in it being // reverted. Wait for native HLS to pick something first. const textTracks = this.getFilteredTextTracks_(); if (!textTracks.find((t) => t.mode != 'disabled')) { await new Promise((resolve) => { this.eventManager_.listenOnce( this.video_.textTracks, 'change', resolve); // We expect the event to fire because it does on Safari. // But in case it doesn't on some other platform or future // version, move on in 1 second no matter what. This keeps the // language settings from being completely ignored if something // goes wrong. new shaka.util.Timer(resolve).tickAfter(1); }); } // If we have moved on to another piece of content while waiting for // the above event/timer, we should not change tracks here. if (unloaded) { return; } this.setupPreferredTextOnSrc_(); }); if (this.video_.error) { // Already failed! fullyLoaded.reject(this.videoErrorToShakaError_()); } else if (this.video_.preload == 'none') { shaka.log.alwaysWarn( 'With <video preload="none">, the browser will not load anything ' + 'until play() is called. We are unable to measure load latency in ' + 'a meaningful way, and we cannot provide track info yet. Please do ' + 'not use preload="none" with Shaka Player.'); // We can't wait for an event load loadedmetadata, since that will be // blocked until a user interaction. So resolve the Promise now. fullyLoaded.resolve(); } this.eventManager_.listenOnce(this.video_, 'error', () => { fullyLoaded.reject(this.videoErrorToShakaError_()); }); return new shaka.util.AbortableOperation(fullyLoaded, /* onAbort= */ () => { const abortedError = new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.PLAYER, shaka.util.Error.Code.OPERATION_ABORTED); fullyLoaded.reject(abortedError); return Promise.resolve(); // Abort complete. }); } /** * This method setup the preferred audio using src=.. * * @private */ setupPreferredAudioOnSrc_() { const preferredAudioLanguage = this.config_.preferredAudioLanguage; // If the user has not selected a preference, the browser preference is // left. if (preferredAudioLanguage == '') { return; } this.selectAudioLanguage(preferredAudioLanguage); const preferredVariantRole = this.config_.preferredVariantRole; // If the user has not selected a role preference, the previous match is // selected. if (preferredVariantRole == '') { return; } this.selectAudioLanguage(preferredAudioLanguage, preferredVariantRole); } /** * This method setup the preferred text using src=. * * @private */ setupPreferredTextOnSrc_() { const preferredTextLanguage = this.config_.preferredTextLanguage; const preferForcedSubs = this.config_.preferForcedSubs; // If the user has not selected a preference, the browser preference is // left. if (preferredTextLanguage == '') { return; } this.selectTextLanguage(preferredTextLanguage, '', preferForcedSubs); const preferredTextRole = this.config_.preferredTextRole; // If the user has not selected a role preference, the previous match is // selected. if (preferredTextRole == '') { return; } this.selectTextLanguage(preferredTextLanguage, preferredTextRole, preferForcedSubs); } /** * We're looking for metadata tracks to process id3 tags. One of the uses is * for ad info on LIVE streams * * @param {!TextTrack} track * @private */ processTimedMetadataSrcEqls_(track) { if (track.kind != 'metadata') { return; } // Hidden mode is required for the cuechange event to launch correctly track.mode = 'hidden'; this.eventManager_.listen(track, 'cuechange', () => { if (!track.activeCues) { return; } for (const cue of track.activeCues) { this.dispatchMetadataEvent_(cue.startTime, cue.endTime, cue.type, cue.value); if (this.adManager_) { this.adManager_.onCueMetadataChange(cue.value); } } }); // In Safari the initial assignment does not always work, so we schedule // this process to be repeated several times to ensure that it has been put // in the correct mode. new shaka.util.Timer(() => { const textTracks = this.getMetadataTracks_(); for (const textTrack of textTracks) { textTrack.mode = 'hidden'; } }).tickNow().tickAfter(/* seconds= */ 0.5); } /** * @param {!Array.<shaka.extern.ID3Metadata>} metadata * @param {number} offset * @param {?number} segmentEndTime * @private */ processTimedMetadataMediaSrc_(metadata, offset, segmentEndTime) { for (const sample of metadata) { if (sample['data'] && sample['cueTime'] && sample['frames']) { const start = sample['cueTime'] + offset; const end = segmentEndTime; const metadataType = 'ID3'; for (const frame of sample['frames']) { const payload = frame; this.dispatchMetadataEvent_(start, end, metadataType, payload); } if (this.adManager_) { this.adManager_.onHlsTimedMetadata(sample, start); } } } } /** * Construct and fire a Player.Metadata event * * @param {number} startTime * @param {?number} endTime * @param {string} metadataType * @param {shaka.extern.ID3Metadata} payload * @private */ dispatchMetadataEvent_(startTime, endTime, metadataType, payload) { goog.asserts.assert(!endTime || startTime <= endTime, 'Metadata start time should be less or equal to the end time!'); const eventName = shaka.Player.EventName.Metadata; const data = { startTime: startTime, endTime: endTime, metadataType: metadataType, payload: payload, }; this.dispatchEvent(this.makeEvent_(eventName, data)); } /** * We're looking for chapters tracks to process the chapters. * * @param {?TextTrack} track * @private */ processChaptersTrack_(track) { if (!track || track.kind != 'chapters') { return; } // Hidden mode is required for the cuechange event to launch correctly and // get the cues and the activeCues track.mode = 'hidden'; // In Safari the initial assignment does not always work, so we schedule // this process to be repeated several times to ensure that it has been put // in the correct mode. new shaka.util.Timer(() => { const chaptersTracks = this.getChaptersTracks_(); for (const chaptersTrack of chaptersTracks) { chaptersTrack.mode = 'hidden'; } }).tickNow().tickAfter(/* seconds= */ 0.5); } /** * Take a series of variants and ensure that they only contain one type of * variant. The different options are: * 1. Audio-Video * 2. Audio-Only * 3. Video-Only * * A manifest can only contain a single type because once we initialize media * source to expect specific streams, it must always have content for those * streams. If we were to start with audio+video and switch to an audio-only * variant, media source would block waiting for video content. * * @param {shaka.extern.Manifest} manifest * @private */ static filterForAVVariants_(manifest) { const isAVVariant = (variant) => { // Audio-video variants may include both streams separately or may be // single multiplexed streams with multiple codecs. return (variant.video && variant.audio) || (variant.video && variant.video.codecs.includes(',')); }; if (manifest.variants.some(isAVVariant)) { shaka.log.debug('Found variant with audio and video content, ' + 'so filtering out audio-only content.'); manifest.variants = manifest.variants.filter(isAVVariant); } } /** * Create a new DrmEngine instance. This may be replaced by tests to create * fake instances. Configuration and initialization will be handled after * |createDrmEngine|. * * @param {shaka.media.DrmEngine.PlayerInterface} playerInterface * @return {!shaka.media.DrmEngine} */ createDrmEngine(playerInterface) { const updateExpirationTime = this.config_.drm.updateExpirationTime; return new shaka.media.DrmEngine(playerInterface, updateExpirationTime); } /** * Creates a new instance of NetworkingEngine. This can be replaced by tests * to create fake instances instead. * * @return {!shaka.net.NetworkingEngine} */ createNetworkingEngine() { /** @type {function(number, number)} */ const onProgressUpdated_ = (deltaTimeMs, bytesDownloaded) => { // In some situations, such as during offline storage, the abr manager // might not yet exist. Therefore, we need to check if abr manager has // been initialized before using it. if (this.abrManager_) { this.abrManager_.segmentDownloaded(deltaTimeMs, bytesDownloaded); } }; /** @type {shaka.net.NetworkingEngine.OnHeadersReceived} */ const onHeadersReceived_ = (headers, request, requestType) => { // Release a 'downloadheadersreceived' event. const name = shaka.Player.EventName.DownloadHeadersReceived; const data = { headers, request, requestType, }; this.dispatchEvent(this.makeEvent_(name, data)); }; /** @type {shaka.net.NetworkingEngine.OnDownloadFailed} */ const onDownloadFailed_ = (request, error, httpResponseCode, aborted) => { // Release a 'downloadfailed' event. const name = shaka.Player.EventName.DownloadFailed; const data = { request, error, httpResponseCode, aborted, }; this.dispatchEvent(this.makeEvent_(name, data)); }; return new shaka.net.NetworkingEngine( onProgressUpdated_, onHeadersReceived_, onDownloadFailed_); } /** * Creates a new instance of Playhead. This can be replaced by tests to * create fake instances instead. * * @param {?number} startTime * @return {!shaka.media.Playhead} */ createPlayhead(startTime) { goog.asserts.assert(this.manifest_, 'Must have manifest'); goog.asserts.assert(this.video_, 'Must have video'); return new shaka.media.MediaSourcePlayhead( this.video_, this.manifest_, this.config_.streaming, startTime, () => this.onSeek_(), (event) => this.dispatchEvent(event)); } /** * Create the observers for MSE playback. These observers are responsible for * notifying the app and player of specific events during MSE playback. * * @return {!shaka.media.PlayheadObserverManager} * @private */ createPlayheadObserversForMSE_() { goog.asserts.assert(this.manifest_, 'Must have manifest'); goog.asserts.assert(this.regionTimeline_, 'Must have region timeline'); goog.asserts.assert(this.video_, 'Must have video element'); // Create the region observer. This will allow us to notify the app when we // move in and out of timeline regions. const regionObserver = new shaka.media.RegionObserver(this.regionTimeline_); const onEnterRegion = (region, seeking) => { this.onRegionEvent_(shaka.Player.EventName.TimelineRegionEnter, region); }; const onExitRegion = (region, seeking) => { this.onRegionEvent_(shaka.Player.EventName.TimelineRegionExit, region); }; const onSkipRegion = (region, seeking) => { // If we are seeking, we don't want to surface the enter/exit events since // they didn't play through them. if (!seeking) { this.onRegionEvent_(shaka.Player.EventName.TimelineRegionEnter, region); this.onRegionEvent_(shaka.Player.EventName.TimelineRegionExit, region); } }; regionObserver.setListeners(onEnterRegion, onExitRegion, onSkipRegion); // Now that we have all our observers, create a manager for them. const manager = new shaka.media.PlayheadObserverManager(this.video_); manager.manage(regionObserver); return manager; } /** * Initialize and start the buffering system (observer and timer) so that we * can monitor our buffer lead during playback. * * @param {number} rebufferingGoal * @private */ startBufferManagement_(rebufferingGoal) { goog.asserts.assert( !this.bufferObserver_, 'No buffering observer should exist before initialization.'); goog.asserts.assert( !this.bufferPoller_, 'No buffer timer should exist before initialization.'); // Give dummy values, will be updated below. this.bufferObserver_ = new shaka.media.BufferingObserver(1, 2); // Force us back to a buffering state. This ensure everything is starting in // the same state. this.bufferObserver_.setState(shaka.media.BufferingObserver.State.STARVING); this.updateBufferingSettings_(rebufferingGoal); this.updateBufferState_(); // TODO: We should take some time to look into the effects of our // quarter-second refresh practice. We often use a quarter-second // but we have no documentation about why. this.bufferPoller_ = new shaka.util.Timer(() => { this.pollBufferState_(); }).tickEvery(/* seconds= */ 0.25); } /** * Updates the buffering thresholds based on the new rebuffering goal. * * @param {number} rebufferingGoal * @private */ updateBufferingSettings_(rebufferingGoal) { // The threshold to transition back to satisfied when starving. const starvingThreshold = rebufferingGoal; // The threshold to transition into starving when satisfied. // We use a "typical" threshold, unless the rebufferingGoal is unusually // low. // Then we force the value down to half the rebufferingGoal, since // starvingThreshold must be strictly larger than satisfiedThreshold for the // logic in BufferingObserver to work correctly. const satisfiedThreshold = Math.min( shaka.Player.TYPICAL_BUFFERING_THRESHOLD_, rebufferingGoal / 2); this.bufferObserver_.setThresholds(starvingThreshold, satisfiedThreshold); } /** * This method is called periodically to check what the buffering observer * says so that we can update the rest of the buffering behaviours. * * @private */ pollBufferState_() { goog.asserts.assert( this.video_, 'Need a media element to update the buffering observer'); goog.asserts.assert( this.bufferObserver_, 'Need a buffering observer to update'); let bufferedToEnd; switch (this.loadMode_) { case shaka.Player.LoadMode.SRC_EQUALS: bufferedToEnd = this.isBufferedToEndSrc_(); break; case shaka.Player.LoadMode.MEDIA_SOURCE: bufferedToEnd = this.isBufferedToEndMS_(); break; default: bufferedToEnd = false; break; } const bufferLead = shaka.media.TimeRangesUtils.bufferedAheadOf( this.video_.buffered, this.video_.currentTime); const stateChanged = this.bufferObserver_.update(bufferLead, bufferedToEnd); // If the state changed, we need to surface the event. if (stateChanged) { this.updateBufferState_(); } } /** * Create a new media source engine. This will ONLY be replaced by tests as a * way to inject fake media source engine instances. * * @param {!HTMLMediaElement} mediaElement * @param {!shaka.media.IClosedCaptionParser} closedCaptionsParser * @param {!shaka.extern.TextDisplayer} textDisplayer * @param {!function(!Array.<shaka.extern.ID3Metadata>, number, ?number)} * onMetadata * * @return {!shaka.media.MediaSourceEngine} */ createMediaSourceEngine(mediaElement, closedCaptionsParser, textDisplayer, onMetadata) { return new shaka.media.MediaSourceEngine( mediaElement, closedCaptionsParser, textDisplayer, onMetadata); } /** * Creates a new instance of StreamingEngine. This can be replaced by tests * to create fake instances instead. * * @return {!shaka.media.StreamingEngine} */ createStreamingEngine() { goog.asserts.assert( this.playhead_ && this.abrManager_ && this.mediaSourceEngine_ && this.manifest_, 'Must not be destroyed'); /** @type {shaka.media.StreamingEngine.PlayerInterface} */ const playerInterface = { getPresentationTime: () => this.playhead_.getTime(), getBandwidthEstimate: () => this.abrManager_.getBandwidthEstimate(), mediaSourceEngine: this.mediaSourceEngine_, netEngine: this.networkingEngine_, onError: (error) => this.onError_(error), onEvent: (event) => this.dispatchEvent(event), onManifestUpdate: () => this.onManifestUpdate_(), onSegmentAppended: () => this.onSegmentAppended_(), }; return new shaka.media.StreamingEngine(this.manifest_, playerInterface); } /** * Changes configuration settings on the Player. This checks the names of * keys and the types of values to avoid coding errors. If there are errors, * this logs them to the console and returns false. Correct fields are still * applied even if there are other errors. You can pass an explicit * <code>undefined</code> value to restore the default value. This has two * modes of operation: * * <p> * First, this can be passed a single "plain" object. This object should * follow the {@link shaka.extern.PlayerConfiguration} object. Not all fields * need to be set; unset fields retain their old values. * * <p> * Second, this can be passed two arguments. The first is the name of the key * to set. This should be a '.' separated path to the key. For example, * <code>'streaming.alwaysStreamText'</code>. The second argument is the * value to set. * * @param {string|!Object} config This should either be a field name or an * object. * @param {*=} value In the second mode, this is the value to set. * @return {boolean} True if the passed config object was valid, false if * there were invalid entries. * @export */ configure(config, value) { goog.asserts.assert(this.config_, 'Config must not be null!'); goog.asserts.assert(typeof(config) == 'object' || arguments.length == 2, 'String configs should have values!'); // ('fieldName', value) format if (arguments.length == 2 && typeof(config) == 'string') { config = shaka.util.ConfigUtils.convertToConfigObject(config, value); } goog.asserts.assert(typeof(config) == 'object', 'Should be an object!'); // Deprecate 'manifest.dash.defaultPresentationDelay' configuration. if (config['manifest'] && config['manifest']['dash'] && 'defaultPresentationDelay' in config['manifest']['dash']) { shaka.Deprecate.deprecateFeature(4, 'manifest.dash.defaultPresentationDelay configuration', 'Please Use manifest.defaultPresentationDelay instead.'); config['manifest']['defaultPresentationDelay'] = config['manifest']['dash']['defaultPresentationDelay']; delete config['manifest']['dash']['defaultPresentationDelay']; } // If lowLatencyMode is enabled, and inaccurateManifestTolerance and // rebufferingGoal are not specified, set inaccurateManifestTolerance to 0 // and rebufferingGoal to 0.01 by default for low latency streaming. if (config['streaming'] && config['streaming']['lowLatencyMode']) { if (config['streaming']['inaccurateManifestTolerance'] == undefined) { config['streaming']['inaccurateManifestTolerance'] = 0; } if (config['streaming']['rebufferingGoal'] == undefined) { config['streaming']['rebufferingGoal'] = 0.01; } } const ret = shaka.util.PlayerConfiguration.mergeConfigObjects( this.config_, config, this.defaultConfig_()); this.applyConfig_(); return ret; } /** * Apply config changes. * @private */ applyConfig_() { if (this.parser_) { const manifestConfig = shaka.util.ObjectUtils.cloneObject(this.config_.manifest); // Don't read video segments if the player is attached to an audio element if (this.video_ && this.video_.nodeName === 'AUDIO') { manifestConfig.disableVideo = true; } this.parser_.configure(manifestConfig); } if (this.drmEngine_) { this.drmEngine_.configure(this.config_.drm); } if (this.streamingEngine_) { this.streamingEngine_.configure(this.config_.streaming); // Need to apply the restrictions. try { // this.filterManifestWithRestrictions_() may throw. this.filterManifestWithRestrictions_(this.manifest_); } catch (error) { this.onError_(error); } if (this.abrManager_) { // Update AbrManager variants to match these new settings. this.updateAbrManagerVariants_(); } // If the streams we are playing are restricted, we need to switch. const activeVariant = this.streamingEngine_.getCurrentVariant(); if (activeVariant) { if (!activeVariant.allowedByApplication || !activeVariant.allowedByKeySystem) { shaka.log.debug('Choosing new variant after changing configuration'); this.chooseVariantAndSwitch_(); } } } if (this.networkingEngine_) { this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS); } if (this.mediaSourceEngine_) { const textDisplayerFactory = this.config_.textDisplayFactory; if (this.lastTextFactory_ != textDisplayerFactory) { const displayer = shaka.util.Functional.callFactory(textDisplayerFactory); this.mediaSourceEngine_.setTextDisplayer(displayer); this.lastTextFactory_ = textDisplayerFactory; if (this.streamingEngine_) { // Reload the text stream, so the cues will load again. this.streamingEngine_.reloadTextStream(); } } } if (this.abrManager_) { this.abrManager_.configure(this.config_.abr); // Simply enable/disable ABR with each call, since multiple calls to these // methods have no effect. if (this.config_.abr.enabled) { this.abrManager_.enable(); } else { this.abrManager_.disable(); } this.onAbrStatusChanged_(); } if (this.bufferObserver_) { let rebufferThreshold = this.config_.streaming.rebufferingGoal; if (this.manifest_) { rebufferThreshold = Math.max(rebufferThreshold, this.manifest_.minBufferTime); } this.updateBufferingSettings_(rebufferThreshold); } if (this.manifest_) { shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline, this.config_.playRangeStart, this.config_.playRangeEnd); } } /** * Return a copy of the current configuration. Modifications of the returned * value will not affect the Player's active configuration. You must call * <code>player.configure()</code> to make changes. * * @return {shaka.extern.PlayerConfiguration} * @export */ getConfiguration() { goog.asserts.assert(this.config_, 'Config must not be null!'); const ret = this.defaultConfig_(); shaka.util.PlayerConfiguration.mergeConfigObjects( ret, this.config_, this.defaultConfig_()); return ret; } /** * Return a reference to the current configuration. Modifications to the * returned value will affect the Player's active configuration. This method * is not exported as sharing configuration with external objects is not * supported. * * @return {shaka.extern.PlayerConfiguration} */ getSharedConfiguration() { goog.asserts.assert( this.config_, 'Cannot call getSharedConfiguration after call destroy!'); return this.config_; } /** * Returns the ratio of video length buffered compared to buffering Goal * @return {number} * @export */ getBufferFullness() { if (this.video_) { const bufferedLength = this.video_.buffered.length; const bufferedEnd = bufferedLength ? this.video_.buffered.end(bufferedLength - 1) : 0; const bufferingGoal = this.getConfiguration().streaming.bufferingGoal; const lengthToBeBuffered = Math.min(this.video_.currentTime + bufferingGoal, this.seekRange().end); if (bufferedEnd >= lengthToBeBuffered) { return 1; } else if (bufferedEnd <= this.video_.currentTime) { return 0; } else if (bufferedEnd < lengthToBeBuffered) { return ((bufferedEnd - this.video_.currentTime) / (lengthToBeBuffered - this.video_.currentTime)); } } return 0; } /** * Reset configuration to default. * @export */ resetConfiguration() { goog.asserts.assert(this.config_, 'Cannot be destroyed'); // Remove the old keys so we remove open-ended dictionaries like drm.servers // but keeps the same object reference. for (const key in this.config_) { delete this.config_[key]; } shaka.util.PlayerConfiguration.mergeConfigObjects( this.config_, this.defaultConfig_(), this.defaultConfig_()); this.applyConfig_(); } /** * Get the current load mode. * * @return {shaka.Player.LoadMode} * @export */ getLoadMode() { return this.loadMode_; } /** * Get the media element that the player is currently using to play loaded * content. If the player has not loaded content, this will return * <code>null</code>. * * @return {HTMLMediaElement} * @export */ getMediaElement() { return this.video_; } /** * @return {shaka.net.NetworkingEngine} A reference to the Player's networking * engine. Applications may use this to make requests through Shaka's * networking plugins. * @export */ getNetworkingEngine() { return this.networkingEngine_; } /** * Get the uri to the asset that the player has loaded. If the player has not * loaded content, this will return <code>null</code>. * * @return {?string} * @export */ getAssetUri() { return this.assetUri_; } /** * Returns a shaka.ads.AdManager instance, responsible for Dynamic * Ad Insertion functionality. * * @return {shaka.extern.IAdManager} * @export */ getAdManager() { // NOTE: this clause is redundant, but it keeps the compiler from // inlining this function. Inlining leads to setting the adManager // not taking effect in the compiled build. // Closure has a @noinline flag, but apparently not all cases are // supported by it, and ours isn't. // If they expand support, we might be able to get rid of this // clause. if (!this.adManager_) { return null; } return this.adManager_; } /** * Get if the player is playing live content. If the player has not loaded * content, this will return <code>false</code>. * * @return {boolean} * @export */ isLive() { if (this.manifest_) { return this.manifest_.presentationTimeline.isLive(); } // For native HLS, the duration for live streams seems to be Infinity. if (this.video_ && this.video_.src) { return this.video_.duration == Infinity; } return false; } /** * Get if the player is playing in-progress content. If the player has not * loaded content, this will return <code>false</code>. * * @return {boolean} * @export */ isInProgress() { return this.manifest_ ? this.manifest_.presentationTimeline.isInProgress() : false; } /** * Check if the manifest contains only audio-only content. If the player has * not loaded content, this will return <code>false</code>. * * <p> * The player does not support content that contain more than one type of * variants (i.e. mixing audio-only, video-only, audio-video). Content will be * filtered to only contain one type of variant. * * @return {boolean} * @export */ isAudioOnly() { if (this.manifest_) { const variants = this.manifest_.variants; if (!variants.length) { return false; } // Note that if there are some audio-only variants and some audio-video // variants, the audio-only variants are removed during filtering. // Therefore if the first variant has no video, that's sufficient to say // it is audio-only content. return !variants[0].video; } else if (this.video_ && this.video_.src) { // If we have video track info, use that. It will be the least // error-prone way with native HLS. In contrast, videoHeight might be // unset until the first frame is loaded. Since isAudioOnly is queried // by the UI on the 'trackschanged' event, the videoTracks info should be // up-to-date. if (this.video_.videoTracks) { return this.video_.videoTracks.length == 0; } // We cast to the more specific HTMLVideoElement to access videoHeight. // This might be an audio element, though, in which case videoHeight will // be undefined at runtime. For audio elements, this will always return // true. const video = /** @type {HTMLVideoElement} */(this.video_); return video.videoHeight == 0; } else { return false; } } /** * Return the value of lowLatencyMode configuration. * @return {boolean} * @private */ isLowLatencyMode_() { return this.config_.streaming.lowLatencyMode; } /** * Return the value of autoLowLatencyMode configuration. * @return {boolean} * @private */ isAutoLowLatencyMode_() { return this.config_.streaming.autoLowLatencyMode; } /** * Get the range of time (in seconds) that seeking is allowed. If the player * has not loaded content, this will return a range from 0 to 0. * * @return {{start: number, end: number}} * @export */ seekRange() { if (this.manifest_) { const timeline = this.manifest_.presentationTimeline; return { 'start': timeline.getSeekRangeStart(), 'end': timeline.getSeekRangeEnd(), }; } // If we have loaded content with src=, we ask the video element for its // seekable range. This covers both plain mp4s and native HLS playbacks. if (this.video_ && this.video_.src) { const seekable = this.video_.seekable; if (seekable.length) { return { 'start': seekable.start(0), 'end': seekable.end(seekable.length - 1), }; } } return {'start': 0, 'end': 0}; } /** * Go to live in a live stream. * * @export */ goToLive() { if (this.isLive()) { this.video_.currentTime = this.seekRange().end; } else { shaka.log.warning('goToLive is for live streams!'); } } /** * Get the key system currently used by EME. If EME is not being used, this * will return an empty string. If the player has not loaded content, this * will return an empty string. * * @return {string} * @export */ keySystem() { return shaka.media.DrmEngine.keySystem(this.drmInfo()); } /** * Get the drm info used to initialize EME. If EME is not being used, this * will return <code>null</code>. If the player is idle or has not initialized * EME yet, this will return <code>null</code>. * * @return {?shaka.extern.DrmInfo} * @export */ drmInfo() { return this.drmEngine_ ? this.drmEngine_.getDrmInfo() : null; } /** * Get the drm engine. * This method should only be used for testing. Applications SHOULD NOT * use this in production. * * @return {?shaka.media.DrmEngine} */ getDrmEngine() { return this.drmEngine_; } /** * Get the next known expiration time for any EME session. If the session * never expires, this will return <code>Infinity</code>. If there are no EME * sessions, this will return <code>Infinity</code>. If the player has not * loaded content, this will return <code>Infinity</code>. * * @return {number} * @export */ getExpiration() { return this.drmEngine_ ? this.drmEngine_.getExpiration() : Infinity; } /** * Gets a map of EME key ID to the current key status. * * @return {!Object<string, string>} * @export */ getKeyStatuses() { return this.drmEngine_ ? this.drmEngine_.getKeyStatuses() : {}; } /** * Check if the player is currently in a buffering state (has too little * content to play smoothly). If the player has not loaded content, this will * return <code>false</code>. * * @return {boolean} * @export */ isBuffering() { const State = shaka.media.BufferingObserver.State; return this.bufferObserver_ ? this.bufferObserver_.getState() == State.STARVING : false; } /** * Get the playback rate of what is playing right now. If we are using trick * play, this will return the trick play rate. * If no content is playing, this will return 0. * If content is buffering, this will return the expected playback rate once * the video starts playing. * * <p> * If the player has not loaded content, this will return a playback rate of * 0. * * @return {number} * @export */ getPlaybackRate() { if (!this.video_) { return 0; } return this.playRateController_ ? this.playRateController_.getRealRate() : 1; } /** * Enable trick play to skip through content without playing by repeatedly * seeking. For example, a rate of 2.5 would result in 2.5 seconds of content * being skipped every second. A negative rate will result in moving * backwards. * * <p> * If the player has not loaded content or is still loading content this will * be a no-op. Wait until <code>load</code> has completed before calling. * * <p> * Trick play will be canceled automatically if the playhead hits the * beginning or end of the seekable range for the content. * * @param {number} rate * @export */ trickPlay(rate) { // A playbackRate of 0 is used internally when we are in a buffering state, // and doesn't make sense for trick play. If you set a rate of 0 for trick // play, we will reject it and issue a warning. If it happens during a // test, we will fail the test through this assertion. goog.asserts.assert(rate != 0, 'Should never set a trick play rate of 0!'); if (rate == 0) { shaka.log.alwaysWarn('A trick play rate of 0 is unsupported!'); return; } if (this.video_.paused) { // Our fast forward is implemented with playbackRate and needs the video // to be playing (to not be paused) to take immediate effect. // If the video is paused, "unpause" it. this.video_.play(); } this.playRateController_.set(rate); if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) { this.abrManager_.playbackRateChanged(rate); this.streamingEngine_.setTrickPlay(Math.abs(rate) > 1); } } /** * Cancel trick-play. If the player has not loaded content or is still loading * content this will be a no-op. * * @export */ cancelTrickPlay() { const defaultPlaybackRate = this.playRateController_.getDefaultRate(); if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) { this.playRateController_.set(defaultPlaybackRate); } if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) { this.playRateController_.set(defaultPlaybackRate); this.abrManager_.playbackRateChanged(defaultPlaybackRate); this.streamingEngine_.setTrickPlay(false); } } /** * Return a list of variant tracks that can be switched to. * * <p> * If the player has not loaded content, this will return an empty list. * * @return {!Array.<shaka.extern.Track>} * @export */ getVariantTracks() { if (this.manifest_) { const currentVariant = this.streamingEngine_ ? this.streamingEngine_.getCurrentVariant() : null; const tracks = []; // Convert each variant to a track. for (const variant of this.manifest_.variants) { if (!shaka.util.StreamUtils.isPlayable(variant)) { continue; } const track = shaka.util.StreamUtils.variantToTrack(variant); track.active = variant == currentVariant; tracks.push(track); } return tracks; } else if (this.video_ && this.video_.audioTracks) { // Safari's native HLS always shows a single element in videoTracks. // You can't use that API to change resolutions. But we can use // audioTracks to generate a variant list that is usable for changing // languages. const audioTracks = Array.from(this.video_.audioTracks); return audioTracks.map((audio) => shaka.util.StreamUtils.html5AudioTrackToTrack(audio)); } else { return []; } } /** * Return a list of text tracks that can be switched to. * * <p> * If the player has not loaded content, this will return an empty list. * * @return {!Array.<shaka.extern.Track>} * @export */ getTextTracks() { if (this.manifest_) { const currentTextStream = this.streamingEngine_ ? this.streamingEngine_.getCurrentTextStream() : null; const tracks = []; // Convert all selectable text streams to tracks. for (const text of this.manifest_.textStreams) { const track = shaka.util.StreamUtils.textStreamToTrack(text); track.active = text == currentTextStream; tracks.push(track); } return tracks; } else if (this.video_ && this.video_.src && this.video_.textTracks) { const textTracks = this.getFilteredTextTracks_(); const StreamUtils = shaka.util.StreamUtils; return textTracks.map((text) => StreamUtils.html5TextTrackToTrack(text)); } else { return []; } } /** * Return a list of image tracks that can be switched to. * * If the player has not loaded content, this will return an empty list. * * @return {!Array.<shaka.extern.Track>} * @export */ getImageTracks() { if (this.manifest_) { const imageStreams = this.manifest_.imageStreams; const StreamUtils = shaka.util.StreamUtils; return imageStreams.map((image) => StreamUtils.imageStreamToTrack(image)); } else { return []; } } /** * Return a Thumbnail object from a image track Id and time. * * If the player has not loaded content, this will return a null. * * @param {number} trackId * @param {number} time * @return {!Promise.<?shaka.extern.Thumbnail>} * @export */ async getThumbnails(trackId, time) { if (this.manifest_) { const imageStream = this.manifest_.imageStreams.find( (stream) => stream.id == trackId); if (!imageStream) { return null; } if (!imageStream.segmentIndex) { await imageStream.createSegmentIndex(); } const referencePosition = imageStream.segmentIndex.find(time); if (referencePosition == null) { return null; } const reference = imageStream.segmentIndex.get(referencePosition); const tilesLayout = reference.getTilesLayout() || imageStream.tilesLayout; // This expression is used to detect one or more numbers (0-9) followed // by an x and after one or more numbers (0-9) const match = /(\d+)x(\d+)/.exec(tilesLayout); if (!match) { shaka.log.warning('Tiles layout does not contain a valid format ' + ' (columns x rows)'); return null; } const fullImageWidth = imageStream.width || 0; const fullImageHeight = imageStream.height || 0; const columns = parseInt(match[1], 10); const rows = parseInt(match[2], 10); const width = fullImageWidth / columns; const height = fullImageHeight / rows; const totalImages = columns * rows; const segmentDuration = reference.trueEndTime - reference.startTime; const thumbnailDuration = segmentDuration / totalImages; let thumbnailTime = reference.startTime; let positionX = 0; let positionY = 0; // If the number of images in the segment is greater than 1, we have to // find the correct image. For that we will return to the app the // coordinates of the position of the correct image. // Image search is always from left to right and top to bottom. // Note: The time between images within the segment is always // equidistant. // // Eg: Total images 5, tileLayout 5x1, segmentDuration 5, thumbnailTime 2 // positionX = 0.4 * fullImageWidth // positionY = 0 if (totalImages > 1) { const thumbnailPosition = Math.floor((time - reference.startTime) / thumbnailDuration); thumbnailTime = reference.startTime + (thumbnailPosition * thumbnailDuration); positionX = (thumbnailPosition % columns) * width; positionY = Math.floor(thumbnailPosition / columns) * height; } return { height: height, positionX: positionX, positionY: positionY, startTime: thumbnailTime, duration: thumbnailDuration, uris: reference.getUris(), width: width, }; } return null; } /** * Select a specific text track. <code>track</code> should come from a call to * <code>getTextTracks</code>. If the track is not found, this will be a * no-op. If the player has not loaded content, this will be a no-op. * * <p> * Note that <code>AdaptationEvents</code> are not fired for manual track * selections. * * @param {shaka.extern.Track} track * @export */ selectTextTrack(track) { if (this.manifest_ && this.streamingEngine_) { const stream = this.manifest_.textStreams.find( (stream) => stream.id == track.id); if (!stream) { shaka.log.error('No stream with id', track.id); return; } if (stream == this.streamingEngine_.getCurrentTextStream()) { shaka.log.debug('Text track already selected.'); return; } // Add entries to the history. this.addTextStreamToSwitchHistory_(stream, /* fromAdaptation= */ false); this.streamingEngine_.switchTextStream(stream); this.onTextChanged_(); // Workaround for https://github.com/google/shaka-player/issues/1299 // When track is selected, back-propagate the language to // currentTextLanguage_. this.currentTextLanguage_ = stream.language; } else if (this.video_ && this.video_.src && this.video_.textTracks) { const textTracks = this.getFilteredTextTracks_(); for (const textTrack of textTracks) { if (shaka.util.StreamUtils.html5TrackId(textTrack) == track.id) { // Leave the track in 'hidden' if it's selected but not showing. textTrack.mode = this.isTextVisible_ ? 'showing' : 'hidden'; } else { // Safari allows multiple text tracks to have mode == 'showing', so be // explicit in resetting the others. textTrack.mode = 'disabled'; } } this.onTextChanged_(); } } /** * Select a specific variant track to play. <code>track</code> should come * from a call to <code>getVariantTracks</code>. If <code>track</code> cannot * be found, this will be a no-op. If the player has not loaded content, this * will be a no-op. * * <p> * Changing variants will take effect once the currently buffered content has * been played. To force the change to happen sooner, use * <code>clearBuffer</code> with <code>safeMargin</code>. Setting * <code>clearBuffer</code> to <code>true</code> will clear all buffered * content after <code>safeMargin</code>, allowing the new variant to start * playing sooner. * * <p> * Note that <code>AdaptationEvents</code> are not fired for manual track * selections. * * @param {shaka.extern.Track} track * @param {boolean=} clearBuffer * @param {number=} safeMargin Optional amount of buffer (in seconds) to * retain when clearing the buffer. Useful for switching variant quickly * without causing a buffering event. Defaults to 0 if not provided. Ignored * if clearBuffer is false. Can cause hiccups on some browsers if chosen too * small, e.g. The amount of two segments is a fair minimum to consider as * safeMargin value. * @export */ selectVariantTrack(track, clearBuffer = false, safeMargin = 0) { if (this.manifest_ && this.streamingEngine_) { if (this.config_.abr.enabled) { shaka.log.alwaysWarn('Changing tracks while abr manager is enabled ' + 'will likely result in the selected track ' + 'being overriden. Consider disabling abr before ' + 'calling selectVariantTrack().'); } const variant = this.manifest_.variants.find( (variant) => variant.id == track.id); if (!variant) { shaka.log.error('No variant with id', track.id); return; } // Double check that the track is allowed to be played. The track list // should only contain playable variants, but if restrictions change and // |selectVariantTrack| is called before the track list is updated, we // could get a now-restricted variant. if (!shaka.util.StreamUtils.isPlayable(variant)) { shaka.log.error('Unable to switch to restricted track', track.id); return; } this.switchVariant_(variant, /* fromAdaptation= */ false, clearBuffer, safeMargin); // Workaround for https://github.com/google/shaka-player/issues/1299 // When track is selected, back-propagate the language to // currentAudioLanguage_. this.currentAdaptationSetCriteria_ = new shaka.media.ExampleBasedCriteria( variant); // Update AbrManager variants to match these new settings. this.updateAbrManagerVariants_(); } else if (this.video_ && this.video_.audioTracks) { // Safari's native HLS won't let you choose an explicit variant, though // you can choose audio languages this way. const audioTracks = Array.from(this.video_.audioTracks); for (const audioTrack of audioTracks) { if (shaka.util.StreamUtils.html5TrackId(audioTrack) == track.id) { // This will reset the "enabled" of other tracks to false. this.switchHtml5Track_(audioTrack); return; } } } } /** * Return a list of audio language-role combinations available. If the * player has not loaded any content, this will return an empty list. * * @return {!Array.<shaka.extern.LanguageRole>} * @export */ getAudioLanguagesAndRoles() { return shaka.Player.getLanguageAndRolesFrom_(this.getVariantTracks()); } /** * Return a list of text language-role combinations available. If the player * has not loaded any content, this will be return an empty list. * * @return {!Array.<shaka.extern.LanguageRole>} * @export */ getTextLanguagesAndRoles() { return shaka.Player.getLanguageAndRolesFrom_(this.getTextTracks()); } /** * Return a list of audio languages available. If the player has not loaded * any content, this will return an empty list. * * @return {!Array.<string>} * @export */ getAudioLanguages() { return Array.from(shaka.Player.getLanguagesFrom_(this.getVariantTracks())); } /** * Return a list of text languages available. If the player has not loaded * any content, this will return an empty list. * * @return {!Array.<string>} * @export */ getTextLanguages() { return Array.from(shaka.Player.getLanguagesFrom_(this.getTextTracks())); } /** * Sets the current audio language and current variant role to the selected * language and role, and chooses a new variant if need be. If the player has * not loaded any content, this will be a no-op. * * @param {string} language * @param {string=} role * @export */ selectAudioLanguage(language, role) { const LanguageUtils = shaka.util.LanguageUtils; if (this.manifest_ && this.playhead_) { this.currentAdaptationSetCriteria_ = new shaka.media.PreferenceBasedCriteria(language, role || '', /* channelCount= */ 0, /* label= */ ''); const diff = (a, b) => { if (!a.video && !b.video) { return 0; } else if (!a.video || !b.video) { return Infinity; } else { return Math.abs((a.video.height || 0) - (b.video.height || 0)) + Math.abs((a.video.width || 0) - (b.video.width || 0)); } }; // Find the variant whose size is closest to the active variant. This // ensures we stay at about the same resolution when just changing the // language/role. const active = this.streamingEngine_.getCurrentVariant(); const set = this.currentAdaptationSetCriteria_.create(this.manifest_.variants); let bestVariant = null; for (const curVariant of set.values()) { if (!bestVariant || diff(bestVariant, active) > diff(curVariant, active)) { bestVariant = curVariant; } } if (bestVariant) { const track = shaka.util.StreamUtils.variantToTrack(bestVariant); this.selectVariantTrack(track, /* clearBuffer= */ true); return; } // If we haven't switched yet, just use ABR to find a new track. this.chooseVariantAndSwitch_(); } else if (this.video_ && this.video_.audioTracks) { const audioTracks = Array.from(this.video_.audioTracks); const selectedLanguage = LanguageUtils.normalize(language); let languageMatch = null; let languageAndRoleMatch = null; for (const audioTrack of audioTracks) { const track = shaka.util.StreamUtils.html5AudioTrackToTrack(audioTrack); if (LanguageUtils.normalize(track.language) == selectedLanguage) { languageMatch = audioTrack; if (role) { if (track.roles.includes(role)) { languageAndRoleMatch = audioTrack; } } else { // no role if (track.roles.length == 0) { languageAndRoleMatch = audioTrack; } } } } if (languageAndRoleMatch) { this.switchHtml5Track_(languageAndRoleMatch); } else if (languageMatch) { this.switchHtml5Track_(languageMatch); } } } /** * Sets the current text language and current text role to the selected * language and role, and chooses a new variant if need be. If the player has * not loaded any content, this will be a no-op. * * @param {string} language * @param {string=} role * @param {boolean=} forced * @export */ selectTextLanguage(language, role, forced = false) { const LanguageUtils = shaka.util.LanguageUtils; if (this.manifest_ && this.playhead_) { this.currentTextLanguage_ = language; this.currentTextRole_ = role || ''; this.currentTextForced_ = forced; const chosenText = this.chooseTextStream_(); if (chosenText) { if (chosenText == this.streamingEngine_.getCurrentTextStream()) { shaka.log.debug('Text track already selected.'); return; } this.addTextStreamToSwitchHistory_( chosenText, /* fromAdaptation= */ false); if (this.shouldStreamText_()) { this.streamingEngine_.switchTextStream(chosenText); this.onTextChanged_(); } } } else { const selectedLanguage = LanguageUtils.normalize(language); const track = this.getTextTracks().find((t) => { return LanguageUtils.normalize(t.language) == selectedLanguage && (!role || t.roles.includes(role)) && t.forced == forced; }); if (track) { this.selectTextTrack(track); } } } /** * Select variant tracks that have a given label. This assumes the * label uniquely identifies an audio stream, so all the variants * are expected to have the same variant.audio. * * @param {string} label * @export */ selectVariantsByLabel(label) { if (this.manifest_ && this.playhead_) { let firstVariantWithLabel = null; for (const variant of this.manifest_.variants) { if (variant.audio.label == label) { firstVariantWithLabel = variant; break; } } if (firstVariantWithLabel == null) { shaka.log.warning('No variants were found with label: ' + label + '. Ignoring the request to switch.'); return; } // Label is a unique identifier of a variant's audio stream. // Because of that we assume that all the variants with the same // label have the same language. this.currentAdaptationSetCriteria_ = new shaka.media.PreferenceBasedCriteria( firstVariantWithLabel.language, '', 0, label); this.chooseVariantAndSwitch_(); } } /** * Check if the text displayer is enabled. * * @return {boolean} * @export */ isTextTrackVisible() { const expected = this.isTextVisible_; if (this.mediaSourceEngine_) { // Make sure our values are still in-sync. const actual = this.mediaSourceEngine_.getTextDisplayer().isTextVisible(); goog.asserts.assert( actual == expected, 'text visibility has fallen out of sync'); // Always return the actual value so that the app has the most accurate // information (in the case that the values come out of sync in prod). return actual; } else if (this.video_ && this.video_.src && this.video_.textTracks) { const textTracks = this.getFilteredTextTracks_(); return textTracks.some((t) => t.mode == 'showing'); } return expected; } /** * Return a list of chapters tracks. * * @return {!Array.<shaka.extern.Track>} * @export */ getChaptersTracks() { if (this.video_ && this.video_.src && this.video_.textTracks) { const textTracks = this.getChaptersTracks_(); const StreamUtils = shaka.util.StreamUtils; return textTracks.map((text) => StreamUtils.html5TextTrackToTrack(text)); } else { return []; } } /** * This returns the list of chapters. * * @param {string} language * @return {!Array.<shaka.extern.Chapter>} * @export */ getChapters(language) { const LanguageUtils = shaka.util.LanguageUtils; const inputlanguage = LanguageUtils.normalize(language); const chaptersTracks = this.getChaptersTracks_(); const chaptersTrack = chaptersTracks .find((t) => LanguageUtils.normalize(t.language) == inputlanguage); if (!chaptersTrack || !chaptersTrack.cues) { return []; } const chapters = []; for (const cue of chaptersTrack.cues) { /** @type {shaka.extern.Chapter} */ const chapter = { title: cue.text, startTime: cue.startTime, endTime: cue.endTime, }; chapters.push(chapter); } return chapters; } /** * Ignore the TextTracks with the 'metadata' or 'chapters' kind, or the one * generated by the SimpleTextDisplayer. * * @return {!Array.<TextTrack>} * @private */ getFilteredTextTracks_() { goog.asserts.assert(this.video_.textTracks, 'TextTracks should be valid.'); return Array.from(this.video_.textTracks) .filter((t) => t.kind != 'metadata' && t.kind != 'chapters' && t.label != shaka.Player.TextTrackLabel); } /** * Get the TextTracks with the 'metadata' kind. * * @return {!Array.<TextTrack>} * @private */ getMetadataTracks_() { goog.asserts.assert(this.video_.textTracks, 'TextTracks should be valid.'); return Array.from(this.video_.textTracks) .filter((t) => t.kind == 'metadata'); } /** * Get the TextTracks with the 'chapters' kind. * * @return {!Array.<TextTrack>} * @private */ getChaptersTracks_() { goog.asserts.assert(this.video_.textTracks, 'TextTracks should be valid.'); return Array.from(this.video_.textTracks) .filter((t) => t.kind == 'chapters'); } /** * Enable or disable the text displayer. If the player is in an unloaded * state, the request will be applied next time content is loaded. * * @param {boolean} isVisible * @export */ setTextTrackVisibility(isVisible) { const oldVisibilty = this.isTextVisible_; // Convert to boolean in case apps pass 0/1 instead false/true. const newVisibility = !!isVisible; if (oldVisibilty == newVisibility) { return; } this.isTextVisible_ = newVisibility; // Hold of on setting the text visibility until we have all the components // we need. This ensures that they stay in-sync. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) { this.mediaSourceEngine_.getTextDisplayer() .setTextVisibility(newVisibility); // When the user wants to see captions, we stream captions. When the user // doesn't want to see captions, we don't stream captions. This is to // avoid bandwidth consumption by an unused resource. The app developer // can override this and configure us to always stream captions. if (!this.config_.streaming.alwaysStreamText) { if (newVisibility) { if (this.streamingEngine_.getCurrentTextStream()) { // We already have a selected text stream. } else { // Find the text stream that best matches the user's preferences. const streams = shaka.util.StreamUtils.filterStreamsByLanguageAndRole( this.manifest_.textStreams, this.currentTextLanguage_, this.currentTextRole_, this.currentTextForced_); // It is possible that there are no streams to play. if (streams.length > 0) { this.streamingEngine_.switchTextStream(streams[0]); this.onTextChanged_(); } } } else { this.streamingEngine_.unloadTextStream(); } } } else if (this.video_ && this.video_.src && this.video_.textTracks) { const textTracks = this.getFilteredTextTracks_(); // Find the active track by looking for one which is not disabled. This // is the only way to identify the track which is currently displayed. // Set it to 'showing' or 'hidden' based on newVisibility. for (const textTrack of textTracks) { if (textTrack.mode != 'disabled') { textTrack.mode = newVisibility ? 'showing' : 'hidden'; } } } // We need to fire the event after we have updated everything so that // everything will be in a stable state when the app responds to the // event. this.onTextTrackVisibility_(); } /** * Get the current playhead position as a date. This should only be called * when the player has loaded a live stream. If the player has not loaded a * live stream, this will return <code>null</code>. * * @return {Date} * @export */ getPlayheadTimeAsDate() { if (!this.isLive()) { shaka.log.warning('getPlayheadTimeAsDate is for live streams!'); return null; } const walkerPayload = this.walker_.getCurrentPayload(); let presentationTime = 0; if (this.playhead_) { presentationTime = this.playhead_.getTime(); } else if (walkerPayload) { if (walkerPayload.startTime == null) { // A live stream with no requested start time and no playhead yet. We // would start at the live edge, but we don't have that yet, so return // the current date & time. return new Date(); } else { // A specific start time has been requested. This is what Playhead will // use once it is created. presentationTime = walkerPayload.startTime; } } if (this.manifest_) { const timeline = this.manifest_.presentationTimeline; const startTime = timeline.getPresentationStartTime(); return new Date(/* ms= */ (startTime + presentationTime) * 1000); } else if (this.video_ && this.video_.getStartDate) { // Apple's native HLS gives us getStartDate(), which is only available if // EXT-X-PROGRAM-DATETIME is in the playlist. const startDate = this.video_.getStartDate(); if (isNaN(startDate.getTime())) { shaka.log.warning( 'EXT-X-PROGRAM-DATETIME required to get playhead time as Date!'); return null; } return new Date(startDate.getTime() + (presentationTime * 1000)); } else { shaka.log.warning('No way to get playhead time as Date!'); return null; } } /** * Get the presentation start time as a date. This should only be called when * the player has loaded a live stream. If the player has not loaded a live * stream, this will return <code>null</code>. * * @return {Date} * @export */ getPresentationStartTimeAsDate() { if (!this.isLive()) { shaka.log.warning('getPresentationStartTimeAsDate is for live streams!'); return null; } if (this.manifest_) { const timeline = this.manifest_.presentationTimeline; const startTime = timeline.getPresentationStartTime(); goog.asserts.assert(startTime != null, 'Presentation start time should not be null!'); return new Date(/* ms= */ startTime * 1000); } else if (this.video_ && this.video_.getStartDate) { // Apple's native HLS gives us getStartDate(), which is only available if // EXT-X-PROGRAM-DATETIME is in the playlist. const startDate = this.video_.getStartDate(); if (isNaN(startDate.getTime())) { shaka.log.warning( 'EXT-X-PROGRAM-DATETIME required to get presentation start time ' + 'as Date!'); return null; } return startDate; } else { shaka.log.warning('No way to get presentation start time as Date!'); return null; } } /** * Get information about what the player has buffered. If the player has not * loaded content or is currently loading content, the buffered content will * be empty. * * @return {shaka.extern.BufferedInfo} * @export */ getBufferedInfo() { if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) { return this.mediaSourceEngine_.getBufferedInfo(); } const info = { total: [], audio: [], video: [], text: [], }; if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) { const TimeRangesUtils = shaka.media.TimeRangesUtils; info.total = TimeRangesUtils.getBufferedInfo(this.video_.buffered); } return info; } /** * Get statistics for the current playback session. If the player is not * playing content, this will return an empty stats object. * * @return {shaka.extern.Stats} * @export */ getStats() { // If the Player is not in a fully-loaded state, then return an empty stats // blob so that this call will never fail. const loaded = this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE || this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS; if (!loaded) { return shaka.util.Stats.getEmptyBlob(); } this.updateStateHistory_(); goog.asserts.assert(this.video_, 'If we have stats, we should have video_'); const element = /** @type {!HTMLVideoElement} */ (this.video_); const completionRatio = element.currentTime / element.duration; if (!isNaN(completionRatio)) { this.stats_.setCompletionPercent(Math.round(100 * completionRatio)); } if (element.getVideoPlaybackQuality) { const info = element.getVideoPlaybackQuality(); this.stats_.setDroppedFrames( Number(info.droppedVideoFrames), Number(info.totalVideoFrames)); this.stats_.setCorruptedFrames(Number(info.corruptedVideoFrames)); } const licenseSeconds = this.drmEngine_ ? this.drmEngine_.getLicenseTime() : NaN; this.stats_.setLicenseTime(licenseSeconds); if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) { // Event through we are loaded, it is still possible that we don't have a // variant yet because we set the load mode before we select the first // variant to stream. const variant = this.streamingEngine_.getCurrentVariant(); if (variant) { const rate = this.playRateController_ ? this.playRateController_.getRealRate() : 1; const variantBandwidth = rate * variant.bandwidth; // TODO: Should include text bandwidth if it enabled. const currentStreamBandwidth = variantBandwidth; this.stats_.setCurrentStreamBandwidth(currentStreamBandwidth); } if (variant && variant.video) { this.stats_.setResolution( /* width= */ variant.video.width || NaN, /* height= */ variant.video.height || NaN); } if (this.isLive()) { const now = this.getPresentationStartTimeAsDate().valueOf() + this.seekRange().end * 1000; const latency = (Date.now() - now) / 1000; this.stats_.setLiveLatency(latency); } if (this.manifest_ && this.manifest_.presentationTimeline) { const maxSegmentDuration = this.manifest_.presentationTimeline.getMaxSegmentDuration(); this.stats_.setMaxSegmentDuration(maxSegmentDuration); } const estimate = this.abrManager_.getBandwidthEstimate(); this.stats_.setBandwidthEstimate(estimate); } return this.stats_.getBlob(); } /** * Adds the given text track to the loaded manifest. <code>load()</code> must * resolve before calling. The presentation must have a duration. * * This returns the created track, which can immediately be selected by the * application. The track will not be automatically selected. * * @param {string} uri * @param {string} language * @param {string} kind * @param {string=} mimeType * @param {string=} codec * @param {string=} label * @param {boolean=} forced * @return {shaka.extern.Track} * @export */ addTextTrack(uri, language, kind, mimeType, codec, label, forced = false) { shaka.Deprecate.deprecateFeature(4, 'addTextTrack', 'Please use an addTextTrackAsync.'); if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE && this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) { shaka.log.error( 'Must call load() and wait for it to resolve before adding text ' + 'tracks.'); throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.PLAYER, shaka.util.Error.Code.CONTENT_NOT_LOADED); } if (!mimeType) { // Try using the uri extension. const extension = shaka.media.ManifestParser.getExtension(uri); mimeType = shaka.Player.TEXT_EXTENSIONS_TO_MIME_TYPES_[extension]; if (!mimeType) { shaka.log.error( 'The mimeType has not been provided and it could not be deduced ' + 'from its extension.'); throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.TEXT_COULD_NOT_GUESS_MIME_TYPE, extension); } } if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) { if (mimeType != 'text/vtt') { shaka.log.error('Only WebVTT is supported when using src='); throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.TEXT_ONLY_WEBVTT_SRC_EQUALS, mimeType); } if (forced) { // See: https://github.com/whatwg/html/issues/4472 kind = 'forced'; } const trackElement = /** @type {!HTMLTrackElement} */(document.createElement('track')); trackElement.src = uri; trackElement.label = label || ''; trackElement.kind = kind; trackElement.srclang = language; // Because we're pulling in the text track file via Javascript, the // same-origin policy applies. If you'd like to have a player served // from one domain, but the text track served from another, you'll // need to enable CORS in order to do so. In addition to enabling CORS // on the server serving the text tracks, you will need to add the // crossorigin attribute to the video element itself. if (!this.video_.getAttribute('crossorigin')) { this.video_.setAttribute('crossorigin', 'anonymous'); } this.video_.appendChild(trackElement); const textTracks = this.getTextTracks(); const srcTrack = textTracks.find((t) => { return t.language == language && t.label == (label || '') && t.kind == kind; }); if (srcTrack) { this.onTracksChanged_(); return srcTrack; } // This should not happen, but there are browser implementations that may // not support the Track element. shaka.log.error('Cannot add this text when loaded with src='); throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS); } const ContentType = shaka.util.ManifestParserUtils.ContentType; const duration = this.manifest_.presentationTimeline.getDuration(); if (duration == Infinity) { throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM); } /** @type {shaka.extern.Stream} */ const stream = { id: this.nextExternalStreamId_++, originalId: null, createSegmentIndex: () => Promise.resolve(), segmentIndex: shaka.media.SegmentIndex.forSingleSegment( /* startTime= */ 0, /* duration= */ duration, /* uris= */ [uri]), mimeType: mimeType || '', codecs: codec || '', kind: kind, encrypted: false, drmInfos: [], keyIds: new Set(), language: language, label: label || null, type: ContentType.TEXT, primary: false, trickModeVideo: null, emsgSchemeIdUris: null, roles: [], forced: !!forced, channelsCount: null, audioSamplingRate: null, spatialAudio: false, closedCaptions: null, }; const fullMimeType = shaka.util.MimeUtils.getFullType( stream.mimeType, stream.codecs); const supported = shaka.text.TextEngine.isTypeSupported(fullMimeType); if (!supported) { throw new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.MISSING_TEXT_PLUGIN, mimeType); } this.manifest_.textStreams.push(stream); this.onTracksChanged_(); return shaka.util.StreamUtils.textStreamToTrack(stream); } /** * Adds the given text track to the loaded manifest. <code>load()</code> must * resolve before calling. The presentation must have a duration. * * This returns the created track, which can immediately be selected by the * application. The track will not be automatically selected. * * @param {string} uri * @param {string} language * @param {string} kind * @param {string=} mimeType * @param {string=} codec * @param {string=} label * @param {boolean=} forced * @return {!Promise.<shaka.extern.Track>} * @export */ async addTextTrackAsync(uri, language, kind, mimeType, codec, label, forced = false) { if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE && this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) { shaka.log.error( 'Must call load() and wait for it to resolve before adding text ' + 'tracks.'); throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.PLAYER, shaka.util.Error.Code.CONTENT_NOT_LOADED); } if (!mimeType) { mimeType = await this.getTextMimetype_(uri); } if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) { if (forced) { // See: https://github.com/whatwg/html/issues/4472 kind = 'forced'; } await this.addSrcTrackElement_(uri, language, kind, mimeType, label); const textTracks = this.getTextTracks(); const srcTrack = textTracks.find((t) => { return t.language == language && t.label == (label || '') && t.kind == kind; }); if (srcTrack) { this.onTracksChanged_(); return srcTrack; } // This should not happen, but there are browser implementations that may // not support the Track element. shaka.log.error('Cannot add this text when loaded with src='); throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS); } const ContentType = shaka.util.ManifestParserUtils.ContentType; const duration = this.manifest_.presentationTimeline.getDuration(); if (duration == Infinity) { throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM); } /** @type {shaka.extern.Stream} */ const stream = { id: this.nextExternalStreamId_++, originalId: null, createSegmentIndex: () => Promise.resolve(), segmentIndex: shaka.media.SegmentIndex.forSingleSegment( /* startTime= */ 0, /* duration= */ duration, /* uris= */ [uri]), mimeType: mimeType || '', codecs: codec || '', kind: kind, encrypted: false, drmInfos: [], keyIds: new Set(), language: language, label: label || null, type: ContentType.TEXT, primary: false, trickModeVideo: null, emsgSchemeIdUris: null, roles: [], forced: !!forced, channelsCount: null, audioSamplingRate: null, spatialAudio: false, closedCaptions: null, }; const fullMimeType = shaka.util.MimeUtils.getFullType( stream.mimeType, stream.codecs); const supported = shaka.text.TextEngine.isTypeSupported(fullMimeType); if (!supported) { throw new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.MISSING_TEXT_PLUGIN, mimeType); } this.manifest_.textStreams.push(stream); this.onTracksChanged_(); return shaka.util.StreamUtils.textStreamToTrack(stream); } /** * Adds the given chapters track to the loaded manifest. <code>load()</code> * must resolve before calling. The presentation must have a duration. * * This returns the created track. * * @param {string} uri * @param {string} language * @param {string=} mimeType * @return {!Promise.<shaka.extern.Track>} * @export */ async addChaptersTrack(uri, language, mimeType) { if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE && this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) { shaka.log.error( 'Must call load() and wait for it to resolve before adding ' + 'chapters tracks.'); throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.PLAYER, shaka.util.Error.Code.CONTENT_NOT_LOADED); } if (!mimeType) { mimeType = await this.getTextMimetype_(uri); } await this.addSrcTrackElement_(uri, language, /* kind= */ 'chapters', mimeType); const chaptersTracks = this.getChaptersTracks(); const chaptersTrack = chaptersTracks.find((t) => { return t.language == language; }); if (chaptersTrack) { const html5ChaptersTracks = this.getChaptersTracks_(); for (const html5ChaptersTrack of html5ChaptersTracks) { this.processChaptersTrack_(html5ChaptersTrack); } return chaptersTrack; } // This should not happen, but there are browser implementations that may // not support the Track element. shaka.log.error('Cannot add this text when loaded with src='); throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS); } /** * @param {string} uri * @return {!Promise.<string>} * @private */ async getTextMimetype_(uri) { // Try using the uri extension. const extension = shaka.media.ManifestParser.getExtension(uri); let mimeType = shaka.Player.TEXT_EXTENSIONS_TO_MIME_TYPES_[extension]; if (mimeType) { return mimeType; } try { goog.asserts.assert( this.networkingEngine_, 'Need networking engine.'); // eslint-disable-next-line require-atomic-updates mimeType = await shaka.media.ManifestParser.getMimeType(uri, this.networkingEngine_, this.config_.streaming.retryParameters); } catch (error) {} if (mimeType) { return mimeType; } shaka.log.error( 'The mimeType has not been provided and it could not be deduced ' + 'from its extension.'); throw new shaka.util.Error( shaka.util.Error.Severity.RECOVERABLE, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.TEXT_COULD_NOT_GUESS_MIME_TYPE, extension); } /** * @param {string} uri * @param {string} language * @param {string} kind * @param {string} mimeType * @param {string=} label * @private */ async addSrcTrackElement_(uri, language, kind, mimeType, label) { if (mimeType != 'text/vtt') { goog.asserts.assert( this.networkingEngine_, 'Need networking engine.'); const data = await this.getTextData_(uri, this.networkingEngine_, this.config_.streaming.retryParameters); const vvtText = this.convertToWebVTT_(data, mimeType); const blob = new Blob([vvtText], {type: 'text/vtt'}); uri = shaka.media.MediaSourceEngine.createObjectURL(blob); mimeType = 'text/vtt'; } const trackElement = /** @type {!HTMLTrackElement} */(document.createElement('track')); trackElement.src = uri; trackElement.label = label || ''; trackElement.kind = kind; trackElement.srclang = language; // Because we're pulling in the text track file via Javascript, the // same-origin policy applies. If you'd like to have a player served // from one domain, but the text track served from another, you'll // need to enable CORS in order to do so. In addition to enabling CORS // on the server serving the text tracks, you will need to add the // crossorigin attribute to the video element itself. if (!this.video_.getAttribute('crossorigin')) { this.video_.setAttribute('crossorigin', 'anonymous'); } this.video_.appendChild(trackElement); } /** * @param {string} uri * @param {!shaka.net.NetworkingEngine} netEngine * @param {shaka.extern.RetryParameters} retryParams * @return {!Promise.<BufferSource>} * @private */ async getTextData_(uri, netEngine, retryParams) { const type = shaka.net.NetworkingEngine.RequestType.SEGMENT; const request = shaka.net.NetworkingEngine.makeRequest([uri], retryParams); request.method = 'GET'; const response = await netEngine.request(type, request).promise; return response.data; } /** * Converts an input string to a WebVTT format string. * * @param {BufferSource} buffer * @param {string} mimeType * @return {string} * @private */ convertToWebVTT_(buffer, mimeType) { const factory = shaka.text.TextEngine.findParser(mimeType); if (factory) { const obj = factory(); const time = { periodStart: 0, segmentStart: 0, segmentEnd: this.video_.duration, }; const data = shaka.util.BufferUtils.toUint8(buffer); const cues = obj.parseMedia(data, time); return shaka.text.WebVttGenerator.convert(cues); } throw new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.TEXT, shaka.util.Error.Code.MISSING_TEXT_PLUGIN, mimeType); } /** * Set the maximum resolution that the platform's hardware can handle. * This will be called automatically by <code>shaka.cast.CastReceiver</code> * to enforce limitations of the Chromecast hardware. * * @param {number} width * @param {number} height * @export */ setMaxHardwareResolution(width, height) { this.maxHwRes_.width = width; this.maxHwRes_.height = height; } /** * Retry streaming after a streaming failure has occurred. When the player has * not loaded content or is loading content, this will be a no-op and will * return <code>false</code>. * * <p> * If the player has loaded content, and streaming has not seen an error, this * will return <code>false</code>. * * <p> * If the player has loaded content, and streaming seen an error, but the * could not resume streaming, this will return <code>false</code>. * * @return {boolean} * @export */ retryStreaming() { return this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE ? this.streamingEngine_.retry() : false; } /** * Get the manifest that the player has loaded. If the player has not loaded * any content, this will return <code>null</code>. * * NOTE: This structure is NOT covered by semantic versioning compatibility * guarantees. It may change at any time! * * This is marked as deprecated to warn Closure Compiler users at compile-time * to avoid using this method. * * @return {?shaka.extern.Manifest} * @export * @deprecated */ getManifest() { shaka.log.alwaysWarn( 'Shaka Player\'s internal Manifest structure is NOT covered by ' + 'semantic versioning compatibility guarantees. It may change at any ' + 'time! Please consider filing a feature request for whatever you ' + 'use getManifest() for.'); return this.manifest_; } /** * Get the type of manifest parser that the player is using. If the player has * not loaded any content, this will return <code>null</code>. * * @return {?shaka.extern.ManifestParser.Factory} * @export */ getManifestParserFactory() { return this.parserFactory_; } /** * @param {shaka.extern.Variant} variant * @param {boolean} fromAdaptation * @private */ addVariantToSwitchHistory_(variant, fromAdaptation) { const switchHistory = this.stats_.getSwitchHistory(); switchHistory.updateCurrentVariant(variant, fromAdaptation); } /** * @param {shaka.extern.Stream} textStream * @param {boolean} fromAdaptation * @private */ addTextStreamToSwitchHistory_(textStream, fromAdaptation) { const switchHistory = this.stats_.getSwitchHistory(); switchHistory.updateCurrentText(textStream, fromAdaptation); } /** * @return {shaka.extern.PlayerConfiguration} * @private */ defaultConfig_() { const config = shaka.util.PlayerConfiguration.createDefault(); config.streaming.failureCallback = (error) => { this.defaultStreamingFailureCallback_(error); }; // Because this.video_ may not be set when the config is built, the default // TextDisplay factory must capture a reference to "this". config.textDisplayFactory = () => { if (this.videoContainer_) { return new shaka.text.UITextDisplayer( this.video_, this.videoContainer_); } else { return new shaka.text.SimpleTextDisplayer(this.video_); } }; return config; } /** * Set the videoContainer to construct UITextDisplayer. * @param {HTMLElement} videoContainer * @export */ setVideoContainer(videoContainer) { this.videoContainer_ = videoContainer; } /** * @param {!shaka.util.Error} error * @private */ defaultStreamingFailureCallback_(error) { const retryErrorCodes = [ shaka.util.Error.Code.BAD_HTTP_STATUS, shaka.util.Error.Code.HTTP_ERROR, shaka.util.Error.Code.TIMEOUT, ]; if (this.isLive() && retryErrorCodes.includes(error.code)) { error.severity = shaka.util.Error.Severity.RECOVERABLE; shaka.log.warning('Live streaming error. Retrying automatically...'); this.retryStreaming(); } } /** * For CEA closed captions embedded in the video streams, create dummy text * stream. This can be safely called again on existing manifests, for * manifest updates. * @param {!shaka.extern.Manifest} manifest * @private */ makeTextStreamsForClosedCaptions_(manifest) { const ContentType = shaka.util.ManifestParserUtils.ContentType; const TextStreamKind = shaka.util.ManifestParserUtils.TextStreamKind; const CEA608_MIME = shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE; const CEA708_MIME = shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE; // A set, to make sure we don't create two text streams for the same video. const closedCaptionsSet = new Set(); for (const textStream of manifest.textStreams) { if (textStream.mimeType == CEA608_MIME || textStream.mimeType == CEA708_MIME) { // This function might be called on a manifest update, so don't make a // new text stream for closed caption streams we have seen before. closedCaptionsSet.add(textStream.originalId); } } for (const variant of manifest.variants) { const video = variant.video; if (video && video.closedCaptions) { for (const id of video.closedCaptions.keys()) { if (!closedCaptionsSet.has(id)) { const mimeType = id.startsWith('CC') ? CEA608_MIME : CEA708_MIME; // Add an empty segmentIndex, for the benefit of the period combiner // in our builtin DASH parser. const segmentIndex = new shaka.media.MetaSegmentIndex(); const textStream = { id: this.nextExternalStreamId_++, // A globally unique ID. originalId: id, // The CC ID string, like 'CC1', 'CC3', etc. createSegmentIndex: () => Promise.resolve(), segmentIndex, mimeType, codecs: '', kind: TextStreamKind.CLOSED_CAPTION, encrypted: false, drmInfos: [], keyIds: new Set(), language: video.closedCaptions.get(id), label: null, type: ContentType.TEXT, primary: false, trickModeVideo: null, emsgSchemeIdUris: null, roles: video.roles, forced: false, channelsCount: null, audioSamplingRate: null, spatialAudio: false, closedCaptions: null, }; manifest.textStreams.push(textStream); closedCaptionsSet.add(id); } } } } } /** * Filters a manifest, removing unplayable streams/variants. * * @param {?shaka.extern.Manifest} manifest * @private */ async filterManifest_(manifest) { await this.filterManifestWithStreamUtils_(manifest); this.filterManifestWithRestrictions_(manifest); } /** * Filters a manifest, removing unplayable streams/variants. * * @param {?shaka.extern.Manifest} manifest * @private */ async filterManifestWithStreamUtils_(manifest) { goog.asserts.assert(manifest, 'Manifest should exist!'); goog.asserts.assert(this.video_, 'Must not be destroyed'); /** @type {?shaka.extern.Variant} */ const currentVariant = this.streamingEngine_ ? this.streamingEngine_.getCurrentVariant() : null; await shaka.util.StreamUtils.filterManifest( this.drmEngine_, currentVariant, manifest); this.checkPlayableVariants_(manifest); } /** * Apply the restrictions configuration to the manifest, and check if there's * a variant that meets the restrictions. * * @param {?shaka.extern.Manifest} manifest * @private */ filterManifestWithRestrictions_(manifest) { // Return if |destroy| is called. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) { return; } const tracksChanged = shaka.util.StreamUtils.applyRestrictions( manifest.variants, this.config_.restrictions, this.maxHwRes_); if (tracksChanged && this.streamingEngine_) { this.onTracksChanged_(); } // We may need to create new sessions for any new init data. const curDrmInfo = this.drmEngine_ ? this.drmEngine_.getDrmInfo() : null; // DrmEngine.newInitData() requires mediaKeys to be available. if (curDrmInfo && this.drmEngine_.getMediaKeys()) { for (const variant of manifest.variants) { const videoDrmInfos = variant.video ? variant.video.drmInfos : []; const audioDrmInfos = variant.audio ? variant.audio.drmInfos : []; const drmInfos = videoDrmInfos.concat(audioDrmInfos); for (const drmInfo of drmInfos) { // Ignore any data for different key systems. if (drmInfo.keySystem == curDrmInfo.keySystem) { for (const initData of (drmInfo.initData || [])) { this.drmEngine_.newInitData( initData.initDataType, initData.initData); } } } } } this.checkRestrictedVariants_(manifest); } /** * @private */ filterManifestByCurrentVariant_() { goog.asserts.assert(this.manifest_, 'Manifest should be valid'); goog.asserts.assert(this.streamingEngine_, 'StreamingEngine should be valid'); const currentVariant = this.streamingEngine_ ? this.streamingEngine_.getCurrentVariant() : null; shaka.util.StreamUtils.filterManifestByCurrentVariant(currentVariant, this.manifest_); this.checkPlayableVariants_(this.manifest_); } /** * @param {shaka.extern.Variant} initialVariant * @param {number} time * @return {!Promise.<number>} * @private */ async adjustStartTime_(initialVariant, time) { /** @type {?shaka.extern.Stream} */ const activeAudio = initialVariant.audio; /** @type {?shaka.extern.Stream} */ const activeVideo = initialVariant.video; /** * @param {?shaka.extern.Stream} stream * @param {number} time * @return {!Promise.<?number>} */ const getAdjustedTime = async (stream, time) => { if (!stream) { return null; } await stream.createSegmentIndex(); const ref = stream.segmentIndex[Symbol.iterator]().seek(time); if (!ref) { return null; } const refTime = ref.startTime; goog.asserts.assert(refTime <= time, 'Segment should start before target time!'); return refTime; }; const audioStartTime = await getAdjustedTime(activeAudio, time); const videoStartTime = await getAdjustedTime(activeVideo, time); // If we have both video and audio times, pick the larger one. If we picked // the smaller one, that one will download an entire segment to buffer the // difference. if (videoStartTime != null && audioStartTime != null) { return Math.max(videoStartTime, audioStartTime); } else if (videoStartTime != null) { return videoStartTime; } else if (audioStartTime != null) { return audioStartTime; } else { return time; } } /** * Update the buffering state to be either "we are buffering" or "we are not * buffering", firing events to the app as needed. * * @private */ updateBufferState_() { const isBuffering = this.isBuffering(); shaka.log.v2('Player changing buffering state to', isBuffering); // Make sure we have all the components we need before we consider ourselves // as being loaded. // TODO: Make the check for "loaded" simpler. const loaded = this.stats_ && this.bufferObserver_ && this.playhead_; if (loaded) { this.playRateController_.setBuffering(isBuffering); this.updateStateHistory_(); } // Surface the buffering event so that the app knows if/when we are // buffering. const eventName = shaka.Player.EventName.Buffering; this.dispatchEvent(this.makeEvent_(eventName, {'buffering': isBuffering})); } /** * A callback for when the playback rate changes. We need to watch the * playback rate so that if the playback rate on the media element changes * (that was not caused by our play rate controller) we can notify the * controller so that it can stay in-sync with the change. * * @private */ onRateChange_() { /** @type {number} */ const newRate = this.video_.playbackRate; // On Edge, when someone seeks using the native controls, it will set the // playback rate to zero until they finish seeking, after which it will // return the playback rate. // // If the playback rate changes while seeking, Edge will cache the playback // rate and use it after seeking. // // https://github.com/google/shaka-player/issues/951 if (newRate == 0) { return; } if (this.playRateController_) { // The playback rate has changed. This could be us or someone else. // If this was us, setting the rate again will be a no-op. this.playRateController_.set(newRate); } const event = this.makeEvent_(shaka.Player.EventName.RateChange); this.dispatchEvent(event); } /** * Try updating the state history. If the player has not finished * initializing, this will be a no-op. * * @private */ updateStateHistory_() { // If we have not finish initializing, this will be a no-op. if (!this.stats_) { return; } if (!this.bufferObserver_) { return; } const State = shaka.media.BufferingObserver.State; const history = this.stats_.getStateHistory(); if (this.bufferObserver_.getState() == State.STARVING) { history.update('buffering'); } else if (this.video_.paused) { history.update('paused'); } else if (this.video_.ended) { history.update('ended'); } else { history.update('playing'); } } /** * Callback from Playhead. * * @private */ onSeek_() { if (this.playheadObservers_) { this.playheadObservers_.notifyOfSeek(); } if (this.streamingEngine_) { this.streamingEngine_.seeked(); } if (this.bufferObserver_) { // If we seek into an unbuffered range, we should fire a 'buffering' event // immediately. If StreamingEngine can buffer fast enough, we may not // update our buffering tracking otherwise. this.pollBufferState_(); } } /** * Update AbrManager with variants while taking into account restrictions, * preferences, and ABR. * * On error, this dispatches an error event and returns false. * * @return {boolean} True if successful. * @private */ updateAbrManagerVariants_() { try { goog.asserts.assert(this.manifest_, 'Manifest should exist by now!'); this.checkRestrictedVariants_(this.manifest_); } catch (e) { this.onError_(e); return false; } const playableVariants = this.manifest_.variants.filter((variant) => { return shaka.util.StreamUtils.isPlayable(variant); }); // Update the abr manager with newly filtered variants. const adaptationSet = this.currentAdaptationSetCriteria_.create( playableVariants); this.abrManager_.setVariants(Array.from(adaptationSet.values())); return true; } /** * Chooses a variant from all possible variants while taking into account * restrictions, preferences, and ABR. * * On error, this dispatches an error event and returns null. * * @return {?shaka.extern.Variant} * @private */ chooseVariant_() { if (this.updateAbrManagerVariants_()) { return this.abrManager_.chooseVariant(); } else { return null; } } /** * Choose a text stream from all possible text streams while taking into * account user preference. * * @return {?shaka.extern.Stream} * @private */ chooseTextStream_() { const subset = shaka.util.StreamUtils.filterStreamsByLanguageAndRole( this.manifest_.textStreams, this.currentTextLanguage_, this.currentTextRole_, this.currentTextForced_); return subset[0] || null; } /** * Chooses a new Variant. If the new variant differs from the old one, it * adds the new one to the switch history and switches to it. * * Called after a config change, a key status event, or an explicit language * change. * * @private */ chooseVariantAndSwitch_() { goog.asserts.assert(this.config_, 'Must not be destroyed'); // Because we're running this after a config change (manual language // change) or a key status event, it is always okay to clear the buffer // here. const chosenVariant = this.chooseVariant_(); if (chosenVariant) { this.switchVariant_(chosenVariant, /* fromAdaptation= */ true, /* clearBuffers= */ true, /* safeMargin= */ 0); } } /** * @param {shaka.extern.Variant} variant * @param {boolean} fromAdaptation * @param {boolean} clearBuffer * @param {number} safeMargin * @private */ switchVariant_(variant, fromAdaptation, clearBuffer, safeMargin) { const currentVariant = this.streamingEngine_.getCurrentVariant(); if (variant == currentVariant) { shaka.log.debug('Variant already selected.'); // If you want to clear the buffer, we force to reselect the same variant if (clearBuffer) { this.streamingEngine_.switchVariant(variant, clearBuffer, safeMargin, /* force= */ true); } return; } // Add entries to the history. this.addVariantToSwitchHistory_(variant, fromAdaptation); this.streamingEngine_.switchVariant(variant, clearBuffer, safeMargin); let oldTrack = null; if (currentVariant) { oldTrack = shaka.util.StreamUtils.variantToTrack(currentVariant); } const newTrack = shaka.util.StreamUtils.variantToTrack(variant); if (fromAdaptation) { // Dispatch an 'adaptation' event this.onAdaptation_(oldTrack, newTrack); } else { // Dispatch a 'variantchanged' event this.onVariantChanged_(oldTrack, newTrack); } } /** * @param {AudioTrack} track * @private */ switchHtml5Track_(track) { goog.asserts.assert(this.video_ && this.video_.audioTracks, 'Video and video.audioTracks should not be null!'); const audioTracks = Array.from(this.video_.audioTracks); const currentTrack = audioTracks.find((t) => t.enabled); // This will reset the "enabled" of other tracks to false. track.enabled = true; // AirPlay does not reset the "enabled" of other tracks to false, so // it must be changed by hand. if (track.id !== currentTrack.id) { currentTrack.enabled = false; } const oldTrack = shaka.util.StreamUtils.html5AudioTrackToTrack(currentTrack); const newTrack = shaka.util.StreamUtils.html5AudioTrackToTrack(track); this.onVariantChanged_(oldTrack, newTrack); } /** * Decide during startup if text should be streamed/shown. * @private */ setInitialTextState_(initialVariant, initialTextStream) { // Check if we should show text (based on difference between audio and text // languages). if (initialTextStream) { if (initialVariant.audio && this.shouldInitiallyShowText_( initialVariant.audio, initialTextStream)) { this.isTextVisible_ = true; } if (this.isTextVisible_) { // If the cached value says to show text, then update the text displayer // since it defaults to not shown. this.mediaSourceEngine_.getTextDisplayer().setTextVisibility(true); goog.asserts.assert(this.shouldStreamText_(), 'Should be streaming text'); } this.onTextTrackVisibility_(); } else { this.isTextVisible_ = false; } } /** * Check if we should show text on screen automatically. * * The text should automatically be shown if the text is language-compatible * with the user's text language preference, but not compatible with the * audio. * * For example: * preferred | chosen | chosen | * text | text | audio | show * ----------------------------------- * en-CA | en | jp | true * en | en-US | fr | true * fr-CA | en-US | jp | false * en-CA | en-US | en-US | false * * @param {shaka.extern.Stream} audioStream * @param {shaka.extern.Stream} textStream * @return {boolean} * @private */ shouldInitiallyShowText_(audioStream, textStream) { const LanguageUtils = shaka.util.LanguageUtils; /** @type {string} */ const preferredTextLocale = LanguageUtils.normalize(this.config_.preferredTextLanguage); /** @type {string} */ const audioLocale = LanguageUtils.normalize(audioStream.language); /** @type {string} */ const textLocale = LanguageUtils.normalize(textStream.language); return ( LanguageUtils.areLanguageCompatible(textLocale, preferredTextLocale) && !LanguageUtils.areLanguageCompatible(audioLocale, textLocale)); } /** * Callback from StreamingEngine. * * @private */ onManifestUpdate_() { if (this.parser_ && this.parser_.update) { this.parser_.update(); } } /** * Callback from StreamingEngine. * * @private */ onSegmentAppended_() { // When we append a segment to media source (via streaming engine) we are // changing what data we have buffered, so notify the playhead of the // change. if (this.playhead_) { this.playhead_.notifyOfBufferingChange(); } this.pollBufferState_(); } /** * Callback from AbrManager. * * @param {shaka.extern.Variant} variant * @param {boolean=} clearBuffer * @param {number=} safeMargin Optional amount of buffer (in seconds) to * retain when clearing the buffer. * Defaults to 0 if not provided. Ignored if clearBuffer is false. * @private */ switch_(variant, clearBuffer = false, safeMargin = 0) { shaka.log.debug('switch_'); goog.asserts.assert(this.config_.abr.enabled, 'AbrManager should not call switch while disabled!'); goog.asserts.assert(this.manifest_, 'We need a manifest to switch ' + 'variants.'); if (!this.streamingEngine_) { // There's no way to change it. return; } if (variant == this.streamingEngine_.getCurrentVariant()) { // This isn't a change. return; } this.switchVariant_(variant, /* fromAdaptation= */ true, clearBuffer, safeMargin); } /** * Dispatches an 'adaptation' event. * @param {?shaka.extern.Track} from * @param {shaka.extern.Track} to * @private */ onAdaptation_(from, to) { // Delay the 'adaptation' event so that StreamingEngine has time to absorb // the changes before the user tries to query it. const event = this.makeEvent_(shaka.Player.EventName.Adaptation, { oldTrack: from, newTrack: to, }); this.delayDispatchEvent_(event); } /** * Dispatches a 'trackschanged' event. * @private */ onTracksChanged_() { // Delay the 'trackschanged' event so StreamingEngine has time to absorb the // changes before the user tries to query it. const event = this.makeEvent_(shaka.Player.EventName.TracksChanged); this.delayDispatchEvent_(event); } /** * Dispatches a 'variantchanged' event. * @param {?shaka.extern.Track} from * @param {shaka.extern.Track} to * @private */ onVariantChanged_(from, to) { // Delay the 'variantchanged' event so StreamingEngine has time to absorb // the changes before the user tries to query it. const event = this.makeEvent_(shaka.Player.EventName.VariantChanged, { oldTrack: from, newTrack: to, }); this.delayDispatchEvent_(event); } /** * Dispatches a 'textchanged' event. * @private */ onTextChanged_() { // Delay the 'textchanged' event so StreamingEngine time to absorb the // changes before the user tries to query it. const event = this.makeEvent_(shaka.Player.EventName.TextChanged); this.delayDispatchEvent_(event); } /** @private */ onTextTrackVisibility_() { const event = this.makeEvent_(shaka.Player.EventName.TextTrackVisibility); this.delayDispatchEvent_(event); } /** @private */ onAbrStatusChanged_() { const event = this.makeEvent_(shaka.Player.EventName.AbrStatusChanged, { newStatus: this.config_.abr.enabled, }); this.delayDispatchEvent_(event); } /** * @param {!shaka.util.Error} error * @private */ onError_(error) { goog.asserts.assert(error instanceof shaka.util.Error, 'Wrong error type!'); // Errors dispatched after |destroy| is called are not meaningful and should // be safe to ignore. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) { return; } const eventName = shaka.Player.EventName.Error; const event = this.makeEvent_(eventName, {'detail': error}); this.dispatchEvent(event); if (event.defaultPrevented) { error.handled = true; } } /** * When we fire region events, we need to copy the information out of the * region to break the connection with the player's internal data. We do the * copy here because this is the transition point between the player and the * app. * * @param {!shaka.Player.EventName} eventName * @param {shaka.extern.TimelineRegionInfo} region * * @private */ onRegionEvent_(eventName, region) { // Always make a copy to avoid exposing our internal data to the app. const clone = { schemeIdUri: region.schemeIdUri, value: region.value, startTime: region.startTime, endTime: region.endTime, id: region.id, eventElement: region.eventElement, }; this.dispatchEvent(this.makeEvent_(eventName, {detail: clone})); } /** * Turn the media element's error object into a Shaka Player error object. * * @return {shaka.util.Error} * @private */ videoErrorToShakaError_() { goog.asserts.assert(this.video_.error, 'Video error expected, but missing!'); if (!this.video_.error) { return null; } const code = this.video_.error.code; if (code == 1 /* MEDIA_ERR_ABORTED */) { // Ignore this error code, which should only occur when navigating away or // deliberately stopping playback of HTTP content. return null; } // Extra error information from MS Edge: let extended = this.video_.error.msExtendedCode; if (extended) { // Convert to unsigned: if (extended < 0) { extended += Math.pow(2, 32); } // Format as hex: extended = extended.toString(16); } // Extra error information from Chrome: const message = this.video_.error.message; return new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MEDIA, shaka.util.Error.Code.VIDEO_ERROR, code, extended, message); } /** * @param {!Event} event * @private */ onVideoError_(event) { const error = this.videoErrorToShakaError_(); if (!error) { return; } this.onError_(error); } /** * @param {!Object.<string, string>} keyStatusMap A map of hex key IDs to * statuses. * @private */ onKeyStatus_(keyStatusMap) { if (!this.streamingEngine_) { // We can't use this info to manage restrictions in src= mode, so ignore // it. return; } const keyIds = Object.keys(keyStatusMap); if (keyIds.length == 0) { shaka.log.warning( 'Got a key status event without any key statuses, so we don\'t ' + 'know the real key statuses. If we don\'t have all the keys, ' + 'you\'ll need to set restrictions so we don\'t select those tracks.'); } // If EME is using a synthetic key ID, the only key ID is '00' (a single 0 // byte). In this case, it is only used to report global success/failure. // See note about old platforms in: https://bit.ly/2tpez5Z const isGlobalStatus = keyIds.length == 1 && keyIds[0] == '00'; if (isGlobalStatus) { shaka.log.warning( 'Got a synthetic key status event, so we don\'t know the real key ' + 'statuses. If we don\'t have all the keys, you\'ll need to set ' + 'restrictions so we don\'t select those tracks.'); } const restrictedStatuses = shaka.Player.restrictedStatuses_; let tracksChanged = false; // Only filter tracks for keys if we have some key statuses to look at. if (keyIds.length) { for (const variant of this.manifest_.variants) { const streams = shaka.util.StreamUtils.getVariantStreams(variant); for (const stream of streams) { const originalAllowed = variant.allowedByKeySystem; // Only update if we have key IDs for the stream. If the keys aren't // all present, then the track should be restricted. if (stream.keyIds.size) { variant.allowedByKeySystem = true; for (const keyId of stream.keyIds) { const keyStatus = keyStatusMap[isGlobalStatus ? '00' : keyId]; variant.allowedByKeySystem = variant.allowedByKeySystem && !!keyStatus && !restrictedStatuses.includes(keyStatus); } } if (originalAllowed != variant.allowedByKeySystem) { tracksChanged = true; } } // for (const stream of streams) } // for (const variant of this.manifest_.variants) } // if (keyIds.size) if (tracksChanged) { this.updateAbrManagerVariants_(); } const currentVariant = this.streamingEngine_.getCurrentVariant(); if (currentVariant && !currentVariant.allowedByKeySystem) { shaka.log.debug('Choosing new streams after key status changed'); this.chooseVariantAndSwitch_(); } if (tracksChanged) { this.onTracksChanged_(); } } /** * Callback from DrmEngine * @param {string} keyId * @param {number} expiration * @private */ onExpirationUpdated_(keyId, expiration) { if (this.parser_ && this.parser_.onExpirationUpdated) { this.parser_.onExpirationUpdated(keyId, expiration); } const event = this.makeEvent_(shaka.Player.EventName.ExpirationUpdated); this.dispatchEvent(event); } /** * @return {boolean} true if we should stream text right now. * @private */ shouldStreamText_() { return this.config_.streaming.alwaysStreamText || this.isTextTrackVisible(); } /** * Applies playRangeStart and playRangeEnd to the given timeline. This will * only affect non-live content. * * @param {shaka.media.PresentationTimeline} timeline * @param {number} playRangeStart * @param {number} playRangeEnd * * @private */ static applyPlayRange_(timeline, playRangeStart, playRangeEnd) { if (playRangeStart > 0) { if (timeline.isLive()) { shaka.log.warning( '|playRangeStart| has been configured for live content. ' + 'Ignoring the setting.'); } else { timeline.setUserSeekStart(playRangeStart); } } // If the playback has been configured to end before the end of the // presentation, update the duration unless it's live content. const fullDuration = timeline.getDuration(); if (playRangeEnd < fullDuration) { if (timeline.isLive()) { shaka.log.warning( '|playRangeEnd| has been configured for live content. ' + 'Ignoring the setting.'); } else { timeline.setDuration(playRangeEnd); } } } /** * Checks if the variants are all restricted, and throw an appropriate * exception if so. * * @param {shaka.extern.Manifest} manifest * * @private */ checkRestrictedVariants_(manifest) { const restrictedStatuses = shaka.Player.restrictedStatuses_; const keyStatusMap = this.drmEngine_ ? this.drmEngine_.getKeyStatuses() : {}; const keyIds = Object.keys(keyStatusMap); const isGlobalStatus = keyIds.length && keyIds[0] == '00'; let hasPlayable = false; let hasAppRestrictions = false; /** @type {!Set.<string>} */ const missingKeys = new Set(); /** @type {!Set.<string>} */ const badKeyStatuses = new Set(); for (const variant of manifest.variants) { // TODO: Combine with onKeyStatus_. const streams = []; if (variant.audio) { streams.push(variant.audio); } if (variant.video) { streams.push(variant.video); } for (const stream of streams) { if (stream.keyIds.size) { for (const keyId of stream.keyIds) { const keyStatus = keyStatusMap[isGlobalStatus ? '00' : keyId]; if (!keyStatus) { missingKeys.add(keyId); } else if (restrictedStatuses.includes(keyStatus)) { badKeyStatuses.add(keyStatus); } } } // if (stream.keyIds.size) } if (!variant.allowedByApplication) { hasAppRestrictions = true; } else if (variant.allowedByKeySystem) { hasPlayable = true; } } if (!hasPlayable) { /** @type {shaka.extern.RestrictionInfo} */ const data = { hasAppRestrictions, missingKeys: Array.from(missingKeys), restrictedKeyStatuses: Array.from(badKeyStatuses), }; throw new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.RESTRICTIONS_CANNOT_BE_MET, data); } } /** * Confirm some variants are playable. Otherwise, throw an exception. * @param {!shaka.extern.Manifest} manifest * @private */ checkPlayableVariants_(manifest) { const valid = manifest.variants.some(shaka.util.StreamUtils.isPlayable); // If none of the variants are playable, throw // CONTENT_UNSUPPORTED_BY_BROWSER. if (!valid) { throw new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.MANIFEST, shaka.util.Error.Code.CONTENT_UNSUPPORTED_BY_BROWSER); } } /** * Fire an event, but wait a little bit so that the immediate execution can * complete before the event is handled. * * @param {!shaka.util.FakeEvent} event * @private */ async delayDispatchEvent_(event) { // Wait until the next interpreter cycle. await Promise.resolve(); // Only dispatch the event if we are still alive. if (this.loadMode_ != shaka.Player.LoadMode.DESTROYED) { this.dispatchEvent(event); } } /** * Get the normalized languages for a group of tracks. * * @param {!Array.<?shaka.extern.Track>} tracks * @return {!Set.<string>} * @private */ static getLanguagesFrom_(tracks) { const languages = new Set(); for (const track of tracks) { if (track.language) { languages.add(shaka.util.LanguageUtils.normalize(track.language)); } else { languages.add('und'); } } return languages; } /** * Get all permutations of normalized languages and role for a group of * tracks. * * @param {!Array.<?shaka.extern.Track>} tracks * @return {!Array.<shaka.extern.LanguageRole>} * @private */ static getLanguageAndRolesFrom_(tracks) { /** @type {!Map.<string, !Set>} */ const languageToRoles = new Map(); /** @type {!Map.<string, !Map.<string, string>>} */ const languageRoleToLabel = new Map(); for (const track of tracks) { let language = 'und'; let roles = []; if (track.language) { language = shaka.util.LanguageUtils.normalize(track.language); } if (track.type == 'variant') { roles = track.audioRoles; } else { roles = track.roles; } if (!roles || !roles.length) { // We must have an empty role so that we will still get a language-role // entry from our Map. roles = ['']; } if (!languageToRoles.has(language)) { languageToRoles.set(language, new Set()); } for (const role of roles) { languageToRoles.get(language).add(role); if (track.label) { if (!languageRoleToLabel.has(language)) { languageRoleToLabel.set(language, new Map()); } languageRoleToLabel.get(language).set(role, track.label); } } } // Flatten our map to an array of language-role pairs. const pairings = []; languageToRoles.forEach((roles, language) => { for (const role of roles) { let label = null; if (languageRoleToLabel.has(language) && languageRoleToLabel.get(language).has(role)) { label = languageRoleToLabel.get(language).get(role); } pairings.push({language, role, label}); } }); return pairings; } /** * Assuming the player is playing content with media source, check if the * player has buffered enough content to make it to the end of the * presentation. * * @return {boolean} * @private */ isBufferedToEndMS_() { goog.asserts.assert( this.video_, 'We need a video element to get buffering information'); goog.asserts.assert( this.mediaSourceEngine_, 'We need a media source engine to get buffering information'); goog.asserts.assert( this.manifest_, 'We need a manifest to get buffering information'); // This is a strong guarantee that we are buffered to the end, because it // means the playhead is already at that end. if (this.video_.ended) { return true; } // This means that MediaSource has buffered the final segment in all // SourceBuffers and is no longer accepting additional segments. if (this.mediaSourceEngine_.ended()) { return true; } // Live streams are "buffered to the end" when they have buffered to the // live edge or beyond (into the region covered by the presentation delay). if (this.manifest_.presentationTimeline.isLive()) { const liveEdge = this.manifest_.presentationTimeline.getSegmentAvailabilityEnd(); const bufferEnd = shaka.media.TimeRangesUtils.bufferEnd(this.video_.buffered); if (bufferEnd != null && bufferEnd >= liveEdge) { return true; } } return false; } /** * Assuming the player is playing content with src=, check if the player has * buffered enough content to make it to the end of the presentation. * * @return {boolean} * @private */ isBufferedToEndSrc_() { goog.asserts.assert( this.video_, 'We need a video element to get buffering information'); // This is a strong guarantee that we are buffered to the end, because it // means the playhead is already at that end. if (this.video_.ended) { return true; } // If we have buffered to the duration of the content, it means we will have // enough content to buffer to the end of the presentation. const bufferEnd = shaka.media.TimeRangesUtils.bufferEnd(this.video_.buffered); // Because Safari's native HLS reports slightly inaccurate values for // bufferEnd here, we use a fudge factor. Without this, we can end up in a // buffering state at the end of the stream. See issue #2117. // TODO: Try to remove the fudge here once we no longer manage buffering // state above the browser with playbackRate=0. const fudge = 1; // 1000 ms return bufferEnd != null && bufferEnd >= this.video_.duration - fudge; } /** * Create an error for when we purposely interrupt a load operation. * * @return {!shaka.util.Error} * @private */ createAbortLoadError_() { return new shaka.util.Error( shaka.util.Error.Severity.CRITICAL, shaka.util.Error.Category.PLAYER, shaka.util.Error.Code.LOAD_INTERRUPTED); } /** * Key * ---------------------- * D : Detach Node * A : Attach Node * MS : Media Source Node * P : Manifest Parser Node * M : Manifest Node * DRM : Drm Engine Node * L : Load Node * U : Unloading Node * SRC : Src Equals Node * * Graph Topology * ---------------------- * * [SRC]-----+ * ^ | * | v * [D]<-->[A]<-----[U] * | ^ * v | * [MS]------+ * | | * v | * [P]-------+ * | | * v | * [M]-------+ * | | * v | * [DRM]-----+ * | | * v | * [L]-------+ * * @param {!shaka.routing.Node} currentlyAt * @param {shaka.routing.Payload} currentlyWith * @param {!shaka.routing.Node} wantsToBeAt * @param {shaka.routing.Payload} wantsToHave * @return {?shaka.routing.Node} * @private */ getNextStep_(currentlyAt, currentlyWith, wantsToBeAt, wantsToHave) { let next = null; // Detach is very simple, either stay in detach (because |detach| was called // while in detached) or go somewhere that requires us to attach to an // element. if (currentlyAt == this.detachNode_) { next = wantsToBeAt == this.detachNode_ ? this.detachNode_ : this.attachNode_; } if (currentlyAt == this.attachNode_) { next = this.getNextAfterAttach_(wantsToBeAt, currentlyWith, wantsToHave); } if (currentlyAt == this.mediaSourceNode_) { next = this.getNextAfterMediaSource_( wantsToBeAt, currentlyWith, wantsToHave); } if (currentlyAt == this.parserNode_) { next = this.getNextMatchingAllDependencies_( /* destination= */ this.loadNode_, /* next= */ this.manifestNode_, /* reset= */ this.unloadNode_, /* goingTo= */ wantsToBeAt, /* has= */ currentlyWith, /* wants= */ wantsToHave); } if (currentlyAt == this.manifestNode_) { next = this.getNextMatchingAllDependencies_( /* destination= */ this.loadNode_, /* next= */ this.drmNode_, /* reset= */ this.unloadNode_, /* goingTo= */ wantsToBeAt, /* has= */ currentlyWith, /* wants= */ wantsToHave); } // For DRM, we have two options "load" or "unload". If all our constraints // are met, we can go to "load". If anything is off, we must go back to // "unload" to reset. if (currentlyAt == this.drmNode_) { next = this.getNextMatchingAllDependencies_( /* destination= */ this.loadNode_, /* next= */ this.loadNode_, /* reset= */ this.unloadNode_, /* goingTo= */ wantsToBeAt, /* has= */ currentlyWith, /* wants= */ wantsToHave); } // For DRM w/ src= playback, we only care about destination and media // element. if (currentlyAt == this.srcEqualsDrmNode_) { if (wantsToBeAt == this.srcEqualsNode_ && currentlyWith.mediaElement == wantsToHave.mediaElement) { next = this.srcEqualsNode_; } else { next = this.unloadNode_; } } // After we load content, always go through unload because we can't safely // use components after we have started playback. if (currentlyAt == this.loadNode_ || currentlyAt == this.srcEqualsNode_) { next = this.unloadNode_; } if (currentlyAt == this.unloadNode_) { next = this.getNextAfterUnload_(wantsToBeAt, currentlyWith, wantsToHave); } goog.asserts.assert(next, 'Missing next step!'); return next; } /** * @param {!shaka.routing.Node} goingTo * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {?shaka.routing.Node} * @private */ getNextAfterAttach_(goingTo, has, wants) { // Attach and detach are the only two nodes that we can directly go // back-and-forth between. if (goingTo == this.detachNode_) { return this.detachNode_; } // If we are going anywhere other than detach, then we need the media // element to match, if they don't match, we need to go through detach // first. if (has.mediaElement != wants.mediaElement) { return this.detachNode_; } // If we are already in attached, and someone calls |attach| again (to the // same video element), we can handle the redundant request by re-entering // our current state. if (goingTo == this.attachNode_) { return this.attachNode_; } // The next step from attached to loaded is through media source. if (goingTo == this.mediaSourceNode_ || goingTo == this.loadNode_) { return this.mediaSourceNode_; } // If we are going to src=, then we should set up DRM first. This will // support cases like FairPlay HLS on Safari. if (goingTo == this.srcEqualsNode_) { return this.srcEqualsDrmNode_; } // We are missing a rule, the null will get caught by a common check in // the routing system. return null; } /** * @param {!shaka.routing.Node} goingTo * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {?shaka.routing.Node} * @private */ getNextAfterMediaSource_(goingTo, has, wants) { // We can only go to parse manifest or unload. If we want to go to load and // we have the right media element, we can go to parse manifest. If we // don't, no matter where we want to go, we must go through unload. if (goingTo == this.loadNode_ && has.mediaElement == wants.mediaElement) { return this.parserNode_; } // Right now the unload node is responsible for tearing down all playback // components (including media source). So since we have created media // source, we need to unload since our dependencies are not compatible. // // TODO: We are structured this way to maintain a historic structure. Going // forward, there is no reason to restrict ourselves to this. Going // forward we should explore breaking apart |onUnload| and develop // more meaningful terminology around tearing down playback resources. return this.unloadNode_; } /** * After unload there are only two options, attached or detached. This choice * is based on whether or not we have a media element. If we have a media * element, then we go to attach. If we don't have a media element, we go to * detach. * * @param {!shaka.routing.Node} goingTo * @param {shaka.routing.Payload} has * @param {shaka.routing.Payload} wants * @return {?shaka.routing.Node} * @private */ getNextAfterUnload_(goingTo, has, wants) { // If we don't want a media element, detach. // If we have the wrong media element, detach. // Otherwise it means we want to attach to a media element and it is safe to // do so. return !wants.mediaElement || has.mediaElement != wants.mediaElement ? this.detachNode_ : this.attachNode_; } /** * A general method used to handle routing when we can either than one step * toward our destination (while all our dependencies match) or go to a node * that will reset us so we can try again. * * @param {!shaka.routing.Node} destinationNode * What |goingTo| must be for us to step toward |nextNode|. Otherwise we * will go to |resetNode|. * @param {!shaka.routing.Node} nextNode * The node we will go to next if |goingTo == destinationNode| and all * dependencies match. * @param {!shaka.routing.Node} resetNode * The node we will go to next if |goingTo != destinationNode| or any * dependency does not match. * @param {!shaka.routing.Node} goingTo * The node that the walker is trying to go to. * @param {shaka.routing.Payload} has * The payload that the walker currently has. * @param {shaka.routing.Payload} wants * The payload that the walker wants to have when iy gets to |goingTo|. * @return {shaka.routing.Node} * @private */ getNextMatchingAllDependencies_(destinationNode, nextNode, resetNode, goingTo, has, wants) { if (goingTo == destinationNode && has.mediaElement == wants.mediaElement && has.uri == wants.uri && has.mimeType == wants.mimeType) { return nextNode; } return resetNode; } /** * @return {shaka.routing.Payload} * @private */ static createEmptyPayload_() { return { mediaElement: null, mimeType: null, startTime: null, startTimeOfLoad: NaN, uri: null, }; } /** * Using a promise, wrap the listeners returned by |Walker.startNewRoute|. * This will work for most usages in |Player| but should not be used for * special cases. * * This will connect |onCancel|, |onEnd|, |onError|, and |onSkip| with * |resolve| and |reject| but will leave |onStart| unset. * * @param {shaka.routing.Walker.Listeners} listeners * @return {!Promise} * @private */ wrapWalkerListenersWithPromise_(listeners) { return new Promise((resolve, reject) => { listeners.onCancel = () => reject(this.createAbortLoadError_()); listeners.onEnd = () => resolve(); listeners.onError = (e) => reject(e); listeners.onSkip = () => reject(this.createAbortLoadError_()); }); } }; /** * An internal enum that contains the string values of all of the player events. * This exists primarily to act as an implicit list of events, for tests. * * @enum {string} */ shaka.Player.EventName = { AbrStatusChanged: 'abrstatuschanged', Adaptation: 'adaptation', Buffering: 'buffering', DownloadFailed: 'downloadfailed', DownloadHeadersReceived: 'downloadheadersreceived', DrmSessionUpdate: 'drmsessionupdate', Emsg: 'emsg', Error: 'error', ExpirationUpdated: 'expirationupdated', LargeGap: 'largegap', Loaded: 'loaded', Loading: 'loading', ManifestParsed: 'manifestparsed', Metadata: 'metadata', OnStateChange: 'onstatechange', OnStateIdle: 'onstateidle', RateChange: 'ratechange', SessionDataEvent: 'sessiondata', Streaming: 'streaming', TextChanged: 'textchanged', TextTrackVisibility: 'texttrackvisibility', TimelineRegionAdded: 'timelineregionadded', TimelineRegionEnter: 'timelineregionenter', TimelineRegionExit: 'timelineregionexit', TracksChanged: 'trackschanged', Unloading: 'unloading', VariantChanged: 'variantchanged', }; /** * In order to know what method of loading the player used for some content, we * have this enum. It lets us know if content has not been loaded, loaded with * media source, or loaded with src equals. * * This enum has a low resolution, because it is only meant to express the * outer limits of the various states that the player is in. For example, when * someone calls a public method on player, it should not matter if they have * initialized drm engine, it should only matter if they finished loading * content. * * @enum {number} * @export */ shaka.Player.LoadMode = { 'DESTROYED': 0, 'NOT_LOADED': 1, 'MEDIA_SOURCE': 2, 'SRC_EQUALS': 3, }; /** * The typical buffering threshold. When we have less than this buffered (in * seconds), we enter a buffering state. This specific value is based on manual * testing and evaluation across a variety of platforms. * * To make the buffering logic work in all cases, this "typical" threshold will * be overridden if the rebufferingGoal configuration is too low. * * @const {number} * @private */ shaka.Player.TYPICAL_BUFFERING_THRESHOLD_ = 0.5; /** * @define {string} A version number taken from git at compile time. * @export */ shaka.Player.version = 'v3.3.0-pre-uncompiled'; // Initialize the deprecation system using the version string we just set // on the player. shaka.Deprecate.init(shaka.Player.version); /** * These are the EME key statuses that represent restricted playback. * 'usable', 'released', 'output-downscaled', 'status-pending' are statuses * of the usable keys. 'expired' status is being handled separately in * DrmEngine. * * @const {!Array.<string>} * @private */ shaka.Player.restrictedStatuses_ = ['output-restricted', 'internal-error']; /** @private {!Object.<string, function():*>} */ shaka.Player.supportPlugins_ = {}; /** @private {?shaka.extern.IAdManager.Factory} */ shaka.Player.adManagerFactory_ = null; /** * @const {!Object.<string, string>} * @private */ shaka.Player.SRC_EQUAL_EXTENSIONS_TO_MIME_TYPES_ = { 'mp4': 'video/mp4', 'm4v': 'video/mp4', 'm4a': 'audio/mp4', 'webm': 'video/webm', 'weba': 'audio/webm', 'mkv': 'video/webm', // Chromium browsers supports it. 'ts': 'video/mp2t', 'ogv': 'video/ogg', 'ogg': 'audio/ogg', 'mpg': 'video/mpeg', 'mpeg': 'video/mpeg', 'm3u8': 'application/x-mpegurl', 'mp3': 'audio/mpeg', 'aac': 'audio/aac', 'flac': 'audio/flac', 'wav': 'audio/wav', }; /** * @const {!Object.<string, string>} * @private */ shaka.Player.TEXT_EXTENSIONS_TO_MIME_TYPES_ = { 'sbv': 'text/x-subviewer', 'srt': 'text/srt', 'vtt': 'text/vtt', 'webvtt': 'text/vtt', 'ttml': 'application/ttml+xml', 'lrc': 'application/x-subtitle-lrc', 'ssa': 'text/x-ssa', 'ass': 'text/x-ssa', }; /** * @const {string} */ shaka.Player.TextTrackLabel = 'Shaka Player TextTrack';
import Head from 'next/head'; import PropTypes from 'prop-types'; export default function Home({ title, description, bg }) { return ( <Head> <title>{title}</title> <meta charSet="utf-8" /> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> <meta property="og:locale" content="pt_BR" /> <meta property="og:title" content={title} /> <meta property="og:site_name" content="VisaQuiz" /> <meta property="og:description" content={description} /> <meta property="og:image" content={bg} /> <meta property="og:image:type" content="image/jpg" /> <meta property="og:image:width" content="1920" /> <meta property="og:image:height" content="1080" /> <meta property="og:type" content="website" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&display=swap" rel="stylesheet" /> </Head> ); } Home.propTypes = { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, bg: PropTypes.string.isRequired, };
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; module('Unit | Route | pipeline/secrets', function(hooks) { setupTest(hooks); test('it exists', function(assert) { let route = this.owner.lookup('route:pipeline/secrets'); assert.ok(route); assert.equal(route.titleToken, 'Secrets'); }); });
'use strict'; const fs = require('fs'); const delay = require('delay'); const aperture = require('.'); async function main() { const recorder = aperture(); console.log('Screens:', await aperture.screens()); console.log('Audio devices:', await aperture.audioDevices()); console.log('Video codecs:', aperture.videoCodecs); console.log('Preparing to record for 5 seconds'); await recorder.startRecording(); console.log('Recording started'); await recorder.isFileReady; console.log('File is ready'); await delay(5000); const fp = await recorder.stopRecording(); fs.renameSync(fp, 'recording.mp4'); console.log('Video saved in the current directory'); } main().catch(console.error); // Run: $ node example.js
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, './coverage/ballotics'), reports: ['html', 'lcovonly', 'text-summary'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true }); };
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __reExport = (target, module2, desc) => { if (module2 && typeof module2 === "object" || typeof module2 === "function") { for (let key of __getOwnPropNames(module2)) if (!__hasOwnProp.call(target, key) && key !== "default") __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable }); } return target; }; var __toModule = (module2) => { return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2); }; __markAsModule(exports); __export(exports, { PinRemovedIcon: () => PinRemovedIcon }); var import_react = __toModule(require("react")); const PinRemovedIcon = (0, import_react.forwardRef)(function PinRemovedIcon2(props, ref) { return /* @__PURE__ */ import_react.default.createElement("svg", __spreadValues({ "data-sanity-icon": "pin-removed", width: "1em", height: "1em", viewBox: "0 0 25 25", fill: "none", xmlns: "http://www.w3.org/2000/svg", ref }, props), /* @__PURE__ */ import_react.default.createElement("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M12.5 21.3485L12.0757 20.9243C10.5685 19.417 9.03448 17.7584 7.87577 16.0203C7.45976 15.3963 7.08725 14.7549 6.78084 14.1H8.12154C8.34249 14.5172 8.59486 14.9356 8.87423 15.3547C9.86189 16.8362 11.1564 18.2803 12.5 19.6478C13.8436 18.2803 15.1381 16.8362 16.1258 15.3547C16.4051 14.9356 16.6575 14.5172 16.8785 14.1H18.2192C17.9127 14.7549 17.5402 15.3963 17.1242 16.0203C15.9655 17.7584 14.4315 19.417 12.9243 20.9243L12.5 21.3485ZM18.9594 11.9C19.0508 11.4372 19.1 10.9701 19.1 10.5C19.1 6.66863 16.3314 3.9 12.5 3.9C8.66863 3.9 5.9 6.66863 5.9 10.5C5.9 10.9701 5.94923 11.4372 6.04056 11.9H7.26799C7.15822 11.4297 7.1 10.9627 7.1 10.5C7.1 7.33137 9.33137 5.1 12.5 5.1C15.6686 5.1 17.9 7.33137 17.9 10.5C17.9 10.9627 17.8418 11.4297 17.732 11.9H18.9594ZM14.0653 11.9C14.3978 11.5285 14.6 11.0378 14.6 10.5C14.6 9.3402 13.6598 8.4 12.5 8.4C11.3402 8.4 10.4 9.3402 10.4 10.5C10.4 11.0378 10.6022 11.5285 10.9347 11.9H14.0653ZM12.5 9.6C12.0029 9.6 11.6 10.0029 11.6 10.5C11.6 10.9971 12.0029 11.4 12.5 11.4C12.9971 11.4 13.4 10.9971 13.4 10.5C13.4 10.0029 12.9971 9.6 12.5 9.6Z", fill: "currentColor" }), /* @__PURE__ */ import_react.default.createElement("path", { d: "M2 13H23", stroke: "currentColor", strokeWidth: 1.2 })); });
var base_url = window.location.toString(); var tabUrl = base_url.split("public"); function cacherToutMotif(){ $(function(){ $('#motif1').toggle(false); $('#motif2').toggle(false); $('#motif3').toggle(false); $('#motif4').toggle(false); $('#motif5').toggle(false); }); } var nbChampMotif; function afficherMotif(nbmotif_admission) { $(function(){ for(var i = 1; i<=nbmotif_admission ; i++){ $('#motif'+i).toggle(true); } }); nbChampMotif = nbmotif_admission; if(nbChampMotif == 1){ $('#supprimer_motif_img').toggle(false); } if(nbChampMotif == 5){ $('#ajouter_motif_img').toggle(false); } if(nbChampMotif == 1){ $(".supprimerMotif1" ).replaceWith( "<img class='supprimerMotif' src='"+tabUrl[0]+"public/images/images/sup2.png' />" ); } ajouterMotif(); supprimerMotif(); supprimerLeMotif1(); } function ajouterMotif(){ $('#ajouter_motif_img').click(function(){ nbChampMotif++; $('#motif'+(nbChampMotif)).toggle(true); if(nbChampMotif == 5){ $('#ajouter_motif_img').toggle(false); } if(nbChampMotif == 2){ $('#supprimer_motif_img').toggle(true); $(".supprimerMotif" ).replaceWith( "<img class='supprimerMotif1' style='cursor: pointer;' src='"+tabUrl[0]+"public/images/images/sup.png' title='supprimer' />" ); supprimerLeMotif1(); } }); if(nbChampMotif == 5){ $('#ajouter_motif_img').toggle(false); } } function supprimerMotif(){ $('#supprimer_motif_img').click(function(){ $("#motif_admission"+nbChampMotif).val(''); $('#motif'+nbChampMotif).toggle(false); nbChampMotif--; if(nbChampMotif == 1){ $('#supprimer_motif_img').toggle(false); $(".supprimerMotif1" ).replaceWith( "<img class='supprimerMotif' src='"+tabUrl[0]+"public/images/images/sup2.png' />" ); } if(nbChampMotif == 4){ $('#ajouter_motif_img').toggle(true); } }); } function supprimerLeMotif1(){ $(".supprimerMotif1").click(function(){ for(var i=1; i<nbChampMotif; i++){ $("#motif_admission"+i).val( $("#motif_admission"+(i+1)).val() ); } $("#motif_admission"+i).val(''); $('#motif'+i).toggle(false); if(nbChampMotif == 5){ $('#ajouter_motif_img').toggle(true); } if(nbChampMotif == 2){ $('#supprimer_motif_img').toggle(false); $(".supprimerMotif1" ).replaceWith( "<img class='supprimerMotif' src='"+tabUrl[0]+"public/images/images/sup2.png' />" ); } nbChampMotif--; return false; }); } function supprimerUnMotif(){ $(".supprimerMotif2").click(function(){ for(var i=2; i<nbChampMotif; i++){ $("#motif_admission"+i).val( $("#motif_admission"+(i+1)).val() ); } $("#motif_admission"+i).val(''); $('#motif'+i).toggle(false); if(nbChampMotif == 5){ $('#ajouter_motif_img').toggle(true); } if(nbChampMotif == 2){ $('#supprimer_motif_img').toggle(false); $(".supprimerMotif1" ).replaceWith( "<img class='supprimerMotif' src='"+tabUrl[0]+"public/images/images/sup2.png' />" ); } nbChampMotif--; return false; }); $(".supprimerMotif3").click(function(){ for(var i=3; i<nbChampMotif; i++){ $("#motif_admission"+i).val( $("#motif_admission"+(i+1)).val() ); } $("#motif_admission"+i).val(''); $('#motif'+i).toggle(false); if(nbChampMotif == 5){ $('#ajouter_motif_img').toggle(true); } if(nbChampMotif == 2){ $('#supprimer_motif_img').toggle(false); $(".supprimerMotif1" ).replaceWith( "<img class='supprimerMotif' src='"+tabUrl[0]+"public/images/images/sup2.png' />" ); } nbChampMotif--; return false; }); $(".supprimerMotif4").click(function(){ for(var i=4; i<nbChampMotif; i++){ $("#motif_admission"+i).val( $("#motif_admission"+(i+1)).val() ); } $("#motif_admission"+i).val(''); $('#motif'+i).toggle(false); if(nbChampMotif == 5){ $('#ajouter_motif_img').toggle(true); } if(nbChampMotif == 2){ $('#supprimer_motif_img').toggle(false); $(".supprimerMotif1" ).replaceWith( "<img class='supprimerMotif' src='"+tabUrl[0]+"public/images/images/sup2.png' />" ); } nbChampMotif--; return false; }); $(".supprimerMotif5").click(function(){ for(var i=5; i<nbChampMotif; i++){ $("#motif_admission"+i).val( $("#motif_admission"+(i+1)).val() ); } $("#motif_admission"+i).val(''); $('#motif'+i).toggle(false); if(nbChampMotif == 5){ $('#ajouter_motif_img').toggle(true); } if(nbChampMotif == 2){ $('#supprimer_motif_img').toggle(false); $(".supprimerMotif1" ).replaceWith( "<img class='supprimerMotif' src='"+tabUrl[0]+"public/images/images/sup2.png' />" ); } nbChampMotif--; return false; }); } //********************* motif_admission ***************************** //********************* motif_admission ***************************** $(function(){ var motif1 = $("#motif_admission1"); var motif2 = $("#motif_admission2"); var motif3 = $("#motif_admission3"); var motif4 = $("#motif_admission4"); var motif5 = $("#motif_admission5"); //Au debut on affiche pas le bouton modifier $("#bouton_motif_modifier").toggle(false); //Au debut on affiche le bouton valider $("#bouton_motif_valider").toggle(true); //Au debut on desactive tous les champs motif1.attr( 'readonly', false); motif2.attr( 'readonly', false); motif3.attr( 'readonly', false); motif4.attr( 'readonly', false); motif5.attr( 'readonly', false); $("#bouton_motif_valider").click(function(){ motif1.attr( 'readonly', true); motif2.attr( 'readonly', true); motif3.attr( 'readonly', true); motif4.attr( 'readonly', true); motif5.attr( 'readonly', true); $("#bouton_motif_modifier").toggle(true); $("#bouton_motif_valider").toggle(false); $('#ajouter_motif_img').toggle(false); $('#supprimer_motif_img').toggle(false); $('.supprimerMotif1, .supprimerMotif2, .supprimerMotif3, .supprimerMotif4, .supprimerMotif5').toggle(false); return false; }); $("#bouton_motif_modifier").click(function(){ motif1.attr( 'readonly', false); motif2.attr( 'readonly', false); motif3.attr( 'readonly', false); motif4.attr( 'readonly', false); motif5.attr( 'readonly', false); $("#bouton_motif_modifier").toggle(false); $("#bouton_motif_valider").toggle(true); if(nbChampMotif != 5) { $('#ajouter_motif_img').toggle(true); } if(nbChampMotif != 1) { $('#supprimer_motif_img').toggle(true); } $('.supprimerMotif1, .supprimerMotif2, .supprimerMotif3, .supprimerMotif4, .supprimerMotif5').toggle(true); return false; }); });
// (c) 2013 Manuel Braun (mb@w69b.com) goog.provide('w69b.qr.CanvasDrawable'); goog.require('w69b.qr.Drawable'); goog.scope(function() { /** * @constructor * @param {HTMLCanvasElement} canvas to draw on. * @implements {w69b.qr.Drawable} */ w69b.qr.CanvasDrawable = function(canvas) { this.canvas_ = canvas; this.context_ = canvas.getContext('2d'); this.bgStyle_ = 'rgb(255, 255, 255)'; this.fgStyle_ = 'rgb(0, 0, 0)'; }; var pro = w69b.qr.CanvasDrawable.prototype; pro.fillBackground = function(width, height) { this.canvas_.width = width; this.canvas_.height = height; this.context_.fillStyle = this.bgStyle_; this.context_.fillRect(0, 0, width, height); }; pro.fillBlack = function(x, y, width, height) { this.context_.fillStyle = this.fgStyle_; // this.context_.strokeStyle = this.fgStyle_; this.context_.fillRect(x, y, width, height); }; });
import { myParse } from './calculator_parse.js'; const APPEND_event = 'APPEND_event'; const CLEAR_event = 'CLEAR_event'; const CALC_event = 'CALC_event'; const defaultState = { display: { fullDisplay: '0', curNumber: '0', newCalc: false } } const appendAction = function (str) { return { type: APPEND_event, str: str }; } const clearAction = function () { return { type: CLEAR_event, str: 'C' }; } const calcAction = function () { return { type: CALC_event, str: '=' }; } const displayParser = function (state = defaultState.display, action) { switch (action.type) { case APPEND_event: case CLEAR_event: case CALC_event: var ret = myParse(state, action.str); return ret; default: return state; } } var store = Redux.createStore(Redux.combineReducers({ display: displayParser })); store.subscribe(function () { console.log('Redux Store:', store.getState()); }) export { store, appendAction, clearAction, calcAction };
import { ACTIONS, Container } from '../../Container.js' import { Cursor } from './cursor.js' import { TextSize } from './TextSize.js' import { FontManager } from './fonts.js' import { Keyboard } from '../utils/keyboard.js' import { EVENTS as ClipboardEvents, Clipboard } from '../utils/clipboard.js' import { ACCESS_REQUIREMENT } from '../utils/InputAccessManager.mjs' import { findCommonStyleSubset } from '../utils/common.js' import { queueWork } from '../../YeldingExecutor.js' //import { getSelection } from '../utils/common.js' //TODO: //fix reverse selection (sometimes it is smaller than it should be) //forward delete doesn't work well (via delete key) //better line comprehension in text manipulation: // - fixed line heights //span compaction (combine if style is identical) //unicode & escaped character support //serialize text units as rich text //line spacing //wrapping - add in logic to support: /* 1. resizing container as text is typed (both with and height) 2. automatically wrapping a line that is too long -> cursor support for this (depends on knowing char height and width) Types of fields: 1. Just a text field width: auto height: auto - self adjusting or fitVisibleContent with expandOnly = false 2. Fixed width text field width: x px height: auto - need some function to break the line - needs auto line breaking 3. Multi content text field width: x px height: y px - container.fitVisibleContent() */ const textItemPerms = {}//, "container.edit":{"*":false}} textItemPerms[ACTIONS.setPosition] = {"*":false} textItemPerms[ACTIONS.create] = {"*":false} const textLinePerms = {} textLinePerms[ACTIONS.setPosition] = {"*":false} export class ContainerTextInjector { appId = "container.edit.text" container = null; target = null; newLineChar = '\n'; tabCharacter = '\t'; tabInSpaces = ' '; #textSize = null; #interface = null; #keyboard = null; #clipboard = null; #fontManager = null; #enabled = false #handlers = {}; //shift select #toggleSelectionModify = false; #anchorCursor = {} #debug = false; #cursorDiv = null defaultTextBoxDescriptor = { nodeName:"DIV", computedStyle:{ "position":"absolute", "background-color": "transparent", "width":"auto", "height":"auto", "min-width":"32px", "min-height":"32px" }, data:{}//[TODO] } cursorDescriptor = { nodeName:"DIV", className: "text-document-cursor", computedStyle:{"position":"absolute"}, data:{ ignore:true, containerPermissions:{ "container.broadcast":{"*":false}, "container.bridge":{"*":false} } } } lineDescriptor = { nodeName: "DIV", className: "text-document-line", "data":{ //"containerActions":[{"trigger":"click","call":"container.edit.text.onLineClick","params":[]}], "containerPermissions":textLinePerms } } textUnitDescriptor = { nodeName: "SPAN", className: "text-document-unit", computedStyle:{}, "data":{ "containerActions":[{"trigger":"click","call":"container.edit.text.onTextUnitClick","params":[]}], "containerPermissions":textItemPerms } } state = { control:false, bold:'normal', italic:'normal', underlined: '', textColor: undefined, highlightColor: undefined, fontFam: "Arial", fontSize: "15px" } cursor = null constructor (container, debug) { this.container = container; container.registerComponent(this); this.#debug = debug if(debug) { this.lineDescriptor['computedStyle'] = { "border-width": "3px", "border-color": "red", "border-style": "dotted" } this.textUnitDescriptor['computedStyle'] = this.lineDescriptor.computedStyle; console.log("Text editor runnign in debug mode") } this.cursor = new Cursor(this) this.#textSize = new TextSize(container, this) this.#keyboard = new Keyboard(this.appId, container, ACCESS_REQUIREMENT.EXCLUSIVE) this.initKeyboard(); this.#clipboard = new Clipboard(this.appId, container); this.#clipboard.setAction(ClipboardEvents.paste, (event) => this.paste(event.detail.originalEvent), ACCESS_REQUIREMENT.EXCLUSIVE) this.#clipboard.setAction(ClipboardEvents.cut, (event) => this.cut(event.detail.originalEvent), ACCESS_REQUIREMENT.EXCLUSIVE) this.#clipboard.setAction(ClipboardEvents.copy, (event) => {}, //noop ACCESS_REQUIREMENT.EXCLUSIVE) this.#fontManager = new FontManager(container) this.#handlers['selectionchange'] = (e) => this.onSelectionChange(e) //create interface holder this.#interface = this.container.createFromSerializable(document.body, { "nodeName":"div", "computedStyle":{ "top":"0px", "left":"0px", "position":"absolute" }, "data":{ "ignore":true, "containerPermissions":{ "container.broadcast":{"*":false}, "container.bridge":{"*":false} } } }, null, this.appId) this.container.hide(this.#interface, this.appId) //load interface style and html this.container.loadStyle("style.css", this.appId) this.container.loadHtml(this.#interface, "interface.html", this.appId) .then(e => { this.#loadFontsInInterface() }) //create cursor pointer this.#cursorDiv = this.container.createFromSerializable(document.body, this.cursorDescriptor, null, this.appId) this.container.hide(this.#cursorDiv, this.appId) } enable() { if (!this.#enabled) { for (const [key, value] of Object.entries(this.#handlers)) { this.container.addEventListener(key, value, this.appId) } document.addEventListener("selectionchange", this.#handlers['selectionchange']) this.#enabled = true } } disable() { if (this.#enabled) { this.stop(); for (const [key, value] of Object.entries(this.#handlers)) { this.container.removeEventListener(key, value, this.appId) } document.removeEventListener("selectionchange", this.#handlers['selectionchange']) this.container.hide(this.#interface, this.appId) this.#enabled = false } } isEnabled() { return this.#enabled } initKeyboard () { this.#keyboard.onPritable(this, (key) => this.addPrintable(key), true) this.#keyboard.setAction(new Set(['Backspace']), this, (key) => this.removePrintable(-1), true) this.#keyboard.setAction(new Set(['Delete']), this, (key) => this.removePrintable(1), true) this.#keyboard.setAction(new Set(['Enter']), this, (key) => this.newLine(), true) this.#keyboard.setAction(new Set(['Escape']), this, (key) => this.stop(), true) this.#keyboard.setAction(new Set(['Tab']), this, (key) => this.tab(), true, true) this.#keyboard.setAction(new Set(['Shift']), this, (key) => { this.#toggleSelectionModify = true this.#anchorCursor = this.cursor.get() }, true) this.#keyboard.setKeyUpAction(new Set(['Shift']), this, (key) => this.#toggleSelectionModify = false, true) this.#keyboard.setAction(new Set(['Down']), this, (key) => this.cursorDown(), true) this.#keyboard.setAction(new Set(['ArrowDown']), this, (key) => this.cursorDown(), true) this.#keyboard.setAction(new Set(['Up']), this, (key) => this.cursorUp(), true) this.#keyboard.setAction(new Set(['ArrowUp']), this, (key) => this.cursorUp(), true) this.#keyboard.setAction(new Set(['Left']), this, (key) => this.cursorLeft(), true) this.#keyboard.setAction(new Set(['ArrowLeft']), this, (key) => this.cursorLeft(), true) this.#keyboard.setAction(new Set(['Right']), this, (key) => this.cursorRight(), true) this.#keyboard.setAction(new Set(['ArrowRight']), this, (key) => this.cursorRight(), true) this.#keyboard.setAction(new Set(['End']), this, (key) => this.toLineEnd(), true) this.#keyboard.setAction(new Set(['Home']), this, (key) => this.toLineStart(), true) this.#keyboard.setAction(new Set(['Control','u']), this, (key) => this.underlined(), true) this.#keyboard.setAction(new Set(['Control','i']), this, (key) => this.italic(), true) this.#keyboard.setAction(new Set(['Control','b']), this, (key) => this.bold(), true) this.#keyboard.setAction(new Set(['Control','a']), this, (key) => this.selectAll(), true) this.#keyboard.setAction(new Set(['Control','1']), this, (key) => this.align('left'), true) this.#keyboard.setAction(new Set(['Control','2']), this, (key) => this.align('center'), true) this.#keyboard.setAction(new Set(['Control','3']), this, (key) => this.align('right'), true) this.#keyboard.setAction(new Set(['Control','4']), this, (key) => this.align('justify'), true) this.#keyboard.setAction(new Set(['Control','+']), this, (key) => this.changeFontSize(1), true) this.#keyboard.setAction(new Set(['Control','-']), this, (key) => this.changeFontSize(-1), true) this.#keyboard.setAction(new Set(['Control','/']), this, (key) => this.underlined(), true) this.#keyboard.setAction(new Set(['Control',';']), this, (key) => this.underlined(), true) this.#keyboard.setAction(new Set(['Control','c']), this, (key) => {}, false) this.#keyboard.setAction(new Set(['Control','v']), this, (key) => {}, false) } #loadFontsInInterface () { let fonts = this.#fontManager.listFonts() let root = this.container.lookup("ns-text-editor-font") for (const fontName of fonts) { let fontRow = document.createElement('option') fontRow.value = fontName fontRow.innerHTML = fontName root.appendChild(fontRow) } } start (target, overrideNewBoxPos) { if (!target || this.target == target || !this.#enabled) { return; } this.container.componentStartedWork(this.appId, {}) console.log(`${this.appId} start text editing ${target}`) this.target = this.findFirstDivParent(this.container.lookup(target)); console.log(`${this.appId} Set text edit target to ${target.id}`) try { this.container.isOperationAllowed('container.edit', this.target, this.appId) } catch (e) { console.log(`${this.appId} - container does not allow editing at all. Aborting`) this.stop(); return; } if (!this.isTargetTextEditable(this.target)) { console.log(`${this.appId} - container not suitable for text editing. Creating a transparent container to type in.`) this.target = this.container.createFromSerializable(this.target, this.defaultTextBoxDescriptor, null, this.appId) if (overrideNewBoxPos) { this.container.setPosition(this.target, overrideNewBoxPos, this.appId) } } this.cursor.setTarget(this.target) this.container.show(this.#interface, this.appId) let pos = this.container.getPosition(this.target) //set interface position pos.originX = 0.0 pos.originY = 1.0 this.container.setPosition(this.#interface, pos, this.appId) this.#interface.style['min-width'] = this.container.getWidth(this.target) //bring up interface this.container.bringToFront(this.#interface, this.appId) this.container.show(this.#cursorDiv, this.appId) this.container.bringToFront(this.#cursorDiv, this.appId) //TODO use cascading and local permissions //these need to be ephemeral state, not sent to the server and propagated... this.container.setMetadata(this.target, 'text-editing', true) this.container.setPermission(this.target, ACTIONS.cascade, '*', false, this.appId, true) //this.container.setPermission(this.target, ACTIONS.delete, 'container.create', false, this.appId) this.#keyboard.enable(); this.#clipboard.enable(); if (this.container.camera) { this.container.camera.focusOn(this.target) } } stop () { if (this.target) { console.log(`${this.appId} stop text editing`) this.container.componentStoppedWork(this.appId) this.#keyboard.disable() this.#clipboard.disable() //this.container.removePermission(this.target, ACTIONS.delete, 'container.create', false, this.appId) this.container.removeMetadata(this.target, 'text-editing') this.container.removePermission(this.target, ACTIONS.cascade, '*', this.appId) this.cursor.setTarget(null); this.container.hide(this.#cursorDiv, this.appId) this.container.hide(this.#interface, this.appId) this.target = null; } } getEditTarget() { return this.target } //[TODO]: make efficient, should not loop over every time getLinesCount(target = {childNodes:[]}) { let count = 0 for (const child of target.childNodes) { if (this.isLine(child) && this.isVisible(child)) { count++ } } return count } //[TODO]: make efficient, should not seek every time this is called getLine(target = {childNodes:[]}, lineNumber) { let count = 0; for (const child of target.childNodes) { if (this.isLine(child) && this.isVisible(child)) { if (count == lineNumber) { return child } count++; } } return null; } isVisible(target = {style:{display:'none'}}) { return target.style.display !== 'none' } static isPrintableCharacter(key) { return key.length === 1; } findFirstDivParent(elem) { if (!elem) return null; if (this.isTextUnit(elem)) { return elem.parentNode.parentNode } if (elem.nodeName == 'DIV') { if (this.isLine(elem)) { return elem.parentNode } return elem } return this.findFirstDivParent(elem.parentNode) } //[TODO]: reconsider criteria isTargetTextEditable(target) { if (target === this.container.parent) { console.log(`${this.appId} - currently not allowing adding text to root container`) return false; } for (const child of target.children) { if (this.isLine(child)) { console.log(`${this.appId} - found a line. Can text edit`) return true; } } if (!target.childNodes || this.getLinesCount(this.target) == 0) { return true; } console.log(`${this.appId} - comprised only of other type of containers. Cannot text edit`) return false; } #detectClipboardFormat(controller) { console.log(`CLIPBOARD_TYPES: ${JSON.stringify(controller.types)}`) //let rtf = controller.getData('text/html') //console.log(`RTF_CLIPBOARD: ${rtf}`) } //doesn't support rich text yet paste (event) { if (!this.target) { return; } let clipboardController = (event.clipboardData || window.clipboardData) let paste = clipboardController.getData('text'); this.addPrintable(paste) event.preventDefault(); //[TODO]: integrate this.#detectClipboardFormat(clipboardController) } cut (event) { if (!this.target) { return; } let selection = this.getSelected() if ( selection ) { event.clipboardData.setData("text/plain", this.serializeTextUnits(selection.units)) event.preventDefault(); } this.deleteSelection(); } isLine(elem) { return elem && elem.className && elem.className.includes(this.lineDescriptor.className); } isNewLine(elem) { return this.isLine(elem) && elem.children.length == 0; } isTextUnit(elem) { return elem && elem.className && elem.className.includes(this.textUnitDescriptor.className); } isTextUnitInCurrentTarget(unit) { while(unit) { if(unit == this.target) { return true; } unit = unit.parentNode } return false; } serializeTextUnits(units) { let result = "" for (const unit of units) { result += unit.innerHTML } return result } cursorUp () { if (!this.target) { return; } let curStat = this.cursor.getPosition() this.cursor.putAt(curStat.lineNumber - 1, curStat.charNumber) if (this.#toggleSelectionModify) { this.modifySelection() } else { this.clearSelection(); } this.cursorUpdateVisible(this.#cursorDiv) } cursorDown () { if (!this.target) { return; } let curStat = this.cursor.getPosition() this.cursor.putAt(curStat.lineNumber + 1, curStat.charNumber) if (this.#toggleSelectionModify) { this.modifySelection() } else { this.clearSelection(); } this.cursorUpdateVisible(this.#cursorDiv) } cursorLeft () { if (!this.target) { return; } this.cursor.move(-1) if (this.#toggleSelectionModify) { this.modifySelection() } else { this.clearSelection(); } this.cursorUpdateVisible(this.#cursorDiv) } cursorRight () { if (!this.target) { return; } this.cursor.move(1) if (this.#toggleSelectionModify) { this.modifySelection() } else { this.clearSelection(); } this.cursorUpdateVisible(this.#cursorDiv) } toLineEnd() { this.cursor.putAtLineEnd() if (this.#toggleSelectionModify) { this.modifySelection() } else { this.clearSelection(); } this.cursorUpdateVisible(this.#cursorDiv) } toLineStart() { this.cursor.putAtLineStart() if (this.#toggleSelectionModify) { this.modifySelection() } else { this.clearSelection(); } this.cursorUpdateVisible(this.#cursorDiv) } makeNewLine(insertAt) { let lineBefore = undefined; if (insertAt >= 0 && insertAt < this.getLinesCount(this.target)) { lineBefore = this.getLine(this.target, insertAt) } return this.container.createFromSerializable(this.target.id, this.lineDescriptor, lineBefore, this.appId) } #updateTextUnitDescriptorFromState() { this.textUnitDescriptor.computedStyle['color'] = this.state.textColor; //this.textUnitDescriptor.computedStyle['background-color'] = this.state.highlightColor; this.textUnitDescriptor.computedStyle['font-family'] = this.state.fontFam; this.textUnitDescriptor.computedStyle['font-size'] = this.state.fontSize; this.textUnitDescriptor.computedStyle['font-weight'] = this.state.bold; this.textUnitDescriptor.computedStyle['font-style'] = this.state.italic; this.textUnitDescriptor.computedStyle['text-decoration-line'] = this.state.underlined; } makeNewTextChild (line, before) { this.#updateTextUnitDescriptorFromState(); let unit = this.container.createFromSerializable(line.id, this.textUnitDescriptor, before, this.appId) return unit } styleTarget() { if ( this.target ) { this.container.fitVisibleContent(this.target, true) } } //[TODO]: NOT USED? findClosestTextUnit(line, direction) { let pointer = line let skippedLines = new Set([]) while (this.isNewLine(pointer)) { skippedLines.add(pointer) if (direction < 0) { pointer = pointer.previousSibling } else { pointer = pointer.nextSibling } } let result = null if (pointer && !this.isNewLine(pointer)) { if (direction < 0){ result = pointer.childNodes[pointer.childNodes.length - 1] } else { result = pointer.childNodes[0] } } return {textUnit: result, skippedLines: skippedLines} } findBetween (start, end, stopAtEOL) { if (!start && !end) { return {lines:new Set([]), units: new Set([])} } let currentLine = null let currentTextUnit = null if (this.isTextUnit(start)) { currentTextUnit = start currentLine = start.parentNode } else if (this.isLine(start)) { currentLine = start currentTextUnit = start.firstChild } else if (start) { throw `Find only works using text units and lines, you seem to have provided a different kind of DOM element for start` } let endTextUnit = null let endLine = null if (this.isTextUnit(end)) { endTextUnit = end endLine = end.parentNode } else if (this.isLine(end)) { endLine = end endTextUnit = end.lastChild } else if(end) { throw `Find only works using text units and lines, you seem to have provided a different kind of DOM element for end` } if (!start) { currentLine = endLine currentTextUnit = currentLine.firstChild } if (!end) { endLine = currentLine endTextUnit = currentLine.lastChild } let units = new Set([]) let lines = new Set([]) while (currentLine) { if (this.isLine(currentLine) && this.isVisible(currentLine)) { if (!currentTextUnit) { currentTextUnit = currentLine.firstChild } lines.add(currentLine) while (currentTextUnit) { if (this.isTextUnit(currentTextUnit)) { units.add(currentTextUnit) if (currentTextUnit == endTextUnit) { units.add(end) return {lines:lines, units:units} } } currentTextUnit = currentTextUnit.nextSibling } if (stopAtEOL) { break; } if (currentLine == endLine) { break; } } currentLine = currentLine.nextSibling } return {lines:lines, units:units} } makeSelection(start, end, startOffset = 0, endOffset = 0) { let range = new Range(); if (this.isTextUnitBefore(end, start)) { range.setStart(end.lastChild, (endOffset > 0) ? endOffset : end.lastChild.length); range.setEnd(start.firstChild, startOffset); } else { range.setStart(start.firstChild, startOffset); range.setEnd(end.lastChild, (endOffset > 0) ? endOffset : end.lastChild.length); } let sel = this.clearSelection() sel.addRange(range) } clearSelection () { let sel = document.getSelection(); sel.removeAllRanges(); return sel; } onSelectionChange(e) { let docSelect = document.getSelection(); if (!docSelect.focusNode) { return; } let focusTextUnit = docSelect.focusNode.parentNode let offset = docSelect.focusOffset; this.cursor.putOn(focusTextUnit, offset) this.cursorUpdateVisible(this.#cursorDiv) } getSelected () { let docSelect = document.getSelection(); //figure out if selection belongs to target if (docSelect && docSelect.focusNode && docSelect.anchorNode) { let focusTunitInTarget = this.isTextUnitInCurrentTarget(docSelect.focusNode.parentNode) let anchorTunitInTarget = this.isTextUnitInCurrentTarget(docSelect.anchorNode.parentNode) if (focusTunitInTarget && anchorTunitInTarget) { var start = docSelect.anchorNode.parentNode var startOffset = docSelect.anchorOffset var end = docSelect.focusNode.parentNode var endOffset = docSelect.focusOffset if (start == end && startOffset == endOffset) { this.clearSelection(); return null; } if (this.isTextUnitBefore(end, start)) { let aux = start; start = end; end = aux; } if (start == end && (startOffset > endOffset)){ let aux = endOffset; endOffset = startOffset; startOffset = aux; } let startSplit = this.splitTextUnit(start, startOffset) let startNode = startSplit[1] if (start == end) { endOffset -= startOffset end = startNode } let endSplit = this.splitTextUnit(end, endOffset) let endNode = endSplit[0] this.makeSelection(startNode, endNode) if (startSplit[0]) { this.cursor.putOn(startSplit[0], startSplit[0].innerHTML.length) } else if(endSplit[1]) { this.cursor.putOn(endSplit[1], 0) } return this.findBetween(startNode, endNode) } } return null; } modifySelection () { let curPos = this.cursor.get() let docSelect = document.getSelection(); if (docSelect && docSelect.anchorNode && docSelect.focusNode) { docSelect.extend(curPos.textUnit.firstChild, curPos.localCharNumber) } else { this.makeSelection(this.#anchorCursor.textUnit, curPos.textUnit, this.#anchorCursor.localCharNumber, curPos.localCharNumber) } } selectAll() { if (this.target) { this.makeSelection(this.target.firstChild.firstChild, this.target.lastChild.lastChild) } } // onLineClick(e) { // let line = e.target // this.start(e.target.parentNode) // } //cursor logic onTextUnitClick(e) { let textUnit = e.target let textStyle = this.container.toSerializableStyle(textUnit) let offset = this.#textSize.positionToCharNumber(textUnit.innerHTML, textStyle, 0, e.offsetX) this.start(e.target.parentNode.parentNode) this.cursor.putOn(textUnit, offset) this.cursorUpdateVisible(this.#cursorDiv) } cursorUpdateVisible(blinker) { if (!blinker) { blinker = this.#cursorDiv } let curStat = this.cursor.get() let localText = "" let localTarget = curStat.line let textUnit = curStat.textUnit if (textUnit) { localText = textUnit.innerHTML localTarget = textUnit } let localStyle = this.container.toSerializableStyle(localTarget) let localPosition = this.#textSize.charNumberToPosition(localText, localStyle, curStat.localCharNumber) let globalPosition = this.container.localToGlobalPosition(localTarget, localPosition.left, localPosition.top) let unitHeight = this.container.getHeight(localTarget) this.container.show(blinker, this.appId) this.container.setPosition(blinker, globalPosition, this.appId) this.container.setHeight(blinker, unitHeight, this.appId) this.container.bringToFront(blinker, this.appId) } splitTextUnit(unit, offset) { if (!this.isTextUnit(unit)) { throw 'You can use splitTextUnit only on textUnits' } if (offset == 0) { return [unit.previousSibling, unit] } if (offset == unit.innerHTML.length) { return [unit, unit.nextSibling] } let rightText = unit.innerHTML.substring(offset, unit.innerHTML.length) unit.innerHTML = unit.innerHTML.substring(0, offset) let descriptor = this.container.toSerializable(unit.id) delete descriptor.id; descriptor.innerHTML = rightText; descriptor.data.containerPermissions = JSON.stringify(textItemPerms) this.container.notifyUpdate(unit, this.appId) let right = this.container.createFromSerializable(unit.parentNode.id, descriptor, unit.nextSibling, this.appId) return [unit, right] } deleteSelection() { let selection = this.getSelected(); this.clearSelection() if (selection && selection.units && selection.units.size > 0) { this.deleteTextUnits(selection.units, true); return true; } return false; } deleteLines(lines) { for (const line of lines) { this.container.delete(line, this.appId) } } deleteTextUnits(units, andLines) { for (const unit of units) { let parent = unit.parentNode this.container.delete(unit, this.appId) if (parent.children.length == 0 && andLines) { this.container.delete(parent, this.appId) } } } insertTextBlockAsLine(descriptor, lineBefore) { let line = this.container.createFromSerializable(this.target.id, this.lineDescriptor, lineBefore, this.appId) this.container.createFromSerializable(line, descriptor, null, this.appId) } addPrintable(text) { if (!this.target) { return; } //if there's a selection delete it first this.deleteSelection(); let curStat = this.cursor.get() if (!curStat.line) { this.makeNewLine(0) curStat = this.cursor.get() } if (!curStat.textUnit) { this.makeNewTextChild(curStat.line) curStat = this.cursor.get() } let textLines = text.split(this.newLineChar) console.log(textLines) let textUnit = curStat.textUnit; let existing = textUnit.innerHTML let before = existing.substring(0, curStat.localCharNumber) let after = existing.substring(curStat.localCharNumber, existing.length) let firstLine = textLines[0] textUnit.innerHTML = `${before}${firstLine.replaceAll(this.tabCharacter, this.tabInSpaces)}${after}` this.cursor.move(firstLine.length) this.cursorUpdateVisible(this.#cursorDiv) this.container.notifyUpdate(textUnit.id, this.appId) if (textLines.length > 1) { let lineBefore = this.getLine(this.target, curStat.lineNumber + 1) for (var i = 1; i < textLines.length; ++i) { let descriptor = Container.clone(this.textUnitDescriptor) descriptor.innerHTML = textLines[i].replaceAll(this.tabCharacter, this.tabInSpaces) queueWork(this.insertTextBlockAsLine, this, [descriptor, lineBefore]) } } queueWork(this.styleTarget, this) } newLine() { if (!this.target) { return; } this.clearSelection() let moveToNewLine = new Set([]) let curStat = this.cursor.get() if (curStat.textUnit) { let split = this.splitTextUnit(curStat.textUnit, curStat.localCharNumber) if (split[1]) { moveToNewLine = this.findBetween(split[1]).units } } //make new line and pull in items let line = this.makeNewLine(curStat.lineNumber + 1) for (const textUnit of moveToNewLine) { this.container.setParent(textUnit, line, this.appId) } //update cursor this.cursor.putAt(curStat.lineNumber + 1, 0) this.cursorUpdateVisible(this.#cursorDiv) this.styleTarget() } //BUG: fix forward deletion removePrintable(count) { if (!this.target) { return; } if (!count) { return; } //ToDo: update cursor in deleteSelection if (this.deleteSelection()) { return; } let start = undefined let startLine = undefined let end = undefined let endLine = undefined let cursorStart = this.cursor.get() let cursorEnd = null let currentLine = null let carryOver = null if (count > 0) { //completely untested flow if (cursorStart.textUnit) { start = this.splitTextUnit(cursorStart.textUnit, cursorStart.localCharNumber) carryOver = this.findBetween(null,start[0]).units } startLine = cursorStart.line cursorEnd = this.cursor.move(count) endLine = cursorEnd.line currentLine = endLine if (cursorEnd.textUnit) { end = this.splitTextUnit(cursorEnd.textUnit, cursorEnd.localCharNumber) } if(start && end && start[1] && start[1] == end[1]) { //split happened on the same text unit start[1] = end[0] } //todo replicate below case } else { if (cursorStart.textUnit) { end = this.splitTextUnit(cursorStart.textUnit, cursorStart.localCharNumber) carryOver = this.findBetween(end[1], null).units } endLine = cursorStart.line cursorEnd = this.cursor.move(count) startLine = cursorEnd.line currentLine = startLine if (cursorEnd.textUnit) { start = this.splitTextUnit(cursorEnd.textUnit, cursorEnd.localCharNumber) } if (end && start && cursorEnd.textUnit == end[0]) { //this is a special annoying case end[0] = start[1] } } //computing delete list let startElem = (start) ? (start[1] || start[0]) : startLine let endElem = (end) ? (end[0] || end[1]) : endLine let delList = this.findBetween( startElem, endElem ) let toDelete = delList.units if (start && !start[1]) { toDelete.delete(start[0]) } if (end && !end[0]) { toDelete.delete(end[1]) } let linesToDelete = delList.lines linesToDelete.delete(currentLine) this.deleteTextUnits(toDelete, false) if ( carryOver ) { for (const carryOverUnit of carryOver) { try { // this.container.setParent(carryOverUnit, currentLine, this.appId) } catch (e) { console.log("PLEASE FIX THIS. THERE WAS AN INVALID ELEMENT IN THE CARRY OVER SET") } } } this.deleteLines(linesToDelete) this.cursorUpdateVisible(this.#cursorDiv) } tabLineStart (line) { let firstTextUnit = line.firstChild || this.makeNewTextChild(line) firstTextUnit.innerHTML = `${this.tabInSpaces}${firstTextUnit.innerHTML}` } tab () { let selection = this.getSelected(); if (selection && selection.lines.size > 0) { for (const line of selection.lines) { queueWork(this.tabLineStart, this, [line]) } } else { this.addPrintable(this.tabInSpaces) } queueWork(this.styleTarget, this) } getTextUnitDistanceFromRoot(textUnit) { let dist = 0; let node = textUnit while (node) { if (this.isTextUnit(node) && !node.previousSibling) { node = node.parentNode } else { node = node.previousSibling } dist ++; } return dist; } isTextUnitBefore(textUnit1, textUnit2) { return this.getTextUnitDistanceFromRoot(textUnit1) < this.getTextUnitDistanceFromRoot(textUnit2) } styleTextUnits(style, textUnits) { for (const unit of textUnits) { if (this.isTextUnit(unit)) { this.container.styleChild(unit, style, this.appId) } } } styleLines (style, lines) { for (const unit of lines) { if (this.isLine(unit)) { this.container.styleChild(unit, style, this.appId) } } } getAllTextUnits() { let result = [] for (const line of this.target.children) { if (this.isLine(line)) { for(const unit of line.children) { if(this.isTextUnit(unit)) { result.push(unit) } } } } return result; } newTextUnitAtCursor () { let cursor = this.cursor.get() if (cursor && cursor.textUnit) { if (cursor.textUnit.innerHTML.length == 0) { this.#updateTextUnitDescriptorFromState(); this.container.styleChild(cursor.textUnit, this.textUnitDescriptor.computedStyle, this.appId) } else { let split = this.splitTextUnit(cursor.textUnit, cursor.localCharNumber) this.makeNewTextChild(cursor.line, split[1]); } } } changeFontSize (delta) { let selection = this.getSelected() if (!selection || selection.units.size == 0) { selection = {units:this.getAllTextUnits()} } let modFunc = function(e) { try { let fsize = parseInt(e,10) + delta return fsize+"px" } catch (ex){ return e } } this.styleTextUnits({"font-size": modFunc}, selection.units) this.cursorUpdateVisible(this.#cursorDiv) this.styleTarget() } setFontSize (fontSize) { let selection = this.getSelected() if (!selection || selection.units.size == 0) { this.newTextUnitAtCursor() return; } this.styleTextUnits({"font-size": fontSize}, selection.units) this.cursorUpdateVisible(this.#cursorDiv) this.styleTarget() } uiSelectFontSize() { let fsize = document.getElementById('ns-text-editor-font-select').value this.state.fontSize = `${fsize}px` this.setFontSize(this.state.fontSize) } fontUp (e) { e.preventDefault(); this.changeFontSize(1) try { let prevVal = document.getElementById('ns-text-editor-font-select').value document.getElementById('ns-text-editor-font-select').value = parseInt(prevVal) + 1 } catch (e) { } this.styleTarget() } fontDown (e) { e.preventDefault(); this.changeFontSize(-1) try { let prevVal = document.getElementById('ns-text-editor-font-select').value document.getElementById('ns-text-editor-font-select').value = parseInt(prevVal) - 1 } catch (e) { } this.styleTarget() } setFont(fontFam) { this.state.fontFam = fontFam let selection = this.getSelected() if (selection && selection.units.size > 0) { this.styleTextUnits({"font-family": fontFam}, selection.units); } else { this.newTextUnitAtCursor() } this.cursorUpdateVisible(this.#cursorDiv) this.styleTarget() } align (alignment) { let selection = this.getSelected() if (!selection || selection.lines.size == 0) { selection = {lines:this.target.children} } this.styleLines({"text-align": alignment, "text-justify": "inter-word"}, selection.lines) this.cursorUpdateVisible(this.#cursorDiv) } bold () { let toggleFunc = function(e) { if (e == "bold") { return "normal" } return "bold" } let selection = this.getSelected() if (selection && selection.units.size > 0) { let commonStyle = findCommonStyleSubset(this.container, selection.units) let currentValue = commonStyle["font-weight"] || "normal" this.styleTextUnits({"font-weight": toggleFunc(currentValue)}, selection.units) } else { this.state.bold = toggleFunc(this.state.bold); this.newTextUnitAtCursor() } this.clearSelection() this.cursorUpdateVisible(this.#cursorDiv) this.styleTarget() } italic (textUnits) { let toggleFunc = function(e) { if (e == 'italic') { return 'normal' } return 'italic' } let selection = this.getSelected() if (selection && selection.units.size > 0) { let commonStyle = findCommonStyleSubset(this.container, selection.units) let currentValue = commonStyle["font-style"] || "normal" this.styleTextUnits({"font-style": toggleFunc(currentValue)}, selection.units) } else { this.state.italic = toggleFunc(this.state.italic); this.newTextUnitAtCursor() } this.clearSelection() this.cursorUpdateVisible(this.#cursorDiv) this.styleTarget() } underlined (textUnits) { let toggleFunc = function(e) { if (e == 'underline') { return '' } return 'underline' } let selection = this.getSelected() if (selection && selection.units.size > 0) { let commonStyle = findCommonStyleSubset(this.container, selection.units) let currentValue = commonStyle["text-decoration-line"] || "" this.styleTextUnits({"text-decoration-line": toggleFunc(currentValue)}, selection.units) } else { this.state.underlined = toggleFunc(this.state.underlined); this.newTextUnitAtCursor() } this.clearSelection() this.cursorUpdateVisible(this.#cursorDiv) this.styleTarget() } #setColor(clr) { this.state.textColor = clr; let selection = this.getSelected() if (selection && selection.units.size > 0) { this.styleTextUnits({"color": clr}, selection.units) } else { this.newTextUnitAtCursor() } } setColor(e) { this.#setColor(e.target.value) } #setHighlightColor(clr) { this.state.highlightColor = clr; let selection = this.getSelected() if (selection && selection.units.size > 0) { this.styleTextUnits({"background-color": clr}, selection.units) } } setHighlightColor(e) { this.#setHighlightColor(e.target.value) } changeFont(e) { console.log(`${this.appId} setting font family to: ${e.target.value}`) this.setFont(e.target.value) } updateInterface() { document.getElementById('ns-text-editor-font').value = this.state.fontSize } }
/** * Resize function without multiple trigger * * Usage: * $(window).smartresize(function(){ * // code here * }); */ (function($,sr){ // debouncing function from John Hann // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ var debounce = function (func, threshold, execAsap) { var timeout; return function debounced () { var obj = this, args = arguments; function delayed () { if (!execAsap) func.apply(obj, args); timeout = null; } if (timeout) clearTimeout(timeout); else if (execAsap) func.apply(obj, args); timeout = setTimeout(delayed, threshold || 100); }; }; // smartresize jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); }; })(jQuery,'smartresize'); /** * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ var CURRENT_URL = window.location.href.split('#')[0].split('?')[0], $BODY = $('body'), $MENU_TOGGLE = $('#menu_toggle'), $SIDEBAR_MENU = $('#sidebar-menu'), $SIDEBAR_FOOTER = $('.sidebar-footer'), $LEFT_COL = $('.left_col'), $RIGHT_COL = $('.right_col'), $NAV_MENU = $('.nav_menu'), $FOOTER = $('footer'); // Sidebar function init_sidebar() { // TODO: This is some kind of easy fix, maybe we can improve this var setContentHeight = function () { // reset height $RIGHT_COL.css('min-height', $(window).height()); var bodyHeight = $BODY.outerHeight(), footerHeight = $BODY.hasClass('footer_fixed') ? -10 : $FOOTER.height(), leftColHeight = $LEFT_COL.eq(1).height() + $SIDEBAR_FOOTER.height(), contentHeight = bodyHeight < leftColHeight ? leftColHeight : bodyHeight; // normalize content contentHeight -= $NAV_MENU.height() + footerHeight; $RIGHT_COL.css('min-height', contentHeight); }; $SIDEBAR_MENU.find('a').on('click', function(ev) { console.log('clicked - sidebar_menu'); var $li = $(this).parent(); if ($li.is('.active')) { $li.removeClass('active active-sm'); $('ul:first', $li).slideUp(function() { setContentHeight(); }); } else { // prevent closing menu if we are on child menu if (!$li.parent().is('.child_menu')) { $SIDEBAR_MENU.find('li').removeClass('active active-sm'); $SIDEBAR_MENU.find('li ul').slideUp(); }else { if ( $BODY.is( ".nav-sm" ) ) { $SIDEBAR_MENU.find( "li" ).removeClass( "active active-sm" ); $SIDEBAR_MENU.find( "li ul" ).slideUp(); } } $li.addClass('active'); $('ul:first', $li).slideDown(function() { setContentHeight(); }); } }); // toggle small or large menu $MENU_TOGGLE.on('click', function() { console.log('clicked - menu toggle'); if ($BODY.hasClass('nav-md')) { $SIDEBAR_MENU.find('li.active ul').hide(); $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active'); } else { $SIDEBAR_MENU.find('li.active-sm ul').show(); $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm'); } $BODY.toggleClass('nav-md nav-sm'); setContentHeight(); }); // check active menu $SIDEBAR_MENU.find('a[href="' + CURRENT_URL + '"]').parent('li').addClass('current-page'); $SIDEBAR_MENU.find('a').filter(function () { return this.href == CURRENT_URL; }).parent('li').addClass('current-page').parents('ul').slideDown(function() { setContentHeight(); }).parent().addClass('active'); // recompute content when resizing $(window).smartresize(function(){ setContentHeight(); }); setContentHeight(); // fixed sidebar if ($.fn.mCustomScrollbar) { $('.menu_fixed').mCustomScrollbar({ autoHideScrollbar: true, theme: 'minimal', mouseWheel:{ preventDefault: true } }); } }; // /Sidebar var randNum = function() { return (Math.floor(Math.random() * (1 + 40 - 20))) + 20; }; // Panel toolbox $(document).ready(function() { $('.collapse-link').on('click', function() { var $BOX_PANEL = $(this).closest('.x_panel'), $ICON = $(this).find('i'), $BOX_CONTENT = $BOX_PANEL.find('.x_content'); // fix for some div with hardcoded fix class if ($BOX_PANEL.attr('style')) { $BOX_CONTENT.slideToggle(200, function(){ $BOX_PANEL.removeAttr('style'); }); } else { $BOX_CONTENT.slideToggle(200); $BOX_PANEL.css('height', 'auto'); } $ICON.toggleClass('fa-chevron-up fa-chevron-down'); }); $('.close-link').click(function () { var $BOX_PANEL = $(this).closest('.x_panel'); $BOX_PANEL.remove(); }); }); // /Panel toolbox // Tooltip $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip({ container: 'body' }); }); // /Tooltip // Progressbar if ($(".progress .progress-bar")[0]) { $('.progress .progress-bar').progressbar(); } // /Progressbar // Switchery $(document).ready(function() { if ($(".js-switch")[0]) { var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { var switchery = new Switchery(html, { color: '#26B99A' }); }); } }); // /Switchery // iCheck $(document).ready(function() { if ($("input.flat")[0]) { $(document).ready(function () { $('input.flat').iCheck({ checkboxClass: 'icheckbox_flat-green', radioClass: 'iradio_flat-green' }); }); } }); // /iCheck // Table $('table input').on('ifChecked', function () { checkState = ''; $(this).parent().parent().parent().addClass('selected'); countChecked(); }); $('table input').on('ifUnchecked', function () { checkState = ''; $(this).parent().parent().parent().removeClass('selected'); countChecked(); }); var checkState = ''; $('.bulk_action input').on('ifChecked', function () { checkState = ''; $(this).parent().parent().parent().addClass('selected'); countChecked(); }); $('.bulk_action input').on('ifUnchecked', function () { checkState = ''; $(this).parent().parent().parent().removeClass('selected'); countChecked(); }); $('.bulk_action input#check-all').on('ifChecked', function () { checkState = 'all'; countChecked(); }); $('.bulk_action input#check-all').on('ifUnchecked', function () { checkState = 'none'; countChecked(); }); function countChecked() { if (checkState === 'all') { $(".bulk_action input[name='table_records']").iCheck('check'); } if (checkState === 'none') { $(".bulk_action input[name='table_records']").iCheck('uncheck'); } var checkCount = $(".bulk_action input[name='table_records']:checked").length; if (checkCount) { $('.column-title').hide(); $('.bulk-actions').show(); $('.action-cnt').html(checkCount + ' Records Selected'); } else { $('.column-title').show(); $('.bulk-actions').hide(); } } // Accordion $(document).ready(function() { $(".expand").on("click", function () { $(this).next().slideToggle(200); $expand = $(this).find(">:first-child"); if ($expand.text() == "+") { $expand.text("-"); } else { $expand.text("+"); } }); }); // NProgress if (typeof NProgress != 'undefined') { $(document).ready(function () { NProgress.start(); }); $(window).load(function () { NProgress.done(); }); } //hover and retain popover when on popover content var originalLeave = $.fn.popover.Constructor.prototype.leave; $.fn.popover.Constructor.prototype.leave = function(obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type); var container, timeout; originalLeave.call(this, obj); if (obj.currentTarget) { container = $(obj.currentTarget).siblings('.popover'); timeout = self.timeout; container.one('mouseenter', function() { //We entered the actual popover – call off the dogs clearTimeout(timeout); //Let's monitor popover content instead container.one('mouseleave', function() { $.fn.popover.Constructor.prototype.leave.call(self, self); }); }); } }; $('body').popover({ selector: '[data-popover]', trigger: 'click hover', delay: { show: 50, hide: 400 } }); function gd(year, month, day) { return new Date(year, month - 1, day).getTime(); } function init_flot_chart(){ if( typeof ($.plot) === 'undefined'){ return; } console.log('init_flot_chart'); var arr_data1 = [ [gd(2012, 1, 1), 17], [gd(2012, 1, 2), 74], [gd(2012, 1, 3), 6], [gd(2012, 1, 4), 39], [gd(2012, 1, 5), 20], [gd(2012, 1, 6), 85], [gd(2012, 1, 7), 7] ]; var arr_data2 = [ [gd(2012, 1, 1), 82], [gd(2012, 1, 2), 23], [gd(2012, 1, 3), 66], [gd(2012, 1, 4), 9], [gd(2012, 1, 5), 119], [gd(2012, 1, 6), 6], [gd(2012, 1, 7), 9] ]; var arr_data3 = [ [0, 1], [1, 9], [2, 6], [3, 10], [4, 5], [5, 17], [6, 6], [7, 10], [8, 7], [9, 11], [10, 35], [11, 9], [12, 12], [13, 5], [14, 3], [15, 4], [16, 9] ]; var chart_plot_02_data = []; var chart_plot_03_data = [ [0, 1], [1, 9], [2, 6], [3, 10], [4, 5], [5, 17], [6, 6], [7, 10], [8, 7], [9, 11], [10, 35], [11, 9], [12, 12], [13, 5], [14, 3], [15, 4], [16, 9] ]; for (var i = 0; i < 30; i++) { chart_plot_02_data.push([new Date(Date.today().add(i).days()).getTime(), randNum() + i + i + 10]); } var chart_plot_01_settings = { series: { lines: { show: false, fill: true }, splines: { show: true, tension: 0.4, lineWidth: 1, fill: 0.4 }, points: { radius: 0, show: true }, shadowSize: 2 }, grid: { verticalLines: true, hoverable: true, clickable: true, tickColor: "#d5d5d5", borderWidth: 1, color: '#fff' }, colors: ["rgba(38, 185, 154, 0.38)", "rgba(3, 88, 106, 0.38)"], xaxis: { tickColor: "rgba(51, 51, 51, 0.06)", mode: "time", tickSize: [1, "day"], //tickLength: 10, axisLabel: "Date", axisLabelUseCanvas: true, axisLabelFontSizePixels: 12, axisLabelFontFamily: 'Verdana, Arial', axisLabelPadding: 10 }, yaxis: { ticks: 8, tickColor: "rgba(51, 51, 51, 0.06)", }, tooltip: false } var chart_plot_02_settings = { grid: { show: true, aboveData: true, color: "#3f3f3f", labelMargin: 10, axisMargin: 0, borderWidth: 0, borderColor: null, minBorderMargin: 5, clickable: true, hoverable: true, autoHighlight: true, mouseActiveRadius: 100 }, series: { lines: { show: true, fill: true, lineWidth: 2, steps: false }, points: { show: true, radius: 4.5, symbol: "circle", lineWidth: 3.0 } }, legend: { position: "ne", margin: [0, -25], noColumns: 0, labelBoxBorderColor: null, labelFormatter: function(label, series) { return label + '&nbsp;&nbsp;'; }, width: 40, height: 1 }, colors: ['#96CA59', '#3F97EB', '#72c380', '#6f7a8a', '#f7cb38', '#5a8022', '#2c7282'], shadowSize: 0, tooltip: true, tooltipOpts: { content: "%s: %y.0", xDateFormat: "%d/%m", shifts: { x: -30, y: -50 }, defaultTheme: false }, yaxis: { min: 0 }, xaxis: { mode: "time", minTickSize: [1, "day"], timeformat: "%d/%m/%y", min: chart_plot_02_data[0][0], max: chart_plot_02_data[20][0] } }; var chart_plot_03_settings = { series: { curvedLines: { apply: true, active: true, monotonicFit: true } }, colors: ["#26B99A"], grid: { borderWidth: { top: 0, right: 0, bottom: 1, left: 1 }, borderColor: { bottom: "#7F8790", left: "#7F8790" } } }; if ($("#chart_plot_01").length){ console.log('Plot1'); $.plot( $("#chart_plot_01"), [ arr_data1, arr_data2 ], chart_plot_01_settings ); } if ($("#chart_plot_02").length){ console.log('Plot2'); $.plot( $("#chart_plot_02"), [{ label: "Email Sent", data: chart_plot_02_data, lines: { fillColor: "rgba(150, 202, 89, 0.12)" }, points: { fillColor: "#fff" } }], chart_plot_02_settings); } if ($("#chart_plot_03").length){ console.log('Plot3'); $.plot($("#chart_plot_03"), [{ label: "Registrations", data: chart_plot_03_data, lines: { fillColor: "rgba(150, 202, 89, 0.12)" }, points: { fillColor: "#fff" } }], chart_plot_03_settings); }; } /* STARRR */ function init_starrr() { if( typeof (starrr) === 'undefined'){ return; } console.log('init_starrr'); $(".stars").starrr(); $('.stars-existing').starrr({ rating: 4 }); $('.stars').on('starrr:change', function (e, value) { $('.stars-count').html(value); }); $('.stars-existing').on('starrr:change', function (e, value) { $('.stars-count-existing').html(value); }); }; function init_JQVmap(){ //console.log('check init_JQVmap [' + typeof (VectorCanvas) + '][' + typeof (jQuery.fn.vectorMap) + ']' ); if(typeof (jQuery.fn.vectorMap) === 'undefined'){ return; } console.log('init_JQVmap'); if ($('#world-map-gdp').length ){ $('#world-map-gdp').vectorMap({ map: 'world_en', backgroundColor: null, color: '#ffffff', hoverOpacity: 0.7, selectedColor: '#666666', enableZoom: true, showTooltip: true, values: sample_data, scaleColors: ['#E6F2F0', '#149B7E'], normalizeFunction: 'polynomial' }); } if ($('#usa_map').length ){ $('#usa_map').vectorMap({ map: 'usa_en', backgroundColor: null, color: '#ffffff', hoverOpacity: 0.7, selectedColor: '#666666', enableZoom: true, showTooltip: true, values: sample_data, scaleColors: ['#E6F2F0', '#149B7E'], normalizeFunction: 'polynomial' }); } }; function init_skycons(){ if( typeof (Skycons) === 'undefined'){ return; } console.log('init_skycons'); var icons = new Skycons({ "color": "#73879C" }), list = [ "clear-day", "clear-night", "partly-cloudy-day", "partly-cloudy-night", "cloudy", "rain", "sleet", "snow", "wind", "fog" ], i; for (i = list.length; i--;) icons.set(list[i], list[i]); icons.play(); } function init_chart_doughnut(){ if( typeof (Chart) === 'undefined'){ return; } console.log('init_chart_doughnut'); if ($('.canvasDoughnut').length){ var chart_doughnut_settings = { type: 'doughnut', tooltipFillColor: "rgba(51, 51, 51, 0.55)", data: { labels: [ "Symbian", "Blackberry", "Other", "Android", "IOS" ], datasets: [{ data: [15, 20, 30, 10, 30], backgroundColor: [ "#BDC3C7", "#9B59B6", "#E74C3C", "#26B99A", "#3498DB" ], hoverBackgroundColor: [ "#CFD4D8", "#B370CF", "#E95E4F", "#36CAAB", "#49A9EA" ] }] }, options: { legend: false, responsive: false } } $('.canvasDoughnut').each(function(){ var chart_element = $(this); var chart_doughnut = new Chart( chart_element, chart_doughnut_settings); }); } } function init_gauge() { if( typeof (Gauge) === 'undefined'){ return; } console.log('init_gauge [' + $('.gauge-chart').length + ']'); console.log('init_gauge'); var chart_gauge_settings = { lines: 12, angle: 0, lineWidth: 0.4, pointer: { length: 0.75, strokeWidth: 0.042, color: '#1D212A' }, limitMax: 'false', colorStart: '#1ABC9C', colorStop: '#1ABC9C', strokeColor: '#F0F3F3', generateGradient: true }; if ($('#chart_gauge_01').length){ var chart_gauge_01_elem = document.getElementById('chart_gauge_01'); var chart_gauge_01 = new Gauge(chart_gauge_01_elem).setOptions(chart_gauge_settings); } if ($('#gauge-text').length){ chart_gauge_01.maxValue = 6000; chart_gauge_01.animationSpeed = 32; chart_gauge_01.set(3200); chart_gauge_01.setTextField(document.getElementById("gauge-text")); } if ($('#chart_gauge_02').length){ var chart_gauge_02_elem = document.getElementById('chart_gauge_02'); var chart_gauge_02 = new Gauge(chart_gauge_02_elem).setOptions(chart_gauge_settings); } if ($('#gauge-text2').length){ chart_gauge_02.maxValue = 9000; chart_gauge_02.animationSpeed = 32; chart_gauge_02.set(2400); chart_gauge_02.setTextField(document.getElementById("gauge-text2")); } } /* SPARKLINES */ function init_sparklines() { if(typeof (jQuery.fn.sparkline) === 'undefined'){ return; } console.log('init_sparklines'); $(".sparkline_one").sparkline([2, 4, 3, 4, 5, 4, 5, 4, 3, 4, 5, 6, 4, 5, 6, 3, 5, 4, 5, 4, 5, 4, 3, 4, 5, 6, 7, 5, 4, 3, 5, 6], { type: 'bar', height: '125', barWidth: 13, colorMap: { '7': '#a1a1a1' }, barSpacing: 2, barColor: '#26B99A' }); $(".sparkline_two").sparkline([2, 4, 3, 4, 5, 4, 5, 4, 3, 4, 5, 6, 7, 5, 4, 3, 5, 6], { type: 'bar', height: '40', barWidth: 9, colorMap: { '7': '#a1a1a1' }, barSpacing: 2, barColor: '#26B99A' }); $(".sparkline_three").sparkline([2, 4, 3, 4, 5, 4, 5, 4, 3, 4, 5, 6, 7, 5, 4, 3, 5, 6], { type: 'line', width: '200', height: '40', lineColor: '#26B99A', fillColor: 'rgba(223, 223, 223, 0.57)', lineWidth: 2, spotColor: '#26B99A', minSpotColor: '#26B99A' }); $(".sparkline11").sparkline([2, 4, 3, 4, 5, 4, 5, 4, 3, 4, 6, 2, 4, 3, 4, 5, 4, 5, 4, 3], { type: 'bar', height: '40', barWidth: 8, colorMap: { '7': '#a1a1a1' }, barSpacing: 2, barColor: '#26B99A' }); $(".sparkline22").sparkline([2, 4, 3, 4, 7, 5, 4, 3, 5, 6, 2, 4, 3, 4, 5, 4, 5, 4, 3, 4, 6], { type: 'line', height: '40', width: '200', lineColor: '#26B99A', fillColor: '#ffffff', lineWidth: 3, spotColor: '#34495E', minSpotColor: '#34495E' }); $(".sparkline_bar").sparkline([2, 4, 3, 4, 5, 4, 5, 4, 3, 4, 5, 6, 4, 5, 6, 3, 5], { type: 'bar', colorMap: { '7': '#a1a1a1' }, barColor: '#26B99A' }); $(".sparkline_area").sparkline([5, 6, 7, 9, 9, 5, 3, 2, 2, 4, 6, 7], { type: 'line', lineColor: '#26B99A', fillColor: '#26B99A', spotColor: '#4578a0', minSpotColor: '#728fb2', maxSpotColor: '#6d93c4', highlightSpotColor: '#ef5179', highlightLineColor: '#8ba8bf', spotRadius: 2.5, width: 85 }); $(".sparkline_line").sparkline([2, 4, 3, 4, 5, 4, 5, 4, 3, 4, 5, 6, 4, 5, 6, 3, 5], { type: 'line', lineColor: '#26B99A', fillColor: '#ffffff', width: 85, spotColor: '#34495E', minSpotColor: '#34495E' }); $(".sparkline_pie").sparkline([1, 1, 2, 1], { type: 'pie', sliceColors: ['#26B99A', '#ccc', '#75BCDD', '#D66DE2'] }); $(".sparkline_discreet").sparkline([4, 6, 7, 7, 4, 3, 2, 1, 4, 4, 2, 4, 3, 7, 8, 9, 7, 6, 4, 3], { type: 'discrete', barWidth: 3, lineColor: '#26B99A', width: '85', }); }; /* AUTOCOMPLETE */ function init_autocomplete() { if( typeof (autocomplete) === 'undefined'){ return; } console.log('init_autocomplete'); var countries = { AD:"Andorra",A2:"Andorra Test",AE:"United Arab Emirates",AF:"Afghanistan",AG:"Antigua and Barbuda",AI:"Anguilla",AL:"Albania",AM:"Armenia",AN:"Netherlands Antilles",AO:"Angola",AQ:"Antarctica",AR:"Argentina",AS:"American Samoa",AT:"Austria",AU:"Australia",AW:"Aruba",AX:"Åland Islands",AZ:"Azerbaijan",BA:"Bosnia and Herzegovina",BB:"Barbados",BD:"Bangladesh",BE:"Belgium",BF:"Burkina Faso",BG:"Bulgaria",BH:"Bahrain",BI:"Burundi",BJ:"Benin",BL:"Saint Barthélemy",BM:"Bermuda",BN:"Brunei",BO:"Bolivia",BQ:"British Antarctic Territory",BR:"Brazil",BS:"Bahamas",BT:"Bhutan",BV:"Bouvet Island",BW:"Botswana",BY:"Belarus",BZ:"Belize",CA:"Canada",CC:"Cocos [Keeling] Islands",CD:"Congo - Kinshasa",CF:"Central African Republic",CG:"Congo - Brazzaville",CH:"Switzerland",CI:"Côte d’Ivoire",CK:"Cook Islands",CL:"Chile",CM:"Cameroon",CN:"China",CO:"Colombia",CR:"Costa Rica",CS:"Serbia and Montenegro",CT:"Canton and Enderbury Islands",CU:"Cuba",CV:"Cape Verde",CX:"Christmas Island",CY:"Cyprus",CZ:"Czech Republic",DD:"East Germany",DE:"Germany",DJ:"Djibouti",DK:"Denmark",DM:"Dominica",DO:"Dominican Republic",DZ:"Algeria",EC:"Ecuador",EE:"Estonia",EG:"Egypt",EH:"Western Sahara",ER:"Eritrea",ES:"Spain",ET:"Ethiopia",FI:"Finland",FJ:"Fiji",FK:"Falkland Islands",FM:"Micronesia",FO:"Faroe Islands",FQ:"French Southern and Antarctic Territories",FR:"France",FX:"Metropolitan France",GA:"Gabon",GB:"United Kingdom",GD:"Grenada",GE:"Georgia",GF:"French Guiana",GG:"Guernsey",GH:"Ghana",GI:"Gibraltar",GL:"Greenland",GM:"Gambia",GN:"Guinea",GP:"Guadeloupe",GQ:"Equatorial Guinea",GR:"Greece",GS:"South Georgia and the South Sandwich Islands",GT:"Guatemala",GU:"Guam",GW:"Guinea-Bissau",GY:"Guyana",HK:"Hong Kong SAR China",HM:"Heard Island and McDonald Islands",HN:"Honduras",HR:"Croatia",HT:"Haiti",HU:"Hungary",ID:"Indonesia",IE:"Ireland",IL:"Israel",IM:"Isle of Man",IN:"India",IO:"British Indian Ocean Territory",IQ:"Iraq",IR:"Iran",IS:"Iceland",IT:"Italy",JE:"Jersey",JM:"Jamaica",JO:"Jordan",JP:"Japan",JT:"Johnston Island",KE:"Kenya",KG:"Kyrgyzstan",KH:"Cambodia",KI:"Kiribati",KM:"Comoros",KN:"Saint Kitts and Nevis",KP:"North Korea",KR:"South Korea",KW:"Kuwait",KY:"Cayman Islands",KZ:"Kazakhstan",LA:"Laos",LB:"Lebanon",LC:"Saint Lucia",LI:"Liechtenstein",LK:"Sri Lanka",LR:"Liberia",LS:"Lesotho",LT:"Lithuania",LU:"Luxembourg",LV:"Latvia",LY:"Libya",MA:"Morocco",MC:"Monaco",MD:"Moldova",ME:"Montenegro",MF:"Saint Martin",MG:"Madagascar",MH:"Marshall Islands",MI:"Midway Islands",MK:"Macedonia",ML:"Mali",MM:"Myanmar [Burma]",MN:"Mongolia",MO:"Macau SAR China",MP:"Northern Mariana Islands",MQ:"Martinique",MR:"Mauritania",MS:"Montserrat",MT:"Malta",MU:"Mauritius",MV:"Maldives",MW:"Malawi",MX:"Mexico",MY:"Malaysia",MZ:"Mozambique",NA:"Namibia",NC:"New Caledonia",NE:"Niger",NF:"Norfolk Island",NG:"Nigeria",NI:"Nicaragua",NL:"Netherlands",NO:"Norway",NP:"Nepal",NQ:"Dronning Maud Land",NR:"Nauru",NT:"Neutral Zone",NU:"Niue",NZ:"New Zealand",OM:"Oman",PA:"Panama",PC:"Pacific Islands Trust Territory",PE:"Peru",PF:"French Polynesia",PG:"Papua New Guinea",PH:"Philippines",PK:"Pakistan",PL:"Poland",PM:"Saint Pierre and Miquelon",PN:"Pitcairn Islands",PR:"Puerto Rico",PS:"Palestinian Territories",PT:"Portugal",PU:"U.S. Miscellaneous Pacific Islands",PW:"Palau",PY:"Paraguay",PZ:"Panama Canal Zone",QA:"Qatar",RE:"Réunion",RO:"Romania",RS:"Serbia",RU:"Russia",RW:"Rwanda",SA:"Saudi Arabia",SB:"Solomon Islands",SC:"Seychelles",SD:"Sudan",SE:"Sweden",SG:"Singapore",SH:"Saint Helena",SI:"Slovenia",SJ:"Svalbard and Jan Mayen",SK:"Slovakia",SL:"Sierra Leone",SM:"San Marino",SN:"Senegal",SO:"Somalia",SR:"Suriname",ST:"São Tomé and Príncipe",SU:"Union of Soviet Socialist Republics",SV:"El Salvador",SY:"Syria",SZ:"Swaziland",TC:"Turks and Caicos Islands",TD:"Chad",TF:"French Southern Territories",TG:"Togo",TH:"Thailand",TJ:"Tajikistan",TK:"Tokelau",TL:"Timor-Leste",TM:"Turkmenistan",TN:"Tunisia",TO:"Tonga",TR:"Turkey",TT:"Trinidad and Tobago",TV:"Tuvalu",TW:"Taiwan",TZ:"Tanzania",UA:"Ukraine",UG:"Uganda",UM:"U.S. Minor Outlying Islands",US:"United States",UY:"Uruguay",UZ:"Uzbekistan",VA:"Vatican City",VC:"Saint Vincent and the Grenadines",VD:"North Vietnam",VE:"Venezuela",VG:"British Virgin Islands",VI:"U.S. Virgin Islands",VN:"Vietnam",VU:"Vanuatu",WF:"Wallis and Futuna",WK:"Wake Island",WS:"Samoa",YD:"People's Democratic Republic of Yemen",YE:"Yemen",YT:"Mayotte",ZA:"South Africa",ZM:"Zambia",ZW:"Zimbabwe",ZZ:"Unknown or Invalid Region" }; var countriesArray = $.map(countries, function(value, key) { return { value: value, data: key }; }); // initialize autocomplete with custom appendTo $('#autocomplete-custom-append').autocomplete({ lookup: countriesArray }); }; /* AUTOSIZE */ function init_autosize() { if(typeof $.fn.autosize !== 'undefined'){ autosize($('.resizable_textarea')); } }; /* PARSLEY */ function init_parsley() { if ($('#demo-form')[0] === undefined) { return; } if( typeof (parsley) === 'undefined'){ return; } console.log('init_parsley'); $/*.listen*/('parsley:field:validate', function() { validateFront(); }); $('#demo-form .btn').on('click', function() { $('#demo-form').parsley().validate(); validateFront(); }); var validateFront = function() { if (true === $('#demo-form').parsley().isValid()) { $('.bs-callout-info').removeClass('hidden'); $('.bs-callout-warning').addClass('hidden'); } else { $('.bs-callout-info').addClass('hidden'); $('.bs-callout-warning').removeClass('hidden'); } }; $/*.listen*/('parsley:field:validate', function() { validateFront(); }); $('#demo-form2 .btn').on('click', function() { $('#demo-form2').parsley().validate(); validateFront(); }); var validateFront = function() { if (true === $('#demo-form2').parsley().isValid()) { $('.bs-callout-info').removeClass('hidden'); $('.bs-callout-warning').addClass('hidden'); } else { $('.bs-callout-info').addClass('hidden'); $('.bs-callout-warning').removeClass('hidden'); } }; try { hljs.initHighlightingOnLoad(); } catch (err) {} }; /* INPUTS */ function onAddTag(tag) { alert("Added a tag: " + tag); } function onRemoveTag(tag) { alert("Removed a tag: " + tag); } function onChangeTag(input, tag) { alert("Changed a tag: " + tag); } //tags input function init_TagsInput() { if(typeof $.fn.tagsInput !== 'undefined'){ $('#tags_1').tagsInput({ width: 'auto' }); } }; /* SELECT2 */ function init_select2() { if( typeof (select2) === 'undefined'){ return; } console.log('init_toolbox'); $(".select2_single").select2({ placeholder: "Select a state", allowClear: true }); $(".select2_group").select2({}); $(".select2_multiple").select2({ maximumSelectionLength: 4, placeholder: "With Max Selection limit 4", allowClear: true }); }; /* WYSIWYG EDITOR */ function init_wysiwyg() { if( typeof ($.fn.wysiwyg) === 'undefined'){ return; } console.log('init_wysiwyg'); function init_ToolbarBootstrapBindings() { var fonts = ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier', 'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times', 'Times New Roman', 'Verdana' ], fontTarget = $('[title=Font]').siblings('.dropdown-menu'); $.each(fonts, function(idx, fontName) { fontTarget.append($('<li><a data-edit="fontName ' + fontName + '" style="font-family:\'' + fontName + '\'">' + fontName + '</a></li>')); }); $('a[title]').tooltip({ container: 'body' }); $('.dropdown-menu input').click(function() { return false; }) .change(function() { $(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle'); }) .keydown('esc', function() { this.value = ''; $(this).change(); }); $('[data-role=magic-overlay]').each(function() { var overlay = $(this), target = $(overlay.data('target')); overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width(target.outerWidth()).height(target.outerHeight()); }); if ("onwebkitspeechchange" in document.createElement("input")) { var editorOffset = $('#editor').offset(); $('.voiceBtn').css('position', 'absolute').offset({ top: editorOffset.top, left: editorOffset.left + $('#editor').innerWidth() - 35 }); } else { $('.voiceBtn').hide(); } } function showErrorAlert(reason, detail) { var msg = ''; if (reason === 'unsupported-file-type') { msg = "Unsupported format " + detail; } else { console.log("error uploading file", reason, detail); } $('<div class="alert"> <button type="button" class="close" data-dismiss="alert">&times;</button>' + '<strong>File upload error</strong> ' + msg + ' </div>').prependTo('#alerts'); } $('.editor-wrapper').each(function(){ var id = $(this).attr('id'); //editor-one $(this).wysiwyg({ toolbarSelector: '[data-target="#' + id + '"]', fileUploadError: showErrorAlert }); }); window.prettyPrint; prettyPrint(); }; /* CROPPER */ function init_cropper() { if( typeof ($.fn.cropper) === 'undefined'){ return; } console.log('init_cropper'); var $image = $('#image'); var $download = $('#download'); var $dataX = $('#dataX'); var $dataY = $('#dataY'); var $dataHeight = $('#dataHeight'); var $dataWidth = $('#dataWidth'); var $dataRotate = $('#dataRotate'); var $dataScaleX = $('#dataScaleX'); var $dataScaleY = $('#dataScaleY'); var options = { aspectRatio: 16 / 9, preview: '.img-preview', crop: function (e) { $dataX.val(Math.round(e.x)); $dataY.val(Math.round(e.y)); $dataHeight.val(Math.round(e.height)); $dataWidth.val(Math.round(e.width)); $dataRotate.val(e.rotate); $dataScaleX.val(e.scaleX); $dataScaleY.val(e.scaleY); } }; // Tooltip $('[data-toggle="tooltip"]').tooltip(); // Cropper $image.on({ 'build.cropper': function (e) { console.log(e.type); }, 'built.cropper': function (e) { console.log(e.type); }, 'cropstart.cropper': function (e) { console.log(e.type, e.action); }, 'cropmove.cropper': function (e) { console.log(e.type, e.action); }, 'cropend.cropper': function (e) { console.log(e.type, e.action); }, 'crop.cropper': function (e) { console.log(e.type, e.x, e.y, e.width, e.height, e.rotate, e.scaleX, e.scaleY); }, 'zoom.cropper': function (e) { console.log(e.type, e.ratio); } }).cropper(options); // Buttons if (!$.isFunction(document.createElement('canvas').getContext)) { $('button[data-method="getCroppedCanvas"]').prop('disabled', true); } if (typeof document.createElement('cropper').style.transition === 'undefined') { $('button[data-method="rotate"]').prop('disabled', true); $('button[data-method="scale"]').prop('disabled', true); } // Download if (typeof $download[0].download === 'undefined') { $download.addClass('disabled'); } // Options $('.docs-toggles').on('change', 'input', function () { var $this = $(this); var name = $this.attr('name'); var type = $this.prop('type'); var cropBoxData; var canvasData; if (!$image.data('cropper')) { return; } if (type === 'checkbox') { options[name] = $this.prop('checked'); cropBoxData = $image.cropper('getCropBoxData'); canvasData = $image.cropper('getCanvasData'); options.built = function () { $image.cropper('setCropBoxData', cropBoxData); $image.cropper('setCanvasData', canvasData); }; } else if (type === 'radio') { options[name] = $this.val(); } $image.cropper('destroy').cropper(options); }); // Methods $('.docs-buttons').on('click', '[data-method]', function () { var $this = $(this); var data = $this.data(); var $target; var result; if ($this.prop('disabled') || $this.hasClass('disabled')) { return; } if ($image.data('cropper') && data.method) { data = $.extend({}, data); // Clone a new one if (typeof data.target !== 'undefined') { $target = $(data.target); if (typeof data.option === 'undefined') { try { data.option = JSON.parse($target.val()); } catch (e) { console.log(e.message); } } } result = $image.cropper(data.method, data.option, data.secondOption); switch (data.method) { case 'scaleX': case 'scaleY': $(this).data('option', -data.option); break; case 'getCroppedCanvas': if (result) { // Bootstrap's Modal $('#getCroppedCanvasModal').modal().find('.modal-body').html(result); if (!$download.hasClass('disabled')) { $download.attr('href', result.toDataURL()); } } break; } if ($.isPlainObject(result) && $target) { try { $target.val(JSON.stringify(result)); } catch (e) { console.log(e.message); } } } }); // Keyboard $(document.body).on('keydown', function (e) { if (!$image.data('cropper') || this.scrollTop > 300) { return; } switch (e.which) { case 37: e.preventDefault(); $image.cropper('move', -1, 0); break; case 38: e.preventDefault(); $image.cropper('move', 0, -1); break; case 39: e.preventDefault(); $image.cropper('move', 1, 0); break; case 40: e.preventDefault(); $image.cropper('move', 0, 1); break; } }); // Import image var $inputImage = $('#inputImage'); var URL = window.URL || window.webkitURL; var blobURL; if (URL) { $inputImage.change(function () { var files = this.files; var file; if (!$image.data('cropper')) { return; } if (files && files.length) { file = files[0]; if (/^image\/\w+$/.test(file.type)) { blobURL = URL.createObjectURL(file); $image.one('built.cropper', function () { // Revoke when load complete URL.revokeObjectURL(blobURL); }).cropper('reset').cropper('replace', blobURL); $inputImage.val(''); } else { window.alert('Please choose an image file.'); } } }); } else { $inputImage.prop('disabled', true).parent().addClass('disabled'); } }; /* CROPPER --- end */ /* KNOB */ function init_knob() { if( typeof ($.fn.knob) === 'undefined'){ return; } console.log('init_knob'); $(".knob").knob({ change: function(value) { //console.log("change : " + value); }, release: function(value) { //console.log(this.$.attr('value')); console.log("release : " + value); }, cancel: function() { console.log("cancel : ", this); }, /*format : function (value) { return value + '%'; },*/ draw: function() { // "tron" case if (this.$.data('skin') == 'tron') { this.cursorExt = 0.3; var a = this.arc(this.cv) // Arc , pa // Previous arc , r = 1; this.g.lineWidth = this.lineWidth; if (this.o.displayPrevious) { pa = this.arc(this.v); this.g.beginPath(); this.g.strokeStyle = this.pColor; this.g.arc(this.xy, this.xy, this.radius - this.lineWidth, pa.s, pa.e, pa.d); this.g.stroke(); } this.g.beginPath(); this.g.strokeStyle = r ? this.o.fgColor : this.fgColor; this.g.arc(this.xy, this.xy, this.radius - this.lineWidth, a.s, a.e, a.d); this.g.stroke(); this.g.lineWidth = 2; this.g.beginPath(); this.g.strokeStyle = this.o.fgColor; this.g.arc(this.xy, this.xy, this.radius - this.lineWidth + 1 + this.lineWidth * 2 / 3, 0, 2 * Math.PI, false); this.g.stroke(); return false; } } }); // Example of infinite knob, iPod click wheel var v, up = 0, down = 0, i = 0, $idir = $("div.idir"), $ival = $("div.ival"), incr = function() { i++; $idir.show().html("+").fadeOut(); $ival.html(i); }, decr = function() { i--; $idir.show().html("-").fadeOut(); $ival.html(i); }; $("input.infinite").knob({ min: 0, max: 20, stopper: false, change: function() { if (v > this.cv) { if (up) { decr(); up = 0; } else { up = 1; down = 0; } } else { if (v < this.cv) { if (down) { incr(); down = 0; } else { down = 1; up = 0; } } } v = this.cv; } }); }; /* INPUT MASK */ function init_InputMask() { if( typeof ($.fn.inputmask) === 'undefined'){ return; } console.log('init_InputMask'); $(":input").inputmask(); }; /* COLOR PICKER */ function init_ColorPicker() { if( typeof ($.fn.colorpicker) === 'undefined'){ return; } console.log('init_ColorPicker'); $('.demo1').colorpicker(); $('.demo2').colorpicker(); $('#demo_forceformat').colorpicker({ format: 'rgba', horizontal: true }); $('#demo_forceformat3').colorpicker({ format: 'rgba', }); $('.demo-auto').colorpicker(); }; /* ION RANGE SLIDER */ function init_IonRangeSlider() { if( typeof ($.fn.ionRangeSlider) === 'undefined'){ return; } console.log('init_IonRangeSlider'); $("#range_27").ionRangeSlider({ type: "double", min: 1000000, max: 2000000, grid: true, force_edges: true }); $("#range").ionRangeSlider({ hide_min_max: true, keyboard: true, min: 0, max: 5000, from: 1000, to: 4000, type: 'double', step: 1, prefix: "$", grid: true }); $("#range_25").ionRangeSlider({ type: "double", min: 1000000, max: 2000000, grid: true }); $("#range_26").ionRangeSlider({ type: "double", min: 0, max: 10000, step: 500, grid: true, grid_snap: true }); $("#range_31").ionRangeSlider({ type: "double", min: 0, max: 100, from: 30, to: 70, from_fixed: true }); $(".range_min_max").ionRangeSlider({ type: "double", min: 0, max: 100, from: 30, to: 70, max_interval: 50 }); $(".range_time24").ionRangeSlider({ min: +moment().subtract(12, "hours").format("X"), max: +moment().format("X"), from: +moment().subtract(6, "hours").format("X"), grid: true, force_edges: true, prettify: function(num) { var m = moment(num, "X"); return m.format("Do MMMM, HH:mm"); } }); }; /* DATERANGEPICKER */ function init_daterangepicker() { if( typeof ($.fn.daterangepicker) === 'undefined'){ return; } console.log('init_daterangepicker'); var cb = function(start, end, label) { console.log(start.toISOString(), end.toISOString(), label); $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); }; var optionSet1 = { startDate: moment().subtract(29, 'days'), endDate: moment(), minDate: '01/01/2012', maxDate: '12/31/2015', dateLimit: { days: 60 }, showDropdowns: true, showWeekNumbers: true, timePicker: false, timePickerIncrement: 1, timePicker12Hour: true, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] }, opens: 'left', buttonClasses: ['btn btn-default'], applyClass: 'btn-small btn-primary', cancelClass: 'btn-small', format: 'MM/DD/YYYY', separator: ' to ', locale: { applyLabel: 'Submit', cancelLabel: 'Clear', fromLabel: 'From', toLabel: 'To', customRangeLabel: 'Custom', daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], firstDay: 1 } }; $('#reportrange span').html(moment().subtract(29, 'days').format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY')); $('#reportrange').daterangepicker(optionSet1, cb); $('#reportrange').on('show.daterangepicker', function() { console.log("show event fired"); }); $('#reportrange').on('hide.daterangepicker', function() { console.log("hide event fired"); }); $('#reportrange').on('apply.daterangepicker', function(ev, picker) { console.log("apply event fired, start/end dates are " + picker.startDate.format('MMMM D, YYYY') + " to " + picker.endDate.format('MMMM D, YYYY')); }); $('#reportrange').on('cancel.daterangepicker', function(ev, picker) { console.log("cancel event fired"); }); $('#options1').click(function() { $('#reportrange').data('daterangepicker').setOptions(optionSet1, cb); }); $('#options2').click(function() { $('#reportrange').data('daterangepicker').setOptions(optionSet2, cb); }); $('#destroy').click(function() { $('#reportrange').data('daterangepicker').remove(); }); } function init_daterangepicker_right() { if( typeof ($.fn.daterangepicker) === 'undefined'){ return; } console.log('init_daterangepicker_right'); var cb = function(start, end, label) { console.log(start.toISOString(), end.toISOString(), label); $('#reportrange_right span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); }; var optionSet1 = { startDate: moment().subtract(29, 'days'), endDate: moment(), minDate: '01/01/2012', maxDate: '12/31/2020', dateLimit: { days: 60 }, showDropdowns: true, showWeekNumbers: true, timePicker: false, timePickerIncrement: 1, timePicker12Hour: true, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] }, opens: 'right', buttonClasses: ['btn btn-default'], applyClass: 'btn-small btn-primary', cancelClass: 'btn-small', format: 'MM/DD/YYYY', separator: ' to ', locale: { applyLabel: 'Submit', cancelLabel: 'Clear', fromLabel: 'From', toLabel: 'To', customRangeLabel: 'Custom', daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], firstDay: 1 } }; $('#reportrange_right span').html(moment().subtract(29, 'days').format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY')); $('#reportrange_right').daterangepicker(optionSet1, cb); $('#reportrange_right').on('show.daterangepicker', function() { console.log("show event fired"); }); $('#reportrange_right').on('hide.daterangepicker', function() { console.log("hide event fired"); }); $('#reportrange_right').on('apply.daterangepicker', function(ev, picker) { console.log("apply event fired, start/end dates are " + picker.startDate.format('MMMM D, YYYY') + " to " + picker.endDate.format('MMMM D, YYYY')); }); $('#reportrange_right').on('cancel.daterangepicker', function(ev, picker) { console.log("cancel event fired"); }); $('#options1').click(function() { $('#reportrange_right').data('daterangepicker').setOptions(optionSet1, cb); }); $('#options2').click(function() { $('#reportrange_right').data('daterangepicker').setOptions(optionSet2, cb); }); $('#destroy').click(function() { $('#reportrange_right').data('daterangepicker').remove(); }); } function init_daterangepicker_single_call() { if( typeof ($.fn.daterangepicker) === 'undefined'){ return; } console.log('init_daterangepicker_single_call'); $('#single_cal1').daterangepicker({ singleDatePicker: true, singleClasses: "picker_1" }, function(start, end, label) { console.log(start.toISOString(), end.toISOString(), label); }); $('#single_cal2').daterangepicker({ singleDatePicker: true, singleClasses: "picker_2" }, function(start, end, label) { console.log(start.toISOString(), end.toISOString(), label); }); $('#single_cal3').daterangepicker({ singleDatePicker: true, singleClasses: "picker_3" }, function(start, end, label) { console.log(start.toISOString(), end.toISOString(), label); }); $('#single_cal4').daterangepicker({ singleDatePicker: true, singleClasses: "picker_4" }, function(start, end, label) { console.log(start.toISOString(), end.toISOString(), label); }); } function init_daterangepicker_reservation() { if( typeof ($.fn.daterangepicker) === 'undefined'){ return; } console.log('init_daterangepicker_reservation'); $('#reservation').daterangepicker(null, function(start, end, label) { console.log(start.toISOString(), end.toISOString(), label); }); $('#reservation-time').daterangepicker({ timePicker: true, timePickerIncrement: 30, locale: { format: 'MM/DD/YYYY h:mm A' } }); } /* SMART WIZARD */ function init_SmartWizard() { if( typeof ($.fn.smartWizard) === 'undefined'){ return; } console.log('init_SmartWizard'); $('#wizard').smartWizard(); $('#wizard_verticle').smartWizard({ transitionEffect: 'slide' }); $('.buttonNext').addClass('btn btn-success'); $('.buttonPrevious').addClass('btn btn-primary'); $('.buttonFinish').addClass('btn btn-default'); }; /* VALIDATOR */ function init_validator () { if( typeof (validator) === 'undefined'){ return; } console.log('init_validator'); // initialize the validator function validator.message.date = 'not a real date'; // validate a field on "blur" event, a 'select' on 'change' event & a '.reuired' classed multifield on 'keyup': $('form') .on('blur', 'input[required], input.optional, select.required', validator.checkField) .on('change', 'select.required', validator.checkField) .on('keypress', 'input[required][pattern]', validator.keypress); $('.multi.required').on('keyup blur', 'input', function() { validator.checkField.apply($(this).siblings().last()[0]); }); $('form').submit(function(e) { e.preventDefault(); var submit = true; // evaluate the form using generic validaing if (!validator.checkAll($(this))) { submit = false; } if (submit) this.submit(); return false; }); }; /* PNotify */ function init_PNotify() { if( typeof (PNotify) === 'undefined'){ return; } console.log('init_PNotify'); new PNotify({ title: "PNotify", type: "info", text: "Welcome. Try hovering over me. You can click things behind me, because I'm non-blocking.", nonblock: { nonblock: true }, addclass: 'dark', styling: 'bootstrap3', hide: false, before_close: function(PNotify) { PNotify.update({ title: PNotify.options.title + " - Enjoy your Stay", before_close: null }); PNotify.queueRemove(); return false; } }); }; /* CUSTOM NOTIFICATION */ function init_CustomNotification() { console.log('run_customtabs'); if( typeof (CustomTabs) === 'undefined'){ return; } console.log('init_CustomTabs'); var cnt = 10; TabbedNotification = function(options) { var message = "<div id='ntf" + cnt + "' class='text alert-" + options.type + "' style='display:none'><h2><i class='fa fa-bell'></i> " + options.title + "</h2><div class='close'><a href='javascript:;' class='notification_close'><i class='fa fa-close'></i></a></div><p>" + options.text + "</p></div>"; if (!document.getElementById('custom_notifications')) { alert('doesnt exists'); } else { $('#custom_notifications ul.notifications').append("<li><a id='ntlink" + cnt + "' class='alert-" + options.type + "' href='#ntf" + cnt + "'><i class='fa fa-bell animated shake'></i></a></li>"); $('#custom_notifications #notif-group').append(message); cnt++; CustomTabs(options); } }; CustomTabs = function(options) { $('.tabbed_notifications > div').hide(); $('.tabbed_notifications > div:first-of-type').show(); $('#custom_notifications').removeClass('dsp_none'); $('.notifications a').click(function(e) { e.preventDefault(); var $this = $(this), tabbed_notifications = '#' + $this.parents('.notifications').data('tabbed_notifications'), others = $this.closest('li').siblings().children('a'), target = $this.attr('href'); others.removeClass('active'); $this.addClass('active'); $(tabbed_notifications).children('div').hide(); $(target).show(); }); }; CustomTabs(); var tabid = idname = ''; $(document).on('click', '.notification_close', function(e) { idname = $(this).parent().parent().attr("id"); tabid = idname.substr(-2); $('#ntf' + tabid).remove(); $('#ntlink' + tabid).parent().remove(); $('.notifications a').first().addClass('active'); $('#notif-group div').first().css('display', 'block'); }); }; /* EASYPIECHART */ function init_EasyPieChart() { if( typeof ($.fn.easyPieChart) === 'undefined'){ return; } console.log('init_EasyPieChart'); $('.chart').easyPieChart({ easing: 'easeOutElastic', delay: 3000, barColor: '#26B99A', trackColor: '#fff', scaleColor: false, lineWidth: 20, trackWidth: 16, lineCap: 'butt', onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); var chart = window.chart = $('.chart').data('easyPieChart'); $('.js_update').on('click', function() { chart.update(Math.random() * 200 - 100); }); //hover and retain popover when on popover content var originalLeave = $.fn.popover.Constructor.prototype.leave; $.fn.popover.Constructor.prototype.leave = function(obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type); var container, timeout; originalLeave.call(this, obj); if (obj.currentTarget) { container = $(obj.currentTarget).siblings('.popover'); timeout = self.timeout; container.one('mouseenter', function() { //We entered the actual popover – call off the dogs clearTimeout(timeout); //Let's monitor popover content instead container.one('mouseleave', function() { $.fn.popover.Constructor.prototype.leave.call(self, self); }); }); } }; $('body').popover({ selector: '[data-popover]', trigger: 'click hover', delay: { show: 50, hide: 400 } }); }; function init_charts() { console.log('run_charts typeof [' + typeof (Chart) + ']'); if( typeof (Chart) === 'undefined'){ return; } console.log('init_charts'); Chart.defaults.global.legend = { enabled: false }; if ($('#canvas_line').length ){ var canvas_line_00 = new Chart(document.getElementById("canvas_line"), { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", backgroundColor: "rgba(38, 185, 154, 0.31)", borderColor: "rgba(38, 185, 154, 0.7)", pointBorderColor: "rgba(38, 185, 154, 0.7)", pointBackgroundColor: "rgba(38, 185, 154, 0.7)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(220,220,220,1)", pointBorderWidth: 1, data: [31, 74, 6, 39, 20, 85, 7] }, { label: "My Second dataset", backgroundColor: "rgba(3, 88, 106, 0.3)", borderColor: "rgba(3, 88, 106, 0.70)", pointBorderColor: "rgba(3, 88, 106, 0.70)", pointBackgroundColor: "rgba(3, 88, 106, 0.70)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(151,187,205,1)", pointBorderWidth: 1, data: [82, 23, 66, 9, 99, 4, 2] }] }, }); } if ($('#canvas_line1').length ){ var canvas_line_01 = new Chart(document.getElementById("canvas_line1"), { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", backgroundColor: "rgba(38, 185, 154, 0.31)", borderColor: "rgba(38, 185, 154, 0.7)", pointBorderColor: "rgba(38, 185, 154, 0.7)", pointBackgroundColor: "rgba(38, 185, 154, 0.7)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(220,220,220,1)", pointBorderWidth: 1, data: [31, 74, 6, 39, 20, 85, 7] }, { label: "My Second dataset", backgroundColor: "rgba(3, 88, 106, 0.3)", borderColor: "rgba(3, 88, 106, 0.70)", pointBorderColor: "rgba(3, 88, 106, 0.70)", pointBackgroundColor: "rgba(3, 88, 106, 0.70)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(151,187,205,1)", pointBorderWidth: 1, data: [82, 23, 66, 9, 99, 4, 2] }] }, }); } if ($('#canvas_line2').length ){ var canvas_line_02 = new Chart(document.getElementById("canvas_line2"), { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", backgroundColor: "rgba(38, 185, 154, 0.31)", borderColor: "rgba(38, 185, 154, 0.7)", pointBorderColor: "rgba(38, 185, 154, 0.7)", pointBackgroundColor: "rgba(38, 185, 154, 0.7)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(220,220,220,1)", pointBorderWidth: 1, data: [31, 74, 6, 39, 20, 85, 7] }, { label: "My Second dataset", backgroundColor: "rgba(3, 88, 106, 0.3)", borderColor: "rgba(3, 88, 106, 0.70)", pointBorderColor: "rgba(3, 88, 106, 0.70)", pointBackgroundColor: "rgba(3, 88, 106, 0.70)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(151,187,205,1)", pointBorderWidth: 1, data: [82, 23, 66, 9, 99, 4, 2] }] }, }); } if ($('#canvas_line3').length ){ var canvas_line_03 = new Chart(document.getElementById("canvas_line3"), { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", backgroundColor: "rgba(38, 185, 154, 0.31)", borderColor: "rgba(38, 185, 154, 0.7)", pointBorderColor: "rgba(38, 185, 154, 0.7)", pointBackgroundColor: "rgba(38, 185, 154, 0.7)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(220,220,220,1)", pointBorderWidth: 1, data: [31, 74, 6, 39, 20, 85, 7] }, { label: "My Second dataset", backgroundColor: "rgba(3, 88, 106, 0.3)", borderColor: "rgba(3, 88, 106, 0.70)", pointBorderColor: "rgba(3, 88, 106, 0.70)", pointBackgroundColor: "rgba(3, 88, 106, 0.70)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(151,187,205,1)", pointBorderWidth: 1, data: [82, 23, 66, 9, 99, 4, 2] }] }, }); } if ($('#canvas_line4').length ){ var canvas_line_04 = new Chart(document.getElementById("canvas_line4"), { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", backgroundColor: "rgba(38, 185, 154, 0.31)", borderColor: "rgba(38, 185, 154, 0.7)", pointBorderColor: "rgba(38, 185, 154, 0.7)", pointBackgroundColor: "rgba(38, 185, 154, 0.7)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(220,220,220,1)", pointBorderWidth: 1, data: [31, 74, 6, 39, 20, 85, 7] }, { label: "My Second dataset", backgroundColor: "rgba(3, 88, 106, 0.3)", borderColor: "rgba(3, 88, 106, 0.70)", pointBorderColor: "rgba(3, 88, 106, 0.70)", pointBackgroundColor: "rgba(3, 88, 106, 0.70)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(151,187,205,1)", pointBorderWidth: 1, data: [82, 23, 66, 9, 99, 4, 2] }] }, }); } // Line chart if ($('#lineChart').length ){ var ctx = document.getElementById("lineChart"); var lineChart = new Chart(ctx, { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", backgroundColor: "rgba(38, 185, 154, 0.31)", borderColor: "rgba(38, 185, 154, 0.7)", pointBorderColor: "rgba(38, 185, 154, 0.7)", pointBackgroundColor: "rgba(38, 185, 154, 0.7)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(220,220,220,1)", pointBorderWidth: 1, data: [31, 74, 6, 39, 20, 85, 7] }, { label: "My Second dataset", backgroundColor: "rgba(3, 88, 106, 0.3)", borderColor: "rgba(3, 88, 106, 0.70)", pointBorderColor: "rgba(3, 88, 106, 0.70)", pointBackgroundColor: "rgba(3, 88, 106, 0.70)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(151,187,205,1)", pointBorderWidth: 1, data: [82, 23, 66, 9, 99, 4, 2] }] }, }); } // Bar chart if ($('#mybarChart').length ){ var ctx = document.getElementById("mybarChart"); var mybarChart = new Chart(ctx, { type: 'bar', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: '# of Votes', backgroundColor: "#26B99A", data: [51, 30, 40, 28, 92, 50, 45] }, { label: '# of Votes', backgroundColor: "#03586A", data: [41, 56, 25, 48, 72, 34, 12] }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); } // Doughnut chart if ($('#canvasDoughnut').length ){ var ctx = document.getElementById("canvasDoughnut"); var data = { labels: [ "Dark Grey", "Purple Color", "Gray Color", "Green Color", "Blue Color" ], datasets: [{ data: [120, 50, 140, 180, 100], backgroundColor: [ "#455C73", "#9B59B6", "#BDC3C7", "#26B99A", "#3498DB" ], hoverBackgroundColor: [ "#34495E", "#B370CF", "#CFD4D8", "#36CAAB", "#49A9EA" ] }] }; var canvasDoughnut = new Chart(ctx, { type: 'doughnut', tooltipFillColor: "rgba(51, 51, 51, 0.55)", data: data }); } // Radar chart if ($('#canvasRadar').length ){ var ctx = document.getElementById("canvasRadar"); var data = { labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"], datasets: [{ label: "My First dataset", backgroundColor: "rgba(3, 88, 106, 0.2)", borderColor: "rgba(3, 88, 106, 0.80)", pointBorderColor: "rgba(3, 88, 106, 0.80)", pointBackgroundColor: "rgba(3, 88, 106, 0.80)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(220,220,220,1)", data: [65, 59, 90, 81, 56, 55, 40] }, { label: "My Second dataset", backgroundColor: "rgba(38, 185, 154, 0.2)", borderColor: "rgba(38, 185, 154, 0.85)", pointColor: "rgba(38, 185, 154, 0.85)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(151,187,205,1)", data: [28, 48, 40, 19, 96, 27, 100] }] }; var canvasRadar = new Chart(ctx, { type: 'radar', data: data, }); } // Pie chart if ($('#pieChart').length ){ var ctx = document.getElementById("pieChart"); var data = { datasets: [{ data: [120, 50, 140, 180, 100], backgroundColor: [ "#455C73", "#9B59B6", "#BDC3C7", "#26B99A", "#3498DB" ], label: 'My dataset' // for legend }], labels: [ "Dark Gray", "Purple", "Gray", "Green", "Blue" ] }; var pieChart = new Chart(ctx, { data: data, type: 'pie', otpions: { legend: false } }); } // PolarArea chart if ($('#polarArea').length ){ var ctx = document.getElementById("polarArea"); var data = { datasets: [{ data: [120, 50, 140, 180, 100], backgroundColor: [ "#455C73", "#9B59B6", "#BDC3C7", "#26B99A", "#3498DB" ], label: 'My dataset' }], labels: [ "Dark Gray", "Purple", "Gray", "Green", "Blue" ] }; var polarArea = new Chart(ctx, { data: data, type: 'polarArea', options: { scale: { ticks: { beginAtZero: true } } } }); } } /* COMPOSE */ function init_compose() { if( typeof ($.fn.slideToggle) === 'undefined'){ return; } console.log('init_compose'); $('#compose, .compose-close').click(function(){ $('.compose').slideToggle(); }); }; /* CALENDAR */ function init_calendar() { if( typeof ($.fn.fullCalendar) === 'undefined'){ return; } console.log('init_calendar'); var date = new Date(), d = date.getDate(), m = date.getMonth(), y = date.getFullYear(), started, categoryClass; var calendar = $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay,listMonth' }, selectable: true, selectHelper: true, select: function(start, end, allDay) { $('#fc_create').click(); started = start; ended = end; $(".antosubmit").on("click", function() { var title = $("#title").val(); if (end) { ended = end; } categoryClass = $("#event_type").val(); if (title) { calendar.fullCalendar('renderEvent', { title: title, start: started, end: end, allDay: allDay }, true // make the event "stick" ); } $('#title').val(''); calendar.fullCalendar('unselect'); $('.antoclose').click(); return false; }); }, eventClick: function(calEvent, jsEvent, view) { $('#fc_edit').click(); $('#title2').val(calEvent.title); categoryClass = $("#event_type").val(); $(".antosubmit2").on("click", function() { calEvent.title = $("#title2").val(); calendar.fullCalendar('updateEvent', calEvent); $('.antoclose2').click(); }); calendar.fullCalendar('unselect'); }, editable: true, events: [{ title: 'All Day Event', start: new Date(y, m, 1) }, { title: 'Long Event', start: new Date(y, m, d - 5), end: new Date(y, m, d - 2) }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), allDay: false }, { title: 'Lunch', start: new Date(y, m, d + 14, 12, 0), end: new Date(y, m, d, 14, 0), allDay: false }, { title: 'Birthday Party', start: new Date(y, m, d + 1, 19, 0), end: new Date(y, m, d + 1, 22, 30), allDay: false }, { title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://google.com/' }] }); }; /* DATA TABLES */ function init_DataTables() { console.log('run_datatables'); if( typeof ($.fn.DataTable) === 'undefined'){ return; } console.log('init_DataTables'); var handleDataTableButtons = function() { if ($("#datatable-buttons").length) { $("#datatable-buttons").DataTable({ dom: "Bfrtip", buttons: [ { extend: "copy", className: "btn-sm" }, { extend: "csv", className: "btn-sm" }, { extend: "excel", className: "btn-sm" }, { extend: "pdfHtml5", className: "btn-sm" }, { extend: "print", className: "btn-sm" }, ], responsive: true }); } }; TableManageButtons = function() { "use strict"; return { init: function() { handleDataTableButtons(); } }; }(); $('#datatable').dataTable(); $('#datatable-keytable').DataTable({ keys: true }); $('#datatable-responsive').DataTable(); $('#datatable-scroller').DataTable({ ajax: "js/datatables/json/scroller-demo.json", deferRender: true, scrollY: 380, scrollCollapse: true, scroller: true }); $('#datatable-fixed-header').DataTable({ fixedHeader: true }); var $datatable = $('#datatable-checkbox'); $datatable.dataTable({ 'order': [[ 1, 'asc' ]], 'columnDefs': [ { orderable: false, targets: [0] } ] }); $datatable.on('draw.dt', function() { $('checkbox input').iCheck({ checkboxClass: 'icheckbox_flat-green' }); }); TableManageButtons.init(); }; /* CHART - MORRIS */ function init_morris_charts() { if( typeof (Morris) === 'undefined'){ return; } console.log('init_morris_charts'); if ($('#graph_bar').length){ Morris.Bar({ element: 'graph_bar', data: [ {device: 'iPhone 4', geekbench: 380}, {device: 'iPhone 4S', geekbench: 655}, {device: 'iPhone 3GS', geekbench: 275}, {device: 'iPhone 5', geekbench: 1571}, {device: 'iPhone 5S', geekbench: 655}, {device: 'iPhone 6', geekbench: 2154}, {device: 'iPhone 6 Plus', geekbench: 1144}, {device: 'iPhone 6S', geekbench: 2371}, {device: 'iPhone 6S Plus', geekbench: 1471}, {device: 'Other', geekbench: 1371} ], xkey: 'device', ykeys: ['geekbench'], labels: ['Geekbench'], barRatio: 0.4, barColors: ['#26B99A', '#34495E', '#ACADAC', '#3498DB'], xLabelAngle: 35, hideHover: 'auto', resize: true }); } if ($('#graph_bar_group').length ){ Morris.Bar({ element: 'graph_bar_group', data: [ {"period": "2016-10-01", "licensed": 807, "sorned": 660}, {"period": "2016-09-30", "licensed": 1251, "sorned": 729}, {"period": "2016-09-29", "licensed": 1769, "sorned": 1018}, {"period": "2016-09-20", "licensed": 2246, "sorned": 1461}, {"period": "2016-09-19", "licensed": 2657, "sorned": 1967}, {"period": "2016-09-18", "licensed": 3148, "sorned": 2627}, {"period": "2016-09-17", "licensed": 3471, "sorned": 3740}, {"period": "2016-09-16", "licensed": 2871, "sorned": 2216}, {"period": "2016-09-15", "licensed": 2401, "sorned": 1656}, {"period": "2016-09-10", "licensed": 2115, "sorned": 1022} ], xkey: 'period', barColors: ['#26B99A', '#34495E', '#ACADAC', '#3498DB'], ykeys: ['licensed', 'sorned'], labels: ['Licensed', 'SORN'], hideHover: 'auto', xLabelAngle: 60, resize: true }); } if ($('#graphx').length ){ Morris.Bar({ element: 'graphx', data: [ {x: '2015 Q1', y: 2, z: 3, a: 4}, {x: '2015 Q2', y: 3, z: 5, a: 6}, {x: '2015 Q3', y: 4, z: 3, a: 2}, {x: '2015 Q4', y: 2, z: 4, a: 5} ], xkey: 'x', ykeys: ['y', 'z', 'a'], barColors: ['#26B99A', '#34495E', '#ACADAC', '#3498DB'], hideHover: 'auto', labels: ['Y', 'Z', 'A'], resize: true }).on('click', function (i, row) { console.log(i, row); }); } if ($('#graph_area').length ){ Morris.Area({ element: 'graph_area', data: [ {period: '2014 Q1', iphone: 2666, ipad: null, itouch: 2647}, {period: '2014 Q2', iphone: 2778, ipad: 2294, itouch: 2441}, {period: '2014 Q3', iphone: 4912, ipad: 1969, itouch: 2501}, {period: '2014 Q4', iphone: 3767, ipad: 3597, itouch: 5689}, {period: '2015 Q1', iphone: 6810, ipad: 1914, itouch: 2293}, {period: '2015 Q2', iphone: 5670, ipad: 4293, itouch: 1881}, {period: '2015 Q3', iphone: 4820, ipad: 3795, itouch: 1588}, {period: '2015 Q4', iphone: 15073, ipad: 5967, itouch: 5175}, {period: '2016 Q1', iphone: 10687, ipad: 4460, itouch: 2028}, {period: '2016 Q2', iphone: 8432, ipad: 5713, itouch: 1791} ], xkey: 'period', ykeys: ['iphone', 'ipad', 'itouch'], lineColors: ['#26B99A', '#34495E', '#ACADAC', '#3498DB'], labels: ['iPhone', 'iPad', 'iPod Touch'], pointSize: 2, hideHover: 'auto', resize: true }); } if ($('#graph_donut').length ){ Morris.Donut({ element: 'graph_donut', data: [ {label: 'Jam', value: 25}, {label: 'Frosted', value: 40}, {label: 'Custard', value: 25}, {label: 'Sugar', value: 10} ], colors: ['#26B99A', '#34495E', '#ACADAC', '#3498DB'], formatter: function (y) { return y + "%"; }, resize: true }); } if ($('#graph_line').length ){ Morris.Line({ element: 'graph_line', xkey: 'year', ykeys: ['value'], labels: ['Value'], hideHover: 'auto', lineColors: ['#26B99A', '#34495E', '#ACADAC', '#3498DB'], data: [ {year: '2012', value: 20}, {year: '2013', value: 10}, {year: '2014', value: 5}, {year: '2015', value: 5}, {year: '2016', value: 20} ], resize: true }); $MENU_TOGGLE.on('click', function() { $(window).resize(); }); } }; /* ECHRTS */ function init_echarts() { if( typeof (echarts) === 'undefined'){ return; } console.log('init_echarts'); var theme = { color: [ '#26B99A', '#34495E', '#BDC3C7', '#3498DB', '#9B59B6', '#8abb6f', '#759c6a', '#bfd3b7' ], title: { itemGap: 8, textStyle: { fontWeight: 'normal', color: '#408829' } }, dataRange: { color: ['#1f610a', '#97b58d'] }, toolbox: { color: ['#408829', '#408829', '#408829', '#408829'] }, tooltip: { backgroundColor: 'rgba(0,0,0,0.5)', axisPointer: { type: 'line', lineStyle: { color: '#408829', type: 'dashed' }, crossStyle: { color: '#408829' }, shadowStyle: { color: 'rgba(200,200,200,0.3)' } } }, dataZoom: { dataBackgroundColor: '#eee', fillerColor: 'rgba(64,136,41,0.2)', handleColor: '#408829' }, grid: { borderWidth: 0 }, categoryAxis: { axisLine: { lineStyle: { color: '#408829' } }, splitLine: { lineStyle: { color: ['#eee'] } } }, valueAxis: { axisLine: { lineStyle: { color: '#408829' } }, splitArea: { show: true, areaStyle: { color: ['rgba(250,250,250,0.1)', 'rgba(200,200,200,0.1)'] } }, splitLine: { lineStyle: { color: ['#eee'] } } }, timeline: { lineStyle: { color: '#408829' }, controlStyle: { normal: {color: '#408829'}, emphasis: {color: '#408829'} } }, k: { itemStyle: { normal: { color: '#68a54a', color0: '#a9cba2', lineStyle: { width: 1, color: '#408829', color0: '#86b379' } } } }, map: { itemStyle: { normal: { areaStyle: { color: '#ddd' }, label: { textStyle: { color: '#c12e34' } } }, emphasis: { areaStyle: { color: '#99d2dd' }, label: { textStyle: { color: '#c12e34' } } } } }, force: { itemStyle: { normal: { linkStyle: { strokeColor: '#408829' } } } }, chord: { padding: 4, itemStyle: { normal: { lineStyle: { width: 1, color: 'rgba(128, 128, 128, 0.5)' }, chordStyle: { lineStyle: { width: 1, color: 'rgba(128, 128, 128, 0.5)' } } }, emphasis: { lineStyle: { width: 1, color: 'rgba(128, 128, 128, 0.5)' }, chordStyle: { lineStyle: { width: 1, color: 'rgba(128, 128, 128, 0.5)' } } } } }, gauge: { startAngle: 225, endAngle: -45, axisLine: { show: true, lineStyle: { color: [[0.2, '#86b379'], [0.8, '#68a54a'], [1, '#408829']], width: 8 } }, axisTick: { splitNumber: 10, length: 12, lineStyle: { color: 'auto' } }, axisLabel: { textStyle: { color: 'auto' } }, splitLine: { length: 18, lineStyle: { color: 'auto' } }, pointer: { length: '90%', color: 'auto' }, title: { textStyle: { color: '#333' } }, detail: { textStyle: { color: 'auto' } } }, textStyle: { fontFamily: 'Arial, Verdana, sans-serif' } }; //echart Bar if ($('#mainb').length ){ var echartBar = echarts.init(document.getElementById('mainb'), theme); echartBar.setOption({ title: { text: 'Graph title', subtext: 'Graph Sub-text' }, tooltip: { trigger: 'axis' }, legend: { data: ['sales', 'purchases'] }, toolbox: { show: false }, calculable: false, xAxis: [{ type: 'category', data: ['1?', '2?', '3?', '4?', '5?', '6?', '7?', '8?', '9?', '10?', '11?', '12?'] }], yAxis: [{ type: 'value' }], series: [{ name: 'sales', type: 'bar', data: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3], markPoint: { data: [{ type: 'max', name: '???' }, { type: 'min', name: '???' }] }, markLine: { data: [{ type: 'average', name: '???' }] } }, { name: 'purchases', type: 'bar', data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3], markPoint: { data: [{ name: 'sales', value: 182.2, xAxis: 7, yAxis: 183, }, { name: 'purchases', value: 2.3, xAxis: 11, yAxis: 3 }] }, markLine: { data: [{ type: 'average', name: '???' }] } }] }); } //echart Radar if ($('#echart_sonar').length ){ var echartRadar = echarts.init(document.getElementById('echart_sonar'), theme); echartRadar.setOption({ title: { text: 'Budget vs spending', subtext: 'Subtitle' }, tooltip: { trigger: 'item' }, legend: { orient: 'vertical', x: 'right', y: 'bottom', data: ['Allocated Budget', 'Actual Spending'] }, toolbox: { show: true, feature: { restore: { show: true, title: "Restore" }, saveAsImage: { show: true, title: "Save Image" } } }, polar: [{ indicator: [{ text: 'Sales', max: 6000 }, { text: 'Administration', max: 16000 }, { text: 'Information Techology', max: 30000 }, { text: 'Customer Support', max: 38000 }, { text: 'Development', max: 52000 }, { text: 'Marketing', max: 25000 }] }], calculable: true, series: [{ name: 'Budget vs spending', type: 'radar', data: [{ value: [4300, 10000, 28000, 35000, 50000, 19000], name: 'Allocated Budget' }, { value: [5000, 14000, 28000, 31000, 42000, 21000], name: 'Actual Spending' }] }] }); } //echart Funnel if ($('#echart_pyramid').length ){ var echartFunnel = echarts.init(document.getElementById('echart_pyramid'), theme); echartFunnel.setOption({ title: { text: 'Echart Pyramid Graph', subtext: 'Subtitle' }, tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c}%" }, toolbox: { show: true, feature: { restore: { show: true, title: "Restore" }, saveAsImage: { show: true, title: "Save Image" } } }, legend: { data: ['Something #1', 'Something #2', 'Something #3', 'Something #4', 'Something #5'], orient: 'vertical', x: 'left', y: 'bottom' }, calculable: true, series: [{ name: '漏斗图', type: 'funnel', width: '40%', data: [{ value: 60, name: 'Something #1' }, { value: 40, name: 'Something #2' }, { value: 20, name: 'Something #3' }, { value: 80, name: 'Something #4' }, { value: 100, name: 'Something #5' }] }] }); } //echart Gauge if ($('#echart_gauge').length ){ var echartGauge = echarts.init(document.getElementById('echart_gauge'), theme); echartGauge.setOption({ tooltip: { formatter: "{a} <br/>{b} : {c}%" }, toolbox: { show: true, feature: { restore: { show: true, title: "Restore" }, saveAsImage: { show: true, title: "Save Image" } } }, series: [{ name: 'Performance', type: 'gauge', center: ['50%', '50%'], startAngle: 140, endAngle: -140, min: 0, max: 100, precision: 0, splitNumber: 10, axisLine: { show: true, lineStyle: { color: [ [0.2, 'lightgreen'], [0.4, 'orange'], [0.8, 'skyblue'], [1, '#ff4500'] ], width: 30 } }, axisTick: { show: true, splitNumber: 5, length: 8, lineStyle: { color: '#eee', width: 1, type: 'solid' } }, axisLabel: { show: true, formatter: function(v) { switch (v + '') { case '10': return 'a'; case '30': return 'b'; case '60': return 'c'; case '90': return 'd'; default: return ''; } }, textStyle: { color: '#333' } }, splitLine: { show: true, length: 30, lineStyle: { color: '#eee', width: 2, type: 'solid' } }, pointer: { length: '80%', width: 8, color: 'auto' }, title: { show: true, offsetCenter: ['-65%', -10], textStyle: { color: '#333', fontSize: 15 } }, detail: { show: true, backgroundColor: 'rgba(0,0,0,0)', borderWidth: 0, borderColor: '#ccc', width: 100, height: 40, offsetCenter: ['-60%', 10], formatter: '{value}%', textStyle: { color: 'auto', fontSize: 30 } }, data: [{ value: 50, name: 'Performance' }] }] }); } //echart Line if ($('#echart_line').length ){ var echartLine = echarts.init(document.getElementById('echart_line'), theme); echartLine.setOption({ title: { text: 'Line Graph', subtext: 'Subtitle' }, tooltip: { trigger: 'axis' }, legend: { x: 220, y: 40, data: ['Intent', 'Pre-order', 'Deal'] }, toolbox: { show: true, feature: { magicType: { show: true, title: { line: 'Line', bar: 'Bar', stack: 'Stack', tiled: 'Tiled' }, type: ['line', 'bar', 'stack', 'tiled'] }, restore: { show: true, title: "Restore" }, saveAsImage: { show: true, title: "Save Image" } } }, calculable: true, xAxis: [{ type: 'category', boundaryGap: false, data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }], yAxis: [{ type: 'value' }], series: [{ name: 'Deal', type: 'line', smooth: true, itemStyle: { normal: { areaStyle: { type: 'default' } } }, data: [10, 12, 21, 54, 260, 830, 710] }, { name: 'Pre-order', type: 'line', smooth: true, itemStyle: { normal: { areaStyle: { type: 'default' } } }, data: [30, 182, 434, 791, 390, 30, 10] }, { name: 'Intent', type: 'line', smooth: true, itemStyle: { normal: { areaStyle: { type: 'default' } } }, data: [1320, 1132, 601, 234, 120, 90, 20] }] }); } //echart Scatter if ($('#echart_scatter').length ){ var echartScatter = echarts.init(document.getElementById('echart_scatter'), theme); echartScatter.setOption({ title: { text: 'Scatter Graph', subtext: 'Heinz 2003' }, tooltip: { trigger: 'axis', showDelay: 0, axisPointer: { type: 'cross', lineStyle: { type: 'dashed', width: 1 } } }, legend: { data: ['Data2', 'Data1'] }, toolbox: { show: true, feature: { saveAsImage: { show: true, title: "Save Image" } } }, xAxis: [{ type: 'value', scale: true, axisLabel: { formatter: '{value} cm' } }], yAxis: [{ type: 'value', scale: true, axisLabel: { formatter: '{value} kg' } }], series: [{ name: 'Data1', type: 'scatter', tooltip: { trigger: 'item', formatter: function(params) { if (params.value.length > 1) { return params.seriesName + ' :<br/>' + params.value[0] + 'cm ' + params.value[1] + 'kg '; } else { return params.seriesName + ' :<br/>' + params.name + ' : ' + params.value + 'kg '; } } }, data: [ [161.2, 51.6], [167.5, 59.0], [159.5, 49.2], [157.0, 63.0], [155.8, 53.6], [170.0, 59.0], [159.1, 47.6], [166.0, 69.8], [176.2, 66.8], [160.2, 75.2], [172.5, 55.2], [170.9, 54.2], [172.9, 62.5], [153.4, 42.0], [160.0, 50.0], [147.2, 49.8], [168.2, 49.2], [175.0, 73.2], [157.0, 47.8], [167.6, 68.8], [159.5, 50.6], [175.0, 82.5], [166.8, 57.2], [176.5, 87.8], [170.2, 72.8], [174.0, 54.5], [173.0, 59.8], [179.9, 67.3], [170.5, 67.8], [160.0, 47.0], [154.4, 46.2], [162.0, 55.0], [176.5, 83.0], [160.0, 54.4], [152.0, 45.8], [162.1, 53.6], [170.0, 73.2], [160.2, 52.1], [161.3, 67.9], [166.4, 56.6], [168.9, 62.3], [163.8, 58.5], [167.6, 54.5], [160.0, 50.2], [161.3, 60.3], [167.6, 58.3], [165.1, 56.2], [160.0, 50.2], [170.0, 72.9], [157.5, 59.8], [167.6, 61.0], [160.7, 69.1], [163.2, 55.9], [152.4, 46.5], [157.5, 54.3], [168.3, 54.8], [180.3, 60.7], [165.5, 60.0], [165.0, 62.0], [164.5, 60.3], [156.0, 52.7], [160.0, 74.3], [163.0, 62.0], [165.7, 73.1], [161.0, 80.0], [162.0, 54.7], [166.0, 53.2], [174.0, 75.7], [172.7, 61.1], [167.6, 55.7], [151.1, 48.7], [164.5, 52.3], [163.5, 50.0], [152.0, 59.3], [169.0, 62.5], [164.0, 55.7], [161.2, 54.8], [155.0, 45.9], [170.0, 70.6], [176.2, 67.2], [170.0, 69.4], [162.5, 58.2], [170.3, 64.8], [164.1, 71.6], [169.5, 52.8], [163.2, 59.8], [154.5, 49.0], [159.8, 50.0], [173.2, 69.2], [170.0, 55.9], [161.4, 63.4], [169.0, 58.2], [166.2, 58.6], [159.4, 45.7], [162.5, 52.2], [159.0, 48.6], [162.8, 57.8], [159.0, 55.6], [179.8, 66.8], [162.9, 59.4], [161.0, 53.6], [151.1, 73.2], [168.2, 53.4], [168.9, 69.0], [173.2, 58.4], [171.8, 56.2], [178.0, 70.6], [164.3, 59.8], [163.0, 72.0], [168.5, 65.2], [166.8, 56.6], [172.7, 105.2], [163.5, 51.8], [169.4, 63.4], [167.8, 59.0], [159.5, 47.6], [167.6, 63.0], [161.2, 55.2], [160.0, 45.0], [163.2, 54.0], [162.2, 50.2], [161.3, 60.2], [149.5, 44.8], [157.5, 58.8], [163.2, 56.4], [172.7, 62.0], [155.0, 49.2], [156.5, 67.2], [164.0, 53.8], [160.9, 54.4], [162.8, 58.0], [167.0, 59.8], [160.0, 54.8], [160.0, 43.2], [168.9, 60.5], [158.2, 46.4], [156.0, 64.4], [160.0, 48.8], [167.1, 62.2], [158.0, 55.5], [167.6, 57.8], [156.0, 54.6], [162.1, 59.2], [173.4, 52.7], [159.8, 53.2], [170.5, 64.5], [159.2, 51.8], [157.5, 56.0], [161.3, 63.6], [162.6, 63.2], [160.0, 59.5], [168.9, 56.8], [165.1, 64.1], [162.6, 50.0], [165.1, 72.3], [166.4, 55.0], [160.0, 55.9], [152.4, 60.4], [170.2, 69.1], [162.6, 84.5], [170.2, 55.9], [158.8, 55.5], [172.7, 69.5], [167.6, 76.4], [162.6, 61.4], [167.6, 65.9], [156.2, 58.6], [175.2, 66.8], [172.1, 56.6], [162.6, 58.6], [160.0, 55.9], [165.1, 59.1], [182.9, 81.8], [166.4, 70.7], [165.1, 56.8], [177.8, 60.0], [165.1, 58.2], [175.3, 72.7], [154.9, 54.1], [158.8, 49.1], [172.7, 75.9], [168.9, 55.0], [161.3, 57.3], [167.6, 55.0], [165.1, 65.5], [175.3, 65.5], [157.5, 48.6], [163.8, 58.6], [167.6, 63.6], [165.1, 55.2], [165.1, 62.7], [168.9, 56.6], [162.6, 53.9], [164.5, 63.2], [176.5, 73.6], [168.9, 62.0], [175.3, 63.6], [159.4, 53.2], [160.0, 53.4], [170.2, 55.0], [162.6, 70.5], [167.6, 54.5], [162.6, 54.5], [160.7, 55.9], [160.0, 59.0], [157.5, 63.6], [162.6, 54.5], [152.4, 47.3], [170.2, 67.7], [165.1, 80.9], [172.7, 70.5], [165.1, 60.9], [170.2, 63.6], [170.2, 54.5], [170.2, 59.1], [161.3, 70.5], [167.6, 52.7], [167.6, 62.7], [165.1, 86.3], [162.6, 66.4], [152.4, 67.3], [168.9, 63.0], [170.2, 73.6], [175.2, 62.3], [175.2, 57.7], [160.0, 55.4], [165.1, 104.1], [174.0, 55.5], [170.2, 77.3], [160.0, 80.5], [167.6, 64.5], [167.6, 72.3], [167.6, 61.4], [154.9, 58.2], [162.6, 81.8], [175.3, 63.6], [171.4, 53.4], [157.5, 54.5], [165.1, 53.6], [160.0, 60.0], [174.0, 73.6], [162.6, 61.4], [174.0, 55.5], [162.6, 63.6], [161.3, 60.9], [156.2, 60.0], [149.9, 46.8], [169.5, 57.3], [160.0, 64.1], [175.3, 63.6], [169.5, 67.3], [160.0, 75.5], [172.7, 68.2], [162.6, 61.4], [157.5, 76.8], [176.5, 71.8], [164.4, 55.5], [160.7, 48.6], [174.0, 66.4], [163.8, 67.3] ], markPoint: { data: [{ type: 'max', name: 'Max' }, { type: 'min', name: 'Min' }] }, markLine: { data: [{ type: 'average', name: 'Mean' }] } }, { name: 'Data2', type: 'scatter', tooltip: { trigger: 'item', formatter: function(params) { if (params.value.length > 1) { return params.seriesName + ' :<br/>' + params.value[0] + 'cm ' + params.value[1] + 'kg '; } else { return params.seriesName + ' :<br/>' + params.name + ' : ' + params.value + 'kg '; } } }, data: [ [174.0, 65.6], [175.3, 71.8], [193.5, 80.7], [186.5, 72.6], [187.2, 78.8], [181.5, 74.8], [184.0, 86.4], [184.5, 78.4], [175.0, 62.0], [184.0, 81.6], [180.0, 76.6], [177.8, 83.6], [192.0, 90.0], [176.0, 74.6], [174.0, 71.0], [184.0, 79.6], [192.7, 93.8], [171.5, 70.0], [173.0, 72.4], [176.0, 85.9], [176.0, 78.8], [180.5, 77.8], [172.7, 66.2], [176.0, 86.4], [173.5, 81.8], [178.0, 89.6], [180.3, 82.8], [180.3, 76.4], [164.5, 63.2], [173.0, 60.9], [183.5, 74.8], [175.5, 70.0], [188.0, 72.4], [189.2, 84.1], [172.8, 69.1], [170.0, 59.5], [182.0, 67.2], [170.0, 61.3], [177.8, 68.6], [184.2, 80.1], [186.7, 87.8], [171.4, 84.7], [172.7, 73.4], [175.3, 72.1], [180.3, 82.6], [182.9, 88.7], [188.0, 84.1], [177.2, 94.1], [172.1, 74.9], [167.0, 59.1], [169.5, 75.6], [174.0, 86.2], [172.7, 75.3], [182.2, 87.1], [164.1, 55.2], [163.0, 57.0], [171.5, 61.4], [184.2, 76.8], [174.0, 86.8], [174.0, 72.2], [177.0, 71.6], [186.0, 84.8], [167.0, 68.2], [171.8, 66.1], [182.0, 72.0], [167.0, 64.6], [177.8, 74.8], [164.5, 70.0], [192.0, 101.6], [175.5, 63.2], [171.2, 79.1], [181.6, 78.9], [167.4, 67.7], [181.1, 66.0], [177.0, 68.2], [174.5, 63.9], [177.5, 72.0], [170.5, 56.8], [182.4, 74.5], [197.1, 90.9], [180.1, 93.0], [175.5, 80.9], [180.6, 72.7], [184.4, 68.0], [175.5, 70.9], [180.6, 72.5], [177.0, 72.5], [177.1, 83.4], [181.6, 75.5], [176.5, 73.0], [175.0, 70.2], [174.0, 73.4], [165.1, 70.5], [177.0, 68.9], [192.0, 102.3], [176.5, 68.4], [169.4, 65.9], [182.1, 75.7], [179.8, 84.5], [175.3, 87.7], [184.9, 86.4], [177.3, 73.2], [167.4, 53.9], [178.1, 72.0], [168.9, 55.5], [157.2, 58.4], [180.3, 83.2], [170.2, 72.7], [177.8, 64.1], [172.7, 72.3], [165.1, 65.0], [186.7, 86.4], [165.1, 65.0], [174.0, 88.6], [175.3, 84.1], [185.4, 66.8], [177.8, 75.5], [180.3, 93.2], [180.3, 82.7], [177.8, 58.0], [177.8, 79.5], [177.8, 78.6], [177.8, 71.8], [177.8, 116.4], [163.8, 72.2], [188.0, 83.6], [198.1, 85.5], [175.3, 90.9], [166.4, 85.9], [190.5, 89.1], [166.4, 75.0], [177.8, 77.7], [179.7, 86.4], [172.7, 90.9], [190.5, 73.6], [185.4, 76.4], [168.9, 69.1], [167.6, 84.5], [175.3, 64.5], [170.2, 69.1], [190.5, 108.6], [177.8, 86.4], [190.5, 80.9], [177.8, 87.7], [184.2, 94.5], [176.5, 80.2], [177.8, 72.0], [180.3, 71.4], [171.4, 72.7], [172.7, 84.1], [172.7, 76.8], [177.8, 63.6], [177.8, 80.9], [182.9, 80.9], [170.2, 85.5], [167.6, 68.6], [175.3, 67.7], [165.1, 66.4], [185.4, 102.3], [181.6, 70.5], [172.7, 95.9], [190.5, 84.1], [179.1, 87.3], [175.3, 71.8], [170.2, 65.9], [193.0, 95.9], [171.4, 91.4], [177.8, 81.8], [177.8, 96.8], [167.6, 69.1], [167.6, 82.7], [180.3, 75.5], [182.9, 79.5], [176.5, 73.6], [186.7, 91.8], [188.0, 84.1], [188.0, 85.9], [177.8, 81.8], [174.0, 82.5], [177.8, 80.5], [171.4, 70.0], [185.4, 81.8], [185.4, 84.1], [188.0, 90.5], [188.0, 91.4], [182.9, 89.1], [176.5, 85.0], [175.3, 69.1], [175.3, 73.6], [188.0, 80.5], [188.0, 82.7], [175.3, 86.4], [170.5, 67.7], [179.1, 92.7], [177.8, 93.6], [175.3, 70.9], [182.9, 75.0], [170.8, 93.2], [188.0, 93.2], [180.3, 77.7], [177.8, 61.4], [185.4, 94.1], [168.9, 75.0], [185.4, 83.6], [180.3, 85.5], [174.0, 73.9], [167.6, 66.8], [182.9, 87.3], [160.0, 72.3], [180.3, 88.6], [167.6, 75.5], [186.7, 101.4], [175.3, 91.1], [175.3, 67.3], [175.9, 77.7], [175.3, 81.8], [179.1, 75.5], [181.6, 84.5], [177.8, 76.6], [182.9, 85.0], [177.8, 102.5], [184.2, 77.3], [179.1, 71.8], [176.5, 87.9], [188.0, 94.3], [174.0, 70.9], [167.6, 64.5], [170.2, 77.3], [167.6, 72.3], [188.0, 87.3], [174.0, 80.0], [176.5, 82.3], [180.3, 73.6], [167.6, 74.1], [188.0, 85.9], [180.3, 73.2], [167.6, 76.3], [183.0, 65.9], [183.0, 90.9], [179.1, 89.1], [170.2, 62.3], [177.8, 82.7], [179.1, 79.1], [190.5, 98.2], [177.8, 84.1], [180.3, 83.2], [180.3, 83.2] ], markPoint: { data: [{ type: 'max', name: 'Max' }, { type: 'min', name: 'Min' }] }, markLine: { data: [{ type: 'average', name: 'Mean' }] } }] }); } //echart Bar Horizontal if ($('#echart_bar_horizontal').length ){ var echartBar = echarts.init(document.getElementById('echart_bar_horizontal'), theme); echartBar.setOption({ title: { text: 'Bar Graph', subtext: 'Graph subtitle' }, tooltip: { trigger: 'axis' }, legend: { x: 100, data: ['2015', '2016'] }, toolbox: { show: true, feature: { saveAsImage: { show: true, title: "Save Image" } } }, calculable: true, xAxis: [{ type: 'value', boundaryGap: [0, 0.01] }], yAxis: [{ type: 'category', data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] }], series: [{ name: '2015', type: 'bar', data: [18203, 23489, 29034, 104970, 131744, 630230] }, { name: '2016', type: 'bar', data: [19325, 23438, 31000, 121594, 134141, 681807] }] }); } //echart Pie Collapse if ($('#echart_pie2').length ){ var echartPieCollapse = echarts.init(document.getElementById('echart_pie2'), theme); echartPieCollapse.setOption({ tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { x: 'center', y: 'bottom', data: ['rose1', 'rose2', 'rose3', 'rose4', 'rose5', 'rose6'] }, toolbox: { show: true, feature: { magicType: { show: true, type: ['pie', 'funnel'] }, restore: { show: true, title: "Restore" }, saveAsImage: { show: true, title: "Save Image" } } }, calculable: true, series: [{ name: 'Area Mode', type: 'pie', radius: [25, 90], center: ['50%', 170], roseType: 'area', x: '50%', max: 40, sort: 'ascending', data: [{ value: 10, name: 'rose1' }, { value: 5, name: 'rose2' }, { value: 15, name: 'rose3' }, { value: 25, name: 'rose4' }, { value: 20, name: 'rose5' }, { value: 35, name: 'rose6' }] }] }); } //echart Donut if ($('#echart_donut').length ){ var echartDonut = echarts.init(document.getElementById('echart_donut'), theme); echartDonut.setOption({ tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, calculable: true, legend: { x: 'center', y: 'bottom', data: ['Direct Access', 'E-mail Marketing', 'Union Ad', 'Video Ads', 'Search Engine'] }, toolbox: { show: true, feature: { magicType: { show: true, type: ['pie', 'funnel'], option: { funnel: { x: '25%', width: '50%', funnelAlign: 'center', max: 1548 } } }, restore: { show: true, title: "Restore" }, saveAsImage: { show: true, title: "Save Image" } } }, series: [{ name: 'Access to the resource', type: 'pie', radius: ['35%', '55%'], itemStyle: { normal: { label: { show: true }, labelLine: { show: true } }, emphasis: { label: { show: true, position: 'center', textStyle: { fontSize: '14', fontWeight: 'normal' } } } }, data: [{ value: 335, name: 'Direct Access' }, { value: 310, name: 'E-mail Marketing' }, { value: 234, name: 'Union Ad' }, { value: 135, name: 'Video Ads' }, { value: 1548, name: 'Search Engine' }] }] }); } //echart Pie if ($('#echart_pie').length ){ var echartPie = echarts.init(document.getElementById('echart_pie'), theme); echartPie.setOption({ tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { x: 'center', y: 'bottom', data: ['Direct Access', 'E-mail Marketing', 'Union Ad', 'Video Ads', 'Search Engine'] }, toolbox: { show: true, feature: { magicType: { show: true, type: ['pie', 'funnel'], option: { funnel: { x: '25%', width: '50%', funnelAlign: 'left', max: 1548 } } }, restore: { show: true, title: "Restore" }, saveAsImage: { show: true, title: "Save Image" } } }, calculable: true, series: [{ name: '访问来源', type: 'pie', radius: '55%', center: ['50%', '48%'], data: [{ value: 335, name: 'Direct Access' }, { value: 310, name: 'E-mail Marketing' }, { value: 234, name: 'Union Ad' }, { value: 135, name: 'Video Ads' }, { value: 1548, name: 'Search Engine' }] }] }); var dataStyle = { normal: { label: { show: false }, labelLine: { show: false } } }; var placeHolderStyle = { normal: { color: 'rgba(0,0,0,0)', label: { show: false }, labelLine: { show: false } }, emphasis: { color: 'rgba(0,0,0,0)' } }; } //echart Mini Pie if ($('#echart_mini_pie').length ){ var echartMiniPie = echarts.init(document.getElementById('echart_mini_pie'), theme); echartMiniPie .setOption({ title: { text: 'Chart #2', subtext: 'From ExcelHome', sublink: 'http://e.weibo.com/1341556070/AhQXtjbqh', x: 'center', y: 'center', itemGap: 20, textStyle: { color: 'rgba(30,144,255,0.8)', fontFamily: '微软雅黑', fontSize: 35, fontWeight: 'bolder' } }, tooltip: { show: true, formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { orient: 'vertical', x: 170, y: 45, itemGap: 12, data: ['68%Something #1', '29%Something #2', '3%Something #3'], }, toolbox: { show: true, feature: { mark: { show: true }, dataView: { show: true, title: "Text View", lang: [ "Text View", "Close", "Refresh", ], readOnly: false }, restore: { show: true, title: "Restore" }, saveAsImage: { show: true, title: "Save Image" } } }, series: [{ name: '1', type: 'pie', clockWise: false, radius: [105, 130], itemStyle: dataStyle, data: [{ value: 68, name: '68%Something #1' }, { value: 32, name: 'invisible', itemStyle: placeHolderStyle }] }, { name: '2', type: 'pie', clockWise: false, radius: [80, 105], itemStyle: dataStyle, data: [{ value: 29, name: '29%Something #2' }, { value: 71, name: 'invisible', itemStyle: placeHolderStyle }] }, { name: '3', type: 'pie', clockWise: false, radius: [25, 80], itemStyle: dataStyle, data: [{ value: 3, name: '3%Something #3' }, { value: 97, name: 'invisible', itemStyle: placeHolderStyle }] }] }); } //echart Map if ($('#echart_world_map').length ){ var echartMap = echarts.init(document.getElementById('echart_world_map'), theme); echartMap.setOption({ title: { text: 'World Population (2010)', subtext: 'from United Nations, Total population, both sexes combined, as of 1 July (thousands)', x: 'center', y: 'top' }, tooltip: { trigger: 'item', formatter: function(params) { var value = (params.value + '').split('.'); value = value[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + '.' + value[1]; return params.seriesName + '<br/>' + params.name + ' : ' + value; } }, toolbox: { show: true, orient: 'vertical', x: 'right', y: 'center', feature: { mark: { show: true }, dataView: { show: true, title: "Text View", lang: [ "Text View", "Close", "Refresh", ], readOnly: false }, restore: { show: true, title: "Restore" }, saveAsImage: { show: true, title: "Save Image" } } }, dataRange: { min: 0, max: 1000000, text: ['High', 'Low'], realtime: false, calculable: true, color: ['#087E65', '#26B99A', '#CBEAE3'] }, series: [{ name: 'World Population (2010)', type: 'map', mapType: 'world', roam: false, mapLocation: { y: 60 }, itemStyle: { emphasis: { label: { show: true } } }, data: [{ name: 'Afghanistan', value: 28397.812 }, { name: 'Angola', value: 19549.124 }, { name: 'Albania', value: 3150.143 }, { name: 'United Arab Emirates', value: 8441.537 }, { name: 'Argentina', value: 40374.224 }, { name: 'Armenia', value: 2963.496 }, { name: 'French Southern and Antarctic Lands', value: 268.065 }, { name: 'Australia', value: 22404.488 }, { name: 'Austria', value: 8401.924 }, { name: 'Azerbaijan', value: 9094.718 }, { name: 'Burundi', value: 9232.753 }, { name: 'Belgium', value: 10941.288 }, { name: 'Benin', value: 9509.798 }, { name: 'Burkina Faso', value: 15540.284 }, { name: 'Bangladesh', value: 151125.475 }, { name: 'Bulgaria', value: 7389.175 }, { name: 'The Bahamas', value: 66402.316 }, { name: 'Bosnia and Herzegovina', value: 3845.929 }, { name: 'Belarus', value: 9491.07 }, { name: 'Belize', value: 308.595 }, { name: 'Bermuda', value: 64.951 }, { name: 'Bolivia', value: 716.939 }, { name: 'Brazil', value: 195210.154 }, { name: 'Brunei', value: 27.223 }, { name: 'Bhutan', value: 716.939 }, { name: 'Botswana', value: 1969.341 }, { name: 'Central African Republic', value: 4349.921 }, { name: 'Canada', value: 34126.24 }, { name: 'Switzerland', value: 7830.534 }, { name: 'Chile', value: 17150.76 }, { name: 'China', value: 1359821.465 }, { name: 'Ivory Coast', value: 60508.978 }, { name: 'Cameroon', value: 20624.343 }, { name: 'Democratic Republic of the Congo', value: 62191.161 }, { name: 'Republic of the Congo', value: 3573.024 }, { name: 'Colombia', value: 46444.798 }, { name: 'Costa Rica', value: 4669.685 }, { name: 'Cuba', value: 11281.768 }, { name: 'Northern Cyprus', value: 1.468 }, { name: 'Cyprus', value: 1103.685 }, { name: 'Czech Republic', value: 10553.701 }, { name: 'Germany', value: 83017.404 }, { name: 'Djibouti', value: 834.036 }, { name: 'Denmark', value: 5550.959 }, { name: 'Dominican Republic', value: 10016.797 }, { name: 'Algeria', value: 37062.82 }, { name: 'Ecuador', value: 15001.072 }, { name: 'Egypt', value: 78075.705 }, { name: 'Eritrea', value: 5741.159 }, { name: 'Spain', value: 46182.038 }, { name: 'Estonia', value: 1298.533 }, { name: 'Ethiopia', value: 87095.281 }, { name: 'Finland', value: 5367.693 }, { name: 'Fiji', value: 860.559 }, { name: 'Falkland Islands', value: 49.581 }, { name: 'France', value: 63230.866 }, { name: 'Gabon', value: 1556.222 }, { name: 'United Kingdom', value: 62066.35 }, { name: 'Georgia', value: 4388.674 }, { name: 'Ghana', value: 24262.901 }, { name: 'Guinea', value: 10876.033 }, { name: 'Gambia', value: 1680.64 }, { name: 'Guinea Bissau', value: 10876.033 }, { name: 'Equatorial Guinea', value: 696.167 }, { name: 'Greece', value: 11109.999 }, { name: 'Greenland', value: 56.546 }, { name: 'Guatemala', value: 14341.576 }, { name: 'French Guiana', value: 231.169 }, { name: 'Guyana', value: 786.126 }, { name: 'Honduras', value: 7621.204 }, { name: 'Croatia', value: 4338.027 }, { name: 'Haiti', value: 9896.4 }, { name: 'Hungary', value: 10014.633 }, { name: 'Indonesia', value: 240676.485 }, { name: 'India', value: 1205624.648 }, { name: 'Ireland', value: 4467.561 }, { name: 'Iran', value: 240676.485 }, { name: 'Iraq', value: 30962.38 }, { name: 'Iceland', value: 318.042 }, { name: 'Israel', value: 7420.368 }, { name: 'Italy', value: 60508.978 }, { name: 'Jamaica', value: 2741.485 }, { name: 'Jordan', value: 6454.554 }, { name: 'Japan', value: 127352.833 }, { name: 'Kazakhstan', value: 15921.127 }, { name: 'Kenya', value: 40909.194 }, { name: 'Kyrgyzstan', value: 5334.223 }, { name: 'Cambodia', value: 14364.931 }, { name: 'South Korea', value: 51452.352 }, { name: 'Kosovo', value: 97.743 }, { name: 'Kuwait', value: 2991.58 }, { name: 'Laos', value: 6395.713 }, { name: 'Lebanon', value: 4341.092 }, { name: 'Liberia', value: 3957.99 }, { name: 'Libya', value: 6040.612 }, { name: 'Sri Lanka', value: 20758.779 }, { name: 'Lesotho', value: 2008.921 }, { name: 'Lithuania', value: 3068.457 }, { name: 'Luxembourg', value: 507.885 }, { name: 'Latvia', value: 2090.519 }, { name: 'Morocco', value: 31642.36 }, { name: 'Moldova', value: 103.619 }, { name: 'Madagascar', value: 21079.532 }, { name: 'Mexico', value: 117886.404 }, { name: 'Macedonia', value: 507.885 }, { name: 'Mali', value: 13985.961 }, { name: 'Myanmar', value: 51931.231 }, { name: 'Montenegro', value: 620.078 }, { name: 'Mongolia', value: 2712.738 }, { name: 'Mozambique', value: 23967.265 }, { name: 'Mauritania', value: 3609.42 }, { name: 'Malawi', value: 15013.694 }, { name: 'Malaysia', value: 28275.835 }, { name: 'Namibia', value: 2178.967 }, { name: 'New Caledonia', value: 246.379 }, { name: 'Niger', value: 15893.746 }, { name: 'Nigeria', value: 159707.78 }, { name: 'Nicaragua', value: 5822.209 }, { name: 'Netherlands', value: 16615.243 }, { name: 'Norway', value: 4891.251 }, { name: 'Nepal', value: 26846.016 }, { name: 'New Zealand', value: 4368.136 }, { name: 'Oman', value: 2802.768 }, { name: 'Pakistan', value: 173149.306 }, { name: 'Panama', value: 3678.128 }, { name: 'Peru', value: 29262.83 }, { name: 'Philippines', value: 93444.322 }, { name: 'Papua New Guinea', value: 6858.945 }, { name: 'Poland', value: 38198.754 }, { name: 'Puerto Rico', value: 3709.671 }, { name: 'North Korea', value: 1.468 }, { name: 'Portugal', value: 10589.792 }, { name: 'Paraguay', value: 6459.721 }, { name: 'Qatar', value: 1749.713 }, { name: 'Romania', value: 21861.476 }, { name: 'Russia', value: 21861.476 }, { name: 'Rwanda', value: 10836.732 }, { name: 'Western Sahara', value: 514.648 }, { name: 'Saudi Arabia', value: 27258.387 }, { name: 'Sudan', value: 35652.002 }, { name: 'South Sudan', value: 9940.929 }, { name: 'Senegal', value: 12950.564 }, { name: 'Solomon Islands', value: 526.447 }, { name: 'Sierra Leone', value: 5751.976 }, { name: 'El Salvador', value: 6218.195 }, { name: 'Somaliland', value: 9636.173 }, { name: 'Somalia', value: 9636.173 }, { name: 'Republic of Serbia', value: 3573.024 }, { name: 'Suriname', value: 524.96 }, { name: 'Slovakia', value: 5433.437 }, { name: 'Slovenia', value: 2054.232 }, { name: 'Sweden', value: 9382.297 }, { name: 'Swaziland', value: 1193.148 }, { name: 'Syria', value: 7830.534 }, { name: 'Chad', value: 11720.781 }, { name: 'Togo', value: 6306.014 }, { name: 'Thailand', value: 66402.316 }, { name: 'Tajikistan', value: 7627.326 }, { name: 'Turkmenistan', value: 5041.995 }, { name: 'East Timor', value: 10016.797 }, { name: 'Trinidad and Tobago', value: 1328.095 }, { name: 'Tunisia', value: 10631.83 }, { name: 'Turkey', value: 72137.546 }, { name: 'United Republic of Tanzania', value: 44973.33 }, { name: 'Uganda', value: 33987.213 }, { name: 'Ukraine', value: 46050.22 }, { name: 'Uruguay', value: 3371.982 }, { name: 'United States of America', value: 312247.116 }, { name: 'Uzbekistan', value: 27769.27 }, { name: 'Venezuela', value: 236.299 }, { name: 'Vietnam', value: 89047.397 }, { name: 'Vanuatu', value: 236.299 }, { name: 'West Bank', value: 13.565 }, { name: 'Yemen', value: 22763.008 }, { name: 'South Africa', value: 51452.352 }, { name: 'Zambia', value: 13216.985 }, { name: 'Zimbabwe', value: 13076.978 }] }] }); } } $(document).ready(function() { init_sparklines(); init_flot_chart(); init_sidebar(); init_wysiwyg(); init_InputMask(); init_JQVmap(); init_cropper(); init_knob(); init_IonRangeSlider(); init_ColorPicker(); init_TagsInput(); init_parsley(); init_daterangepicker(); init_daterangepicker_right(); init_daterangepicker_single_call(); init_daterangepicker_reservation(); init_SmartWizard(); init_EasyPieChart(); init_charts(); init_echarts(); init_morris_charts(); init_skycons(); init_select2(); init_validator(); init_DataTables(); init_chart_doughnut(); init_gauge(); init_PNotify(); init_starrr(); init_calendar(); init_compose(); init_CustomNotification(); init_autosize(); init_autocomplete(); });
import cors from '../../middleware/cors'; import data from '../../data/pancasila'; export default async (req, res) => { await cors(req, res); res.setHeader('Cache-Control', 'max-age=86400'); res.statusCode = 200; res.json({ success: true, data: data, }); };
//// [sourceMapValidationDestructuringForObjectBindingPattern2.ts] declare var console: { log(msg: any): void; } interface Robot { name: string; skill: string; } interface MultiRobot { name: string; skills: { primary: string; secondary: string; }; } let robot: Robot = { name: "mower", skill: "mowing" }; let multiRobot: MultiRobot = { name: "mower", skills: { primary: "mowing", secondary: "none" } }; function getRobot() { return robot; } function getMultiRobot() { return multiRobot; } let nameA: string, primaryA: string, secondaryA: string, i: number, skillA: string; let name: string, primary: string, secondary: string, skill: string; for ({ name: nameA } = robot, i = 0; i < 1; i++) { console.log(nameA); } for ({ name: nameA } = getRobot(), i = 0; i < 1; i++) { console.log(nameA); } for ({ name: nameA } = <Robot>{ name: "trimmer", skill: "trimming" }, i = 0; i < 1; i++) { console.log(nameA); } for ({ skills: { primary: primaryA, secondary: secondaryA } } = multiRobot, i = 0; i < 1; i++) { console.log(primaryA); } for ({ skills: { primary: primaryA, secondary: secondaryA } } = getMultiRobot(), i = 0; i < 1; i++) { console.log(primaryA); } for ({ skills: { primary: primaryA, secondary: secondaryA } } = <MultiRobot>{ name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, i = 0; i < 1; i++) { console.log(primaryA); } for ({ name } = robot, i = 0; i < 1; i++) { console.log(nameA); } for ({ name } = getRobot(), i = 0; i < 1; i++) { console.log(nameA); } for ({ name } = <Robot>{ name: "trimmer", skill: "trimming" }, i = 0; i < 1; i++) { console.log(nameA); } for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { console.log(primaryA); } for ({ skills: { primary, secondary } } = getMultiRobot(), i = 0; i < 1; i++) { console.log(primaryA); } for ({ skills: { primary, secondary } } = <MultiRobot>{ name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, i = 0; i < 1; i++) { console.log(primaryA); } for ({ name: nameA, skill: skillA } = robot, i = 0; i < 1; i++) { console.log(nameA); } for ({ name: nameA, skill: skillA } = getRobot(), i = 0; i < 1; i++) { console.log(nameA); } for ({ name: nameA, skill: skillA } = <Robot>{ name: "trimmer", skill: "trimming" }, i = 0; i < 1; i++) { console.log(nameA); } for ({ name: nameA, skills: { primary: primaryA, secondary: secondaryA } } = multiRobot, i = 0; i < 1; i++) { console.log(primaryA); } for ({ name: nameA, skills: { primary: primaryA, secondary: secondaryA } } = getMultiRobot(), i = 0; i < 1; i++) { console.log(primaryA); } for ({ name: nameA, skills: { primary: primaryA, secondary: secondaryA } } = <MultiRobot>{ name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, i = 0; i < 1; i++) { console.log(primaryA); } for ({ name, skill } = robot, i = 0; i < 1; i++) { console.log(nameA); } for ({ name, skill } = getRobot(), i = 0; i < 1; i++) { console.log(nameA); } for ({ name, skill } = <Robot>{ name: "trimmer", skill: "trimming" }, i = 0; i < 1; i++) { console.log(nameA); } for ({ name, skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { console.log(primaryA); } for ({ name, skills: { primary, secondary } } = getMultiRobot(), i = 0; i < 1; i++) { console.log(primaryA); } for ({ name, skills: { primary, secondary } } = <MultiRobot>{ name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, i = 0; i < 1; i++) { console.log(primaryA); } //// [sourceMapValidationDestructuringForObjectBindingPattern2.js] var robot = { name: "mower", skill: "mowing" }; var multiRobot = { name: "mower", skills: { primary: "mowing", secondary: "none" } }; function getRobot() { return robot; } function getMultiRobot() { return multiRobot; } var nameA, primaryA, secondaryA, i, skillA; var name, primary, secondary, skill; for ((nameA = robot.name, robot), i = 0; i < 1; i++) { console.log(nameA); } for ((_a = getRobot(), nameA = _a.name, _a), i = 0; i < 1; i++) { console.log(nameA); } for ((_b = { name: "trimmer", skill: "trimming" }, nameA = _b.name, _b), i = 0; i < 1; i++) { console.log(nameA); } for ((_c = multiRobot.skills, primaryA = _c.primary, secondaryA = _c.secondary, multiRobot), i = 0; i < 1; i++) { console.log(primaryA); } for ((_d = getMultiRobot(), _e = _d.skills, primaryA = _e.primary, secondaryA = _e.secondary, _d), i = 0; i < 1; i++) { console.log(primaryA); } for ((_f = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, _g = _f.skills, primaryA = _g.primary, secondaryA = _g.secondary, _f), i = 0; i < 1; i++) { console.log(primaryA); } for ((name = robot.name, robot), i = 0; i < 1; i++) { console.log(nameA); } for ((_h = getRobot(), name = _h.name, _h), i = 0; i < 1; i++) { console.log(nameA); } for ((_j = { name: "trimmer", skill: "trimming" }, name = _j.name, _j), i = 0; i < 1; i++) { console.log(nameA); } for ((_k = multiRobot.skills, primary = _k.primary, secondary = _k.secondary, multiRobot), i = 0; i < 1; i++) { console.log(primaryA); } for ((_l = getMultiRobot(), _m = _l.skills, primary = _m.primary, secondary = _m.secondary, _l), i = 0; i < 1; i++) { console.log(primaryA); } for ((_o = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, _p = _o.skills, primary = _p.primary, secondary = _p.secondary, _o), i = 0; i < 1; i++) { console.log(primaryA); } for ((nameA = robot.name, skillA = robot.skill, robot), i = 0; i < 1; i++) { console.log(nameA); } for ((_q = getRobot(), nameA = _q.name, skillA = _q.skill, _q), i = 0; i < 1; i++) { console.log(nameA); } for ((_r = { name: "trimmer", skill: "trimming" }, nameA = _r.name, skillA = _r.skill, _r), i = 0; i < 1; i++) { console.log(nameA); } for ((nameA = multiRobot.name, _s = multiRobot.skills, primaryA = _s.primary, secondaryA = _s.secondary, multiRobot), i = 0; i < 1; i++) { console.log(primaryA); } for ((_t = getMultiRobot(), nameA = _t.name, _u = _t.skills, primaryA = _u.primary, secondaryA = _u.secondary, _t), i = 0; i < 1; i++) { console.log(primaryA); } for ((_v = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, nameA = _v.name, _w = _v.skills, primaryA = _w.primary, secondaryA = _w.secondary, _v), i = 0; i < 1; i++) { console.log(primaryA); } for ((name = robot.name, skill = robot.skill, robot), i = 0; i < 1; i++) { console.log(nameA); } for ((_x = getRobot(), name = _x.name, skill = _x.skill, _x), i = 0; i < 1; i++) { console.log(nameA); } for ((_y = { name: "trimmer", skill: "trimming" }, name = _y.name, skill = _y.skill, _y), i = 0; i < 1; i++) { console.log(nameA); } for ((name = multiRobot.name, _z = multiRobot.skills, primary = _z.primary, secondary = _z.secondary, multiRobot), i = 0; i < 1; i++) { console.log(primaryA); } for ((_0 = getMultiRobot(), name = _0.name, _1 = _0.skills, primary = _1.primary, secondary = _1.secondary, _0), i = 0; i < 1; i++) { console.log(primaryA); } for ((_2 = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, name = _2.name, _3 = _2.skills, primary = _3.primary, secondary = _3.secondary, _2), i = 0; i < 1; i++) { console.log(primaryA); } var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3; //# sourceMappingURL=sourceMapValidationDestructuringForObjectBindingPattern2.js.map
import React from 'react'; import { Platform, StyleSheet, Text, View } from 'react-native'; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); function PushedScreen() { return ( <View style={styles.container}> <Text style={styles.welcome}>Welcome to React Native!</Text> <Text style={styles.instructions}>To get started, edit PushedScreen.js</Text> <Text style={styles.instructions}> {Platform.select({ ios: 'Press Cmd+R to reload,\nCmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', })} </Text> </View> ); } export default PushedScreen;
import { shallowMount } from '@vue/test-utils' import BDatepickerTableRow from '@components/datepicker/DatepickerTableRow' const newDate = (y, m, d) => { const date = new Date(Date.UTC(y, m, d)) date.getDate = jest.fn(() => date.getUTCDate()) return date } const propsData = { firstDayOfWeek: 0, week: [ newDate(2017, 12, 31), newDate(2018, 1, 1), newDate(2018, 1, 2), newDate(2018, 1, 3), newDate(2018, 1, 4), newDate(2018, 1, 5), newDate(2018, 1, 6) ], month: 12, dateCreator: () => newDate() } let wrapper describe('BDatepickerTableRow', () => { beforeEach(() => { wrapper = shallowMount(BDatepickerTableRow, { propsData }) }) it('is called', () => { expect(wrapper.name()).toBe('BDatepickerTableRow') expect(wrapper.isVueInstance()).toBeTruthy() }) it('render correctly', () => { expect(wrapper.html()).toMatchSnapshot() }) describe('classObject', function () { beforeEach(() => { wrapper.setProps({ selectedDate: [propsData.week[1], propsData.week[5]], nearbySelectableMonthDays: true }) }) it('should have is-selected class for all range of dates selected', function () { expect(wrapper.findAll('.is-selected').length).toBe(5) }) it('should have is-first-selected class for the first date selected within the range', function () { const {wrappers: [firstSelectedCell]} = wrapper.findAll('.is-selected') expect(firstSelectedCell.classes()).toContain('is-first-selected') }) it('should have is-within-selected class for the dates selected within the range', function () { const withinSelectedRangeCells = wrapper.findAll('.is-selected.is-within-selected') expect(withinSelectedRangeCells.length).toBe(3) }) it('should have is-last-selected class for the last date selected within the range', function () { // wrappers should return 5 elements. Destructure to get the last one const {wrappers: [, , , , lastSelectedCell]} = wrapper.findAll('.is-selected') expect(lastSelectedCell.classes()).toContain('is-last-selected') }) it('should has is-selected class for all range of dates selected', function () { expect(wrapper.findAll('.is-selected').length).toBe(5) }) describe('hovered', function () { beforeEach(() => { wrapper.setProps({ hoveredDateRange: [propsData.week[1], propsData.week[5]] }) }) it('should have is-within-hovered-range class for all range of dates hovered', function () { expect(wrapper.findAll('.is-selected').length).toBe(5) }) it('should have is-first-hovered class for the first date hovered within the range', function () { const {wrappers: [firstHoveredCell]} = wrapper.findAll('.is-within-hovered-range') expect(firstHoveredCell.classes()).toContain('is-first-hovered') }) it('should have is-within-hovered class for the dates hovered within the range', function () { const withinHoveredRangeCells = wrapper.findAll('.is-within-hovered-range.is-within-hovered') expect(withinHoveredRangeCells.length).toBe(3) }) it('should have is-last-hovered class for the last date hovered within the range', function () { // wrappers should return 5 elements. Destructure to get the last one const {wrappers: [, , , , lastHoveredCell]} = wrapper.findAll('.is-within-hovered-range') expect(lastHoveredCell.classes()).toContain('is-last-hovered') }) it('should has is-within-hovered-range class for all range of dates hovered', function () { expect(wrapper.findAll('.is-within-hovered-range').length).toBe(5) }) }) }) describe('classObject with multiple dates', function () { beforeEach(() => { wrapper.setProps({ selectedDate: [propsData.week[1], propsData.week[5], propsData.week[3]], multiple: true }) }) it('should have is-selected class for all dates selected', function () { expect(wrapper.findAll('.is-selected').length).toBe(3) }) it('should not have is-first-selected class for the first date selected within the range', function () { const {wrappers: [firstSelectedCell]} = wrapper.findAll('.is-selected') expect(firstSelectedCell.classes()).not.toContain('is-first-selected') }) it('should not have is-within-selected class for the dates selected within the range', function () { const withinSelectedRangeCells = wrapper.findAll('.is-selected.is-within-selected') expect(withinSelectedRangeCells.length).toBe(0) }) it('should not have is-last-selected class for the last date selected within the range', function () { // wrappers should return 3 elements. Destructure to get the last one const {wrappers: [, , lastSelectedCell]} = wrapper.findAll('.is-selected') expect(lastSelectedCell.classes()).not.toContain('is-last-selected') }) }) it('manage accordingly leap years', () => { expect(wrapper.vm.isLeapYear(2020)).toBeTruthy() expect(wrapper.vm.daysInYear(2020)).toBe(366) expect(wrapper.vm.isLeapYear(2021)).toBeFalsy() expect(wrapper.vm.daysInYear(2021)).toBe(365) }) it('emit chosen date', () => { wrapper.vm.selectableDate = jest.fn(() => false) wrapper.vm.emitChosenDate(5) expect(wrapper.vm.selectableDate).toHaveBeenCalled() expect(wrapper.emitted()['select']).toBeFalsy() wrapper.vm.selectableDate = jest.fn(() => true) wrapper.vm.emitChosenDate(5) expect(wrapper.vm.selectableDate).toHaveBeenCalled() expect(wrapper.emitted()['select']).toBeTruthy() }) it('emit focused date', () => { const [y, m, d] = [2019, 4, 4] const day = newDate(y, m, d) let inc = 1 let expected = day expected.setDate(day.getDate() + inc) wrapper.vm.changeFocus(day, inc) let valueEmitted = wrapper.emitted()['change-focus'][0] expect(valueEmitted).toContainEqual(expected) inc = -1 expected = day expected.setDate(day.getDate() + inc) wrapper.vm.changeFocus(day, inc) valueEmitted = wrapper.emitted()['change-focus'][0] expect(valueEmitted).toContainEqual(expected) inc = 7 expected = day expected.setDate(day.getDate() + inc) wrapper.vm.changeFocus(day, inc) valueEmitted = wrapper.emitted()['change-focus'][0] expect(valueEmitted).toContainEqual(expected) inc = -7 expected = day expected.setDate(day.getDate() + inc) wrapper.vm.changeFocus(day, inc) valueEmitted = wrapper.emitted()['change-focus'][0] expect(valueEmitted).toContainEqual(expected) }) it('match event days accordingly', () => { const thisMonth = newDate(2019, 4, 4).getMonth() const day = newDate(2019, thisMonth, 6) const todayEvent = { date: day, type: 'is-warning' } const events = [ { date: newDate(2019, thisMonth, 2), type: 'is-warning' }, todayEvent ] wrapper.setProps({ events }) expect(wrapper.vm.eventsDateMatch(day)).toEqual([todayEvent]) }) it('emit rangeHoverEndDate', () => { wrapper.setProps({ range: true }) const thisMonth = new Date().getMonth() const day = newDate(2019, thisMonth, 6) wrapper.vm.setRangeHoverEndDate(day) expect(wrapper.emitted()['rangeHoverEndDate']).toBeTruthy() }) it('manage selectable dates as expected', () => { const day = newDate(2019, 7, 7) wrapper.setProps({ minDate: newDate(2019, 7, 17) }) expect(wrapper.vm.selectableDate(day)).toBeFalsy() wrapper.setProps({ minDate: null, maxDate: newDate(2019, 7, 1) }) expect(wrapper.vm.selectableDate(day)).toBeFalsy() wrapper.setProps({ minDate: null, maxDate: null, selectableDates: [newDate(2019, 7, 1), newDate(2019, 7, 2)] }) expect(wrapper.vm.selectableDate(day)).toBeFalsy() wrapper.setProps({ selectableDates: [newDate(2019, 7, 1), newDate(2019, 7, 2), day] }) expect(wrapper.vm.selectableDate(day)).toBeTruthy() wrapper.setProps({ minDate: null, maxDate: null, selectableDates: null, unselectableDates: [newDate(2019, 7, 1), newDate(2019, 7, 2)] }) expect(wrapper.vm.selectableDate(day)).toBeTruthy() wrapper.setProps({ unselectableDates: [day] }) expect(wrapper.vm.selectableDate(day)).toBeFalsy() wrapper.setProps({ minDate: null, maxDate: null, selectableDates: null, unselectableDates: null, unselectableDaysOfWeek: [0, 1] }) expect(wrapper.vm.selectableDate(day)).toBeTruthy() }) })