taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit d2f1cb3234cbeca88903efcfd0d7d406fbece53c
parent 5f996fedbc7542e1ba757a5a5856e43931ad7939
Author: Florian Dold <florian.dold@gmail.com>
Date:   Tue, 26 Jan 2016 17:21:17 +0100

fix #4153 and #0004154

Diffstat:
Mextension/.gitignore | 1+
Mextension/content_scripts/notify.js | 51++++++++++++++++++++++++++-------------------------
Mextension/content_scripts/notify.ts | 56+++++++++++++++++++++++++++++++-------------------------
Aextension/lib/module-trampoline.js | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dextension/lib/vendor/handlebars-v4.0.5.js | 4609-------------------------------------------------------------------------------
Mextension/lib/vendor/mithril.js | 2--
Aextension/lib/vendor/system-csp-production.src.js | 4156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dextension/lib/vendor/system.src.js | 4844-------------------------------------------------------------------------------
Mextension/lib/wallet/wallet.ts | 123++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mextension/lib/wallet/wxmessaging.js | 7+++++--
Mextension/lib/wallet/wxmessaging.ts | 21++++++++++++---------
Aextension/lib/web-common.ts | 22++++++++++++++++++++++
Mextension/manifest.json | 8+++-----
Mextension/pages/confirm-contract.html | 23++++++-----------------
Mextension/pages/confirm-contract.js | 90+++++++++++++++++++++++++++++++++++++++++++------------------------------------
Mextension/pages/confirm-contract.tsx | 79++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mextension/pages/confirm-create-reserve.html | 4++--
Mextension/pages/confirm-create-reserve.js | 46++++++++++++++++++++++++++--------------------
Mextension/pages/confirm-create-reserve.tsx | 40++++++++++++++++++----------------------
Mextension/popup/popup.html | 3++-
Mextension/popup/popup.tsx | 55+++++++++++++++++++++++++++++++++++++------------------
Mextension/tsconfig.json | 1+
22 files changed, 4565 insertions(+), 9745 deletions(-)

diff --git a/extension/.gitignore b/extension/.gitignore @@ -3,5 +3,6 @@ node_modules/ background/*.js lib/wallet/*.js lib/*.js +!lib/module-trampoline.js popup/*.js test/tests/*.js diff --git a/extension/content_scripts/notify.js b/extension/content_scripts/notify.js @@ -18,6 +18,11 @@ /// <reference path="../lib/decl/chrome/chrome.d.ts" /> "use strict"; console.log("Taler injected"); +function subst(url, H_contract) { + url = url.replace("${H_contract}", H_contract); + url = url.replace("${$}", "$"); + return url; +} document.addEventListener("taler-probe", function (e) { var evt = new Event("taler-wallet-present"); document.dispatchEvent(evt); @@ -55,10 +60,15 @@ document.addEventListener("taler-contract", function (e) { }); document.addEventListener('taler-execute-payment', function (e) { console.log("got taler-execute-payment in content page"); + if (!e.detail.pay_url) { + console.log("field 'pay_url' missing in taler-execute-payment event"); + return; + } + var payUrl = e.detail.pay_url; var msg = { type: "execute-payment", detail: { - H_contract: e.detail.H_contract + H_contract: e.detail.H_contract, }, }; chrome.runtime.sendMessage(msg, function (resp) { @@ -66,38 +76,29 @@ document.addEventListener('taler-execute-payment', function (e) { console.log("failure!"); return; } - console.log("Making request to ", resp.payUrl); + var contract = resp.contract; + if (!contract) { + throw Error("contract missing"); + } + var payReq = Object.assign({}, resp.payReq); + if (e.detail.require_contract) { + payReq.contract = contract; + } + console.log("Making request to ", payUrl); var r = new XMLHttpRequest(); - r.open('post', resp.payUrl); - r.send(JSON.stringify(resp.payReq)); - var detail = {}; - r.onload = function (e) { + r.open('post', payUrl); + r.send(JSON.stringify(payReq)); + r.onload = function () { switch (r.status) { case 200: - detail.success = true; - var respJson = JSON.parse(r.responseText); - console.log("respJson:", JSON.stringify(respJson)); - if (!respJson) { - console.log("Invalid JSON in response from $pay_url"); - detail.success = false; - break; - } - if (!respJson.fulfillment_url) { - console.log("Missing 'fulfillment_url' in response from $pay_url"); - detail.success = false; - break; - } - detail.fulfillmentUrl = respJson.fulfillment_url; + console.log("going to", contract.fulfillment_url); + window.location.href = subst(contract.fulfillment_url, e.detail.H_contract); + window.location.reload(true); break; default: console.log("Unexpected status code for $pay_url:", r.status); - detail.success = false; break; } - detail.status = r.status; - detail.responseText = r.responseText; - detail.fulfillmentUrl = - document.dispatchEvent(new CustomEvent("taler-payment-result", { detail: detail })); }; }); }); diff --git a/extension/content_scripts/notify.ts b/extension/content_scripts/notify.ts @@ -23,6 +23,13 @@ console.log("Taler injected"); +function subst(url: string, H_contract) { + url = url.replace("${H_contract}", H_contract); + url = url.replace("${$}", "$"); + return url; +} + + document.addEventListener("taler-probe", function(e) { let evt = new Event("taler-wallet-present"); document.dispatchEvent(evt); @@ -65,10 +72,15 @@ document.addEventListener("taler-contract", function(e: CustomEvent) { document.addEventListener('taler-execute-payment', function(e: CustomEvent) { console.log("got taler-execute-payment in content page"); + if (!e.detail.pay_url) { + console.log("field 'pay_url' missing in taler-execute-payment event"); + return; + } + let payUrl = e.detail.pay_url; let msg = { type: "execute-payment", detail: { - H_contract: e.detail.H_contract + H_contract: e.detail.H_contract, }, }; chrome.runtime.sendMessage(msg, (resp) => { @@ -76,38 +88,32 @@ document.addEventListener('taler-execute-payment', function(e: CustomEvent) { console.log("failure!"); return; } - console.log("Making request to ", resp.payUrl); + let contract = resp.contract; + if (!contract) { + throw Error("contract missing"); + } + + let payReq = Object.assign({}, resp.payReq); + if (e.detail.require_contract) { + payReq.contract = contract; + } + + console.log("Making request to ", payUrl); let r = new XMLHttpRequest(); - r.open('post', resp.payUrl); - r.send(JSON.stringify(resp.payReq)); - let detail: any = {}; - r.onload = (e) => { + r.open('post', payUrl); + r.send(JSON.stringify(payReq)); + r.onload = () => { switch (r.status) { case 200: - detail.success = true; - let respJson = JSON.parse(r.responseText); - console.log("respJson:", JSON.stringify(respJson)); - if (!respJson) { - console.log("Invalid JSON in response from $pay_url"); - detail.success = false; - break; - } - if (!respJson.fulfillment_url) { - console.log("Missing 'fulfillment_url' in response from $pay_url"); - detail.success = false; - break; - } - detail.fulfillmentUrl = respJson.fulfillment_url; + console.log("going to", contract.fulfillment_url); + window.location.href = subst(contract.fulfillment_url, + e.detail.H_contract); + window.location.reload(true); break; default: console.log("Unexpected status code for $pay_url:", r.status); - detail.success = false; break; } - detail.status = r.status; - detail.responseText = r.responseText; - detail.fulfillmentUrl = - document.dispatchEvent(new CustomEvent("taler-payment-result", {detail: detail})); }; }); }); \ No newline at end of file diff --git a/extension/lib/module-trampoline.js b/extension/lib/module-trampoline.js @@ -0,0 +1,68 @@ +/* + This file is part of TALER + (C) 2016 GNUnet e.V. + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, If not, see <http://www.gnu.org/licenses/> + */ + + +/** + * Boilerplate to initialize the module system and call main() + */ + +"use strict"; + +if (typeof System === "undefined") { + throw Error("system loader not present (must be included before the" + + " trampoline"); +} + +System.config({ + defaultJSExtensions: true, +}); + +let me = window.location.protocol + + "//" + window.location.host + + window.location.pathname.replace(/[.]html$/, ".js"); + +let domLoaded = false; + +document.addEventListener("DOMContentLoaded", function(event) { + domLoaded = true; +}); + +function execMain(m) { + if (m.main) { + console.log("executing module main"); + m.main(); + } else { + console.warn("module does not export a main() function"); + } +} + +console.log("loading", me); + +System.import(me) + .then((m) => { + console.log("module imported", me); + if (domLoaded) { + execMain(m); + return; + } + document.addEventListener("DOMContentLoaded", function(event) { + execMain(m); + }); + }) + .catch((e) => { + console.log("trampoline failed"); + console.error(e.stack); + }); +\ No newline at end of file diff --git a/extension/lib/vendor/handlebars-v4.0.5.js b/extension/lib/vendor/handlebars-v4.0.5.js @@ -1,4608 +0,0 @@ -/*! - - handlebars v4.0.5 - -Copyright (C) 2011-2015 by Yehuda Katz - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -@license -*/ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["Handlebars"] = factory(); - else - root["Handlebars"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.loaded = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - - var _handlebarsRuntime = __webpack_require__(2); - - var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime); - - // Compiler imports - - var _handlebarsCompilerAst = __webpack_require__(21); - - var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst); - - var _handlebarsCompilerBase = __webpack_require__(22); - - var _handlebarsCompilerCompiler = __webpack_require__(27); - - var _handlebarsCompilerJavascriptCompiler = __webpack_require__(28); - - var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler); - - var _handlebarsCompilerVisitor = __webpack_require__(25); - - var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor); - - var _handlebarsNoConflict = __webpack_require__(20); - - var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict); - - var _create = _handlebarsRuntime2['default'].create; - function create() { - var hb = _create(); - - hb.compile = function (input, options) { - return _handlebarsCompilerCompiler.compile(input, options, hb); - }; - hb.precompile = function (input, options) { - return _handlebarsCompilerCompiler.precompile(input, options, hb); - }; - - hb.AST = _handlebarsCompilerAst2['default']; - hb.Compiler = _handlebarsCompilerCompiler.Compiler; - hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default']; - hb.Parser = _handlebarsCompilerBase.parser; - hb.parse = _handlebarsCompilerBase.parse; - - return hb; - } - - var inst = create(); - inst.create = create; - - _handlebarsNoConflict2['default'](inst); - - inst.Visitor = _handlebarsCompilerVisitor2['default']; - - inst['default'] = inst; - - exports['default'] = inst; - module.exports = exports['default']; - -/***/ }, -/* 1 */ -/***/ function(module, exports) { - - "use strict"; - - exports["default"] = function (obj) { - return obj && obj.__esModule ? obj : { - "default": obj - }; - }; - - exports.__esModule = true; - -/***/ }, -/* 2 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireWildcard = __webpack_require__(3)['default']; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - - var _handlebarsBase = __webpack_require__(4); - - var base = _interopRequireWildcard(_handlebarsBase); - - // Each of these augment the Handlebars object. No need to setup here. - // (This is done to easily share code between commonjs and browse envs) - - var _handlebarsSafeString = __webpack_require__(18); - - var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString); - - var _handlebarsException = __webpack_require__(6); - - var _handlebarsException2 = _interopRequireDefault(_handlebarsException); - - var _handlebarsUtils = __webpack_require__(5); - - var Utils = _interopRequireWildcard(_handlebarsUtils); - - var _handlebarsRuntime = __webpack_require__(19); - - var runtime = _interopRequireWildcard(_handlebarsRuntime); - - var _handlebarsNoConflict = __webpack_require__(20); - - var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict); - - // For compatibility and usage outside of module systems, make the Handlebars object a namespace - function create() { - var hb = new base.HandlebarsEnvironment(); - - Utils.extend(hb, base); - hb.SafeString = _handlebarsSafeString2['default']; - hb.Exception = _handlebarsException2['default']; - hb.Utils = Utils; - hb.escapeExpression = Utils.escapeExpression; - - hb.VM = runtime; - hb.template = function (spec) { - return runtime.template(spec, hb); - }; - - return hb; - } - - var inst = create(); - inst.create = create; - - _handlebarsNoConflict2['default'](inst); - - inst['default'] = inst; - - exports['default'] = inst; - module.exports = exports['default']; - -/***/ }, -/* 3 */ -/***/ function(module, exports) { - - "use strict"; - - exports["default"] = function (obj) { - if (obj && obj.__esModule) { - return obj; - } else { - var newObj = {}; - - if (obj != null) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; - } - } - - newObj["default"] = obj; - return newObj; - } - }; - - exports.__esModule = true; - -/***/ }, -/* 4 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - exports.HandlebarsEnvironment = HandlebarsEnvironment; - - var _utils = __webpack_require__(5); - - var _exception = __webpack_require__(6); - - var _exception2 = _interopRequireDefault(_exception); - - var _helpers = __webpack_require__(7); - - var _decorators = __webpack_require__(15); - - var _logger = __webpack_require__(17); - - var _logger2 = _interopRequireDefault(_logger); - - var VERSION = '4.0.5'; - exports.VERSION = VERSION; - var COMPILER_REVISION = 7; - - exports.COMPILER_REVISION = COMPILER_REVISION; - var REVISION_CHANGES = { - 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it - 2: '== 1.0.0-rc.3', - 3: '== 1.0.0-rc.4', - 4: '== 1.x.x', - 5: '== 2.0.0-alpha.x', - 6: '>= 2.0.0-beta.1', - 7: '>= 4.0.0' - }; - - exports.REVISION_CHANGES = REVISION_CHANGES; - var objectType = '[object Object]'; - - function HandlebarsEnvironment(helpers, partials, decorators) { - this.helpers = helpers || {}; - this.partials = partials || {}; - this.decorators = decorators || {}; - - _helpers.registerDefaultHelpers(this); - _decorators.registerDefaultDecorators(this); - } - - HandlebarsEnvironment.prototype = { - constructor: HandlebarsEnvironment, - - logger: _logger2['default'], - log: _logger2['default'].log, - - registerHelper: function registerHelper(name, fn) { - if (_utils.toString.call(name) === objectType) { - if (fn) { - throw new _exception2['default']('Arg not supported with multiple helpers'); - } - _utils.extend(this.helpers, name); - } else { - this.helpers[name] = fn; - } - }, - unregisterHelper: function unregisterHelper(name) { - delete this.helpers[name]; - }, - - registerPartial: function registerPartial(name, partial) { - if (_utils.toString.call(name) === objectType) { - _utils.extend(this.partials, name); - } else { - if (typeof partial === 'undefined') { - throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined'); - } - this.partials[name] = partial; - } - }, - unregisterPartial: function unregisterPartial(name) { - delete this.partials[name]; - }, - - registerDecorator: function registerDecorator(name, fn) { - if (_utils.toString.call(name) === objectType) { - if (fn) { - throw new _exception2['default']('Arg not supported with multiple decorators'); - } - _utils.extend(this.decorators, name); - } else { - this.decorators[name] = fn; - } - }, - unregisterDecorator: function unregisterDecorator(name) { - delete this.decorators[name]; - } - }; - - var log = _logger2['default'].log; - - exports.log = log; - exports.createFrame = _utils.createFrame; - exports.logger = _logger2['default']; - -/***/ }, -/* 5 */ -/***/ function(module, exports) { - - 'use strict'; - - exports.__esModule = true; - exports.extend = extend; - exports.indexOf = indexOf; - exports.escapeExpression = escapeExpression; - exports.isEmpty = isEmpty; - exports.createFrame = createFrame; - exports.blockParams = blockParams; - exports.appendContextPath = appendContextPath; - var escape = { - '&': '&amp;', - '<': '&lt;', - '>': '&gt;', - '"': '&quot;', - "'": '&#x27;', - '`': '&#x60;', - '=': '&#x3D;' - }; - - var badChars = /[&<>"'`=]/g, - possible = /[&<>"'`=]/; - - function escapeChar(chr) { - return escape[chr]; - } - - function extend(obj /* , ...source */) { - for (var i = 1; i < arguments.length; i++) { - for (var key in arguments[i]) { - if (Object.prototype.hasOwnProperty.call(arguments[i], key)) { - obj[key] = arguments[i][key]; - } - } - } - - return obj; - } - - var toString = Object.prototype.toString; - - exports.toString = toString; - // Sourced from lodash - // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt - /* eslint-disable func-style */ - var isFunction = function isFunction(value) { - return typeof value === 'function'; - }; - // fallback for older versions of Chrome and Safari - /* istanbul ignore next */ - if (isFunction(/x/)) { - exports.isFunction = isFunction = function (value) { - return typeof value === 'function' && toString.call(value) === '[object Function]'; - }; - } - exports.isFunction = isFunction; - - /* eslint-enable func-style */ - - /* istanbul ignore next */ - var isArray = Array.isArray || function (value) { - return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false; - }; - - exports.isArray = isArray; - // Older IE versions do not directly support indexOf so we must implement our own, sadly. - - function indexOf(array, value) { - for (var i = 0, len = array.length; i < len; i++) { - if (array[i] === value) { - return i; - } - } - return -1; - } - - function escapeExpression(string) { - if (typeof string !== 'string') { - // don't escape SafeStrings, since they're already safe - if (string && string.toHTML) { - return string.toHTML(); - } else if (string == null) { - return ''; - } else if (!string) { - return string + ''; - } - - // Force a string conversion as this will be done by the append regardless and - // the regex test will do this transparently behind the scenes, causing issues if - // an object's to string has escaped characters in it. - string = '' + string; - } - - if (!possible.test(string)) { - return string; - } - return string.replace(badChars, escapeChar); - } - - function isEmpty(value) { - if (!value && value !== 0) { - return true; - } else if (isArray(value) && value.length === 0) { - return true; - } else { - return false; - } - } - - function createFrame(object) { - var frame = extend({}, object); - frame._parent = object; - return frame; - } - - function blockParams(params, ids) { - params.path = ids; - return params; - } - - function appendContextPath(contextPath, id) { - return (contextPath ? contextPath + '.' : '') + id; - } - -/***/ }, -/* 6 */ -/***/ function(module, exports) { - - 'use strict'; - - exports.__esModule = true; - - var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; - - function Exception(message, node) { - var loc = node && node.loc, - line = undefined, - column = undefined; - if (loc) { - line = loc.start.line; - column = loc.start.column; - - message += ' - ' + line + ':' + column; - } - - var tmp = Error.prototype.constructor.call(this, message); - - // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. - for (var idx = 0; idx < errorProps.length; idx++) { - this[errorProps[idx]] = tmp[errorProps[idx]]; - } - - /* istanbul ignore else */ - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Exception); - } - - if (loc) { - this.lineNumber = line; - this.column = column; - } - } - - Exception.prototype = new Error(); - - exports['default'] = Exception; - module.exports = exports['default']; - -/***/ }, -/* 7 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - exports.registerDefaultHelpers = registerDefaultHelpers; - - var _helpersBlockHelperMissing = __webpack_require__(8); - - var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing); - - var _helpersEach = __webpack_require__(9); - - var _helpersEach2 = _interopRequireDefault(_helpersEach); - - var _helpersHelperMissing = __webpack_require__(10); - - var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing); - - var _helpersIf = __webpack_require__(11); - - var _helpersIf2 = _interopRequireDefault(_helpersIf); - - var _helpersLog = __webpack_require__(12); - - var _helpersLog2 = _interopRequireDefault(_helpersLog); - - var _helpersLookup = __webpack_require__(13); - - var _helpersLookup2 = _interopRequireDefault(_helpersLookup); - - var _helpersWith = __webpack_require__(14); - - var _helpersWith2 = _interopRequireDefault(_helpersWith); - - function registerDefaultHelpers(instance) { - _helpersBlockHelperMissing2['default'](instance); - _helpersEach2['default'](instance); - _helpersHelperMissing2['default'](instance); - _helpersIf2['default'](instance); - _helpersLog2['default'](instance); - _helpersLookup2['default'](instance); - _helpersWith2['default'](instance); - } - -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.__esModule = true; - - var _utils = __webpack_require__(5); - - exports['default'] = function (instance) { - instance.registerHelper('blockHelperMissing', function (context, options) { - var inverse = options.inverse, - fn = options.fn; - - if (context === true) { - return fn(this); - } else if (context === false || context == null) { - return inverse(this); - } else if (_utils.isArray(context)) { - if (context.length > 0) { - if (options.ids) { - options.ids = [options.name]; - } - - return instance.helpers.each(context, options); - } else { - return inverse(this); - } - } else { - if (options.data && options.ids) { - var data = _utils.createFrame(options.data); - data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name); - options = { data: data }; - } - - return fn(context, options); - } - }); - }; - - module.exports = exports['default']; - -/***/ }, -/* 9 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - - var _utils = __webpack_require__(5); - - var _exception = __webpack_require__(6); - - var _exception2 = _interopRequireDefault(_exception); - - exports['default'] = function (instance) { - instance.registerHelper('each', function (context, options) { - if (!options) { - throw new _exception2['default']('Must pass iterator to #each'); - } - - var fn = options.fn, - inverse = options.inverse, - i = 0, - ret = '', - data = undefined, - contextPath = undefined; - - if (options.data && options.ids) { - contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.'; - } - - if (_utils.isFunction(context)) { - context = context.call(this); - } - - if (options.data) { - data = _utils.createFrame(options.data); - } - - function execIteration(field, index, last) { - if (data) { - data.key = field; - data.index = index; - data.first = index === 0; - data.last = !!last; - - if (contextPath) { - data.contextPath = contextPath + field; - } - } - - ret = ret + fn(context[field], { - data: data, - blockParams: _utils.blockParams([context[field], field], [contextPath + field, null]) - }); - } - - if (context && typeof context === 'object') { - if (_utils.isArray(context)) { - for (var j = context.length; i < j; i++) { - if (i in context) { - execIteration(i, i, i === context.length - 1); - } - } - } else { - var priorKey = undefined; - - for (var key in context) { - if (context.hasOwnProperty(key)) { - // We're running the iterations one step out of sync so we can detect - // the last iteration without have to scan the object twice and create - // an itermediate keys array. - if (priorKey !== undefined) { - execIteration(priorKey, i - 1); - } - priorKey = key; - i++; - } - } - if (priorKey !== undefined) { - execIteration(priorKey, i - 1, true); - } - } - } - - if (i === 0) { - ret = inverse(this); - } - - return ret; - }); - }; - - module.exports = exports['default']; - -/***/ }, -/* 10 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - - var _exception = __webpack_require__(6); - - var _exception2 = _interopRequireDefault(_exception); - - exports['default'] = function (instance) { - instance.registerHelper('helperMissing', function () /* [args, ]options */{ - if (arguments.length === 1) { - // A missing field in a {{foo}} construct. - return undefined; - } else { - // Someone is actually trying to call something, blow up. - throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"'); - } - }); - }; - - module.exports = exports['default']; - -/***/ }, -/* 11 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.__esModule = true; - - var _utils = __webpack_require__(5); - - exports['default'] = function (instance) { - instance.registerHelper('if', function (conditional, options) { - if (_utils.isFunction(conditional)) { - conditional = conditional.call(this); - } - - // Default behavior is to render the positive path if the value is truthy and not empty. - // The `includeZero` option may be set to treat the condtional as purely not empty based on the - // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative. - if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) { - return options.inverse(this); - } else { - return options.fn(this); - } - }); - - instance.registerHelper('unless', function (conditional, options) { - return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash }); - }); - }; - - module.exports = exports['default']; - -/***/ }, -/* 12 */ -/***/ function(module, exports) { - - 'use strict'; - - exports.__esModule = true; - - exports['default'] = function (instance) { - instance.registerHelper('log', function () /* message, options */{ - var args = [undefined], - options = arguments[arguments.length - 1]; - for (var i = 0; i < arguments.length - 1; i++) { - args.push(arguments[i]); - } - - var level = 1; - if (options.hash.level != null) { - level = options.hash.level; - } else if (options.data && options.data.level != null) { - level = options.data.level; - } - args[0] = level; - - instance.log.apply(instance, args); - }); - }; - - module.exports = exports['default']; - -/***/ }, -/* 13 */ -/***/ function(module, exports) { - - 'use strict'; - - exports.__esModule = true; - - exports['default'] = function (instance) { - instance.registerHelper('lookup', function (obj, field) { - return obj && obj[field]; - }); - }; - - module.exports = exports['default']; - -/***/ }, -/* 14 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.__esModule = true; - - var _utils = __webpack_require__(5); - - exports['default'] = function (instance) { - instance.registerHelper('with', function (context, options) { - if (_utils.isFunction(context)) { - context = context.call(this); - } - - var fn = options.fn; - - if (!_utils.isEmpty(context)) { - var data = options.data; - if (options.data && options.ids) { - data = _utils.createFrame(options.data); - data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]); - } - - return fn(context, { - data: data, - blockParams: _utils.blockParams([context], [data && data.contextPath]) - }); - } else { - return options.inverse(this); - } - }); - }; - - module.exports = exports['default']; - -/***/ }, -/* 15 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - exports.registerDefaultDecorators = registerDefaultDecorators; - - var _decoratorsInline = __webpack_require__(16); - - var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline); - - function registerDefaultDecorators(instance) { - _decoratorsInline2['default'](instance); - } - -/***/ }, -/* 16 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.__esModule = true; - - var _utils = __webpack_require__(5); - - exports['default'] = function (instance) { - instance.registerDecorator('inline', function (fn, props, container, options) { - var ret = fn; - if (!props.partials) { - props.partials = {}; - ret = function (context, options) { - // Create a new partials stack frame prior to exec. - var original = container.partials; - container.partials = _utils.extend({}, original, props.partials); - var ret = fn(context, options); - container.partials = original; - return ret; - }; - } - - props.partials[options.args[0]] = options.fn; - - return ret; - }); - }; - - module.exports = exports['default']; - -/***/ }, -/* 17 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.__esModule = true; - - var _utils = __webpack_require__(5); - - var logger = { - methodMap: ['debug', 'info', 'warn', 'error'], - level: 'info', - - // Maps a given level value to the `methodMap` indexes above. - lookupLevel: function lookupLevel(level) { - if (typeof level === 'string') { - var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase()); - if (levelMap >= 0) { - level = levelMap; - } else { - level = parseInt(level, 10); - } - } - - return level; - }, - - // Can be overridden in the host environment - log: function log(level) { - level = logger.lookupLevel(level); - - if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) { - var method = logger.methodMap[level]; - if (!console[method]) { - // eslint-disable-line no-console - method = 'log'; - } - - for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - message[_key - 1] = arguments[_key]; - } - - console[method].apply(console, message); // eslint-disable-line no-console - } - } - }; - - exports['default'] = logger; - module.exports = exports['default']; - -/***/ }, -/* 18 */ -/***/ function(module, exports) { - - // Build out our basic SafeString type - 'use strict'; - - exports.__esModule = true; - function SafeString(string) { - this.string = string; - } - - SafeString.prototype.toString = SafeString.prototype.toHTML = function () { - return '' + this.string; - }; - - exports['default'] = SafeString; - module.exports = exports['default']; - -/***/ }, -/* 19 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireWildcard = __webpack_require__(3)['default']; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - exports.checkRevision = checkRevision; - exports.template = template; - exports.wrapProgram = wrapProgram; - exports.resolvePartial = resolvePartial; - exports.invokePartial = invokePartial; - exports.noop = noop; - - var _utils = __webpack_require__(5); - - var Utils = _interopRequireWildcard(_utils); - - var _exception = __webpack_require__(6); - - var _exception2 = _interopRequireDefault(_exception); - - var _base = __webpack_require__(4); - - function checkRevision(compilerInfo) { - var compilerRevision = compilerInfo && compilerInfo[0] || 1, - currentRevision = _base.COMPILER_REVISION; - - if (compilerRevision !== currentRevision) { - if (compilerRevision < currentRevision) { - var runtimeVersions = _base.REVISION_CHANGES[currentRevision], - compilerVersions = _base.REVISION_CHANGES[compilerRevision]; - throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').'); - } else { - // Use the embedded version info since the runtime doesn't know about this revision yet - throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').'); - } - } - } - - function template(templateSpec, env) { - /* istanbul ignore next */ - if (!env) { - throw new _exception2['default']('No environment passed to template'); - } - if (!templateSpec || !templateSpec.main) { - throw new _exception2['default']('Unknown template object: ' + typeof templateSpec); - } - - templateSpec.main.decorator = templateSpec.main_d; - - // Note: Using env.VM references rather than local var references throughout this section to allow - // for external users to override these as psuedo-supported APIs. - env.VM.checkRevision(templateSpec.compiler); - - function invokePartialWrapper(partial, context, options) { - if (options.hash) { - context = Utils.extend({}, context, options.hash); - if (options.ids) { - options.ids[0] = true; - } - } - - partial = env.VM.resolvePartial.call(this, partial, context, options); - var result = env.VM.invokePartial.call(this, partial, context, options); - - if (result == null && env.compile) { - options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env); - result = options.partials[options.name](context, options); - } - if (result != null) { - if (options.indent) { - var lines = result.split('\n'); - for (var i = 0, l = lines.length; i < l; i++) { - if (!lines[i] && i + 1 === l) { - break; - } - - lines[i] = options.indent + lines[i]; - } - result = lines.join('\n'); - } - return result; - } else { - throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode'); - } - } - - // Just add water - var container = { - strict: function strict(obj, name) { - if (!(name in obj)) { - throw new _exception2['default']('"' + name + '" not defined in ' + obj); - } - return obj[name]; - }, - lookup: function lookup(depths, name) { - var len = depths.length; - for (var i = 0; i < len; i++) { - if (depths[i] && depths[i][name] != null) { - return depths[i][name]; - } - } - }, - lambda: function lambda(current, context) { - return typeof current === 'function' ? current.call(context) : current; - }, - - escapeExpression: Utils.escapeExpression, - invokePartial: invokePartialWrapper, - - fn: function fn(i) { - var ret = templateSpec[i]; - ret.decorator = templateSpec[i + '_d']; - return ret; - }, - - programs: [], - program: function program(i, data, declaredBlockParams, blockParams, depths) { - var programWrapper = this.programs[i], - fn = this.fn(i); - if (data || depths || blockParams || declaredBlockParams) { - programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths); - } else if (!programWrapper) { - programWrapper = this.programs[i] = wrapProgram(this, i, fn); - } - return programWrapper; - }, - - data: function data(value, depth) { - while (value && depth--) { - value = value._parent; - } - return value; - }, - merge: function merge(param, common) { - var obj = param || common; - - if (param && common && param !== common) { - obj = Utils.extend({}, common, param); - } - - return obj; - }, - - noop: env.VM.noop, - compilerInfo: templateSpec.compiler - }; - - function ret(context) { - var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; - - var data = options.data; - - ret._setup(options); - if (!options.partial && templateSpec.useData) { - data = initData(context, data); - } - var depths = undefined, - blockParams = templateSpec.useBlockParams ? [] : undefined; - if (templateSpec.useDepths) { - if (options.depths) { - depths = context !== options.depths[0] ? [context].concat(options.depths) : options.depths; - } else { - depths = [context]; - } - } - - function main(context /*, options*/) { - return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths); - } - main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams); - return main(context, options); - } - ret.isTop = true; - - ret._setup = function (options) { - if (!options.partial) { - container.helpers = container.merge(options.helpers, env.helpers); - - if (templateSpec.usePartial) { - container.partials = container.merge(options.partials, env.partials); - } - if (templateSpec.usePartial || templateSpec.useDecorators) { - container.decorators = container.merge(options.decorators, env.decorators); - } - } else { - container.helpers = options.helpers; - container.partials = options.partials; - container.decorators = options.decorators; - } - }; - - ret._child = function (i, data, blockParams, depths) { - if (templateSpec.useBlockParams && !blockParams) { - throw new _exception2['default']('must pass block params'); - } - if (templateSpec.useDepths && !depths) { - throw new _exception2['default']('must pass parent depths'); - } - - return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths); - }; - return ret; - } - - function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) { - function prog(context) { - var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; - - var currentDepths = depths; - if (depths && context !== depths[0]) { - currentDepths = [context].concat(depths); - } - - return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths); - } - - prog = executeDecorators(fn, prog, container, depths, data, blockParams); - - prog.program = i; - prog.depth = depths ? depths.length : 0; - prog.blockParams = declaredBlockParams || 0; - return prog; - } - - function resolvePartial(partial, context, options) { - if (!partial) { - if (options.name === '@partial-block') { - partial = options.data['partial-block']; - } else { - partial = options.partials[options.name]; - } - } else if (!partial.call && !options.name) { - // This is a dynamic partial that returned a string - options.name = partial; - partial = options.partials[partial]; - } - return partial; - } - - function invokePartial(partial, context, options) { - options.partial = true; - if (options.ids) { - options.data.contextPath = options.ids[0] || options.data.contextPath; - } - - var partialBlock = undefined; - if (options.fn && options.fn !== noop) { - options.data = _base.createFrame(options.data); - partialBlock = options.data['partial-block'] = options.fn; - - if (partialBlock.partials) { - options.partials = Utils.extend({}, options.partials, partialBlock.partials); - } - } - - if (partial === undefined && partialBlock) { - partial = partialBlock; - } - - if (partial === undefined) { - throw new _exception2['default']('The partial ' + options.name + ' could not be found'); - } else if (partial instanceof Function) { - return partial(context, options); - } - } - - function noop() { - return ''; - } - - function initData(context, data) { - if (!data || !('root' in data)) { - data = data ? _base.createFrame(data) : {}; - data.root = context; - } - return data; - } - - function executeDecorators(fn, prog, container, depths, data, blockParams) { - if (fn.decorator) { - var props = {}; - prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths); - Utils.extend(prog, props); - } - return prog; - } - -/***/ }, -/* 20 */ -/***/ function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {/* global window */ - 'use strict'; - - exports.__esModule = true; - - exports['default'] = function (Handlebars) { - /* istanbul ignore next */ - var root = typeof global !== 'undefined' ? global : window, - $Handlebars = root.Handlebars; - /* istanbul ignore next */ - Handlebars.noConflict = function () { - if (root.Handlebars === Handlebars) { - root.Handlebars = $Handlebars; - } - return Handlebars; - }; - }; - - module.exports = exports['default']; - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }, -/* 21 */ -/***/ function(module, exports) { - - 'use strict'; - - exports.__esModule = true; - var AST = { - // Public API used to evaluate derived attributes regarding AST nodes - helpers: { - // a mustache is definitely a helper if: - // * it is an eligible helper, and - // * it has at least one parameter or hash segment - helperExpression: function helperExpression(node) { - return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash); - }, - - scopedId: function scopedId(path) { - return (/^\.|this\b/.test(path.original) - ); - }, - - // an ID is simple if it only has one part, and that part is not - // `..` or `this`. - simpleId: function simpleId(path) { - return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth; - } - } - }; - - // Must be exported as an object rather than the root of the module as the jison lexer - // must modify the object to operate properly. - exports['default'] = AST; - module.exports = exports['default']; - -/***/ }, -/* 22 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - var _interopRequireWildcard = __webpack_require__(3)['default']; - - exports.__esModule = true; - exports.parse = parse; - - var _parser = __webpack_require__(23); - - var _parser2 = _interopRequireDefault(_parser); - - var _whitespaceControl = __webpack_require__(24); - - var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl); - - var _helpers = __webpack_require__(26); - - var Helpers = _interopRequireWildcard(_helpers); - - var _utils = __webpack_require__(5); - - exports.parser = _parser2['default']; - - var yy = {}; - _utils.extend(yy, Helpers); - - function parse(input, options) { - // Just return if an already-compiled AST was passed in. - if (input.type === 'Program') { - return input; - } - - _parser2['default'].yy = yy; - - // Altering the shared object here, but this is ok as parser is a sync operation - yy.locInfo = function (locInfo) { - return new yy.SourceLocation(options && options.srcName, locInfo); - }; - - var strip = new _whitespaceControl2['default'](options); - return strip.accept(_parser2['default'].parse(input)); - } - -/***/ }, -/* 23 */ -/***/ function(module, exports) { - - /* istanbul ignore next */ - /* Jison generated parser */ - "use strict"; - - var handlebars = (function () { - var parser = { trace: function trace() {}, - yy: {}, - symbols_: { "error": 2, "root": 3, "program": 4, "EOF": 5, "program_repetition0": 6, "statement": 7, "mustache": 8, "block": 9, "rawBlock": 10, "partial": 11, "partialBlock": 12, "content": 13, "COMMENT": 14, "CONTENT": 15, "openRawBlock": 16, "rawBlock_repetition_plus0": 17, "END_RAW_BLOCK": 18, "OPEN_RAW_BLOCK": 19, "helperName": 20, "openRawBlock_repetition0": 21, "openRawBlock_option0": 22, "CLOSE_RAW_BLOCK": 23, "openBlock": 24, "block_option0": 25, "closeBlock": 26, "openInverse": 27, "block_option1": 28, "OPEN_BLOCK": 29, "openBlock_repetition0": 30, "openBlock_option0": 31, "openBlock_option1": 32, "CLOSE": 33, "OPEN_INVERSE": 34, "openInverse_repetition0": 35, "openInverse_option0": 36, "openInverse_option1": 37, "openInverseChain": 38, "OPEN_INVERSE_CHAIN": 39, "openInverseChain_repetition0": 40, "openInverseChain_option0": 41, "openInverseChain_option1": 42, "inverseAndProgram": 43, "INVERSE": 44, "inverseChain": 45, "inverseChain_option0": 46, "OPEN_ENDBLOCK": 47, "OPEN": 48, "mustache_repetition0": 49, "mustache_option0": 50, "OPEN_UNESCAPED": 51, "mustache_repetition1": 52, "mustache_option1": 53, "CLOSE_UNESCAPED": 54, "OPEN_PARTIAL": 55, "partialName": 56, "partial_repetition0": 57, "partial_option0": 58, "openPartialBlock": 59, "OPEN_PARTIAL_BLOCK": 60, "openPartialBlock_repetition0": 61, "openPartialBlock_option0": 62, "param": 63, "sexpr": 64, "OPEN_SEXPR": 65, "sexpr_repetition0": 66, "sexpr_option0": 67, "CLOSE_SEXPR": 68, "hash": 69, "hash_repetition_plus0": 70, "hashSegment": 71, "ID": 72, "EQUALS": 73, "blockParams": 74, "OPEN_BLOCK_PARAMS": 75, "blockParams_repetition_plus0": 76, "CLOSE_BLOCK_PARAMS": 77, "path": 78, "dataName": 79, "STRING": 80, "NUMBER": 81, "BOOLEAN": 82, "UNDEFINED": 83, "NULL": 84, "DATA": 85, "pathSegments": 86, "SEP": 87, "$accept": 0, "$end": 1 }, - terminals_: { 2: "error", 5: "EOF", 14: "COMMENT", 15: "CONTENT", 18: "END_RAW_BLOCK", 19: "OPEN_RAW_BLOCK", 23: "CLOSE_RAW_BLOCK", 29: "OPEN_BLOCK", 33: "CLOSE", 34: "OPEN_INVERSE", 39: "OPEN_INVERSE_CHAIN", 44: "INVERSE", 47: "OPEN_ENDBLOCK", 48: "OPEN", 51: "OPEN_UNESCAPED", 54: "CLOSE_UNESCAPED", 55: "OPEN_PARTIAL", 60: "OPEN_PARTIAL_BLOCK", 65: "OPEN_SEXPR", 68: "CLOSE_SEXPR", 72: "ID", 73: "EQUALS", 75: "OPEN_BLOCK_PARAMS", 77: "CLOSE_BLOCK_PARAMS", 80: "STRING", 81: "NUMBER", 82: "BOOLEAN", 83: "UNDEFINED", 84: "NULL", 85: "DATA", 87: "SEP" }, - productions_: [0, [3, 2], [4, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [13, 1], [10, 3], [16, 5], [9, 4], [9, 4], [24, 6], [27, 6], [38, 6], [43, 2], [45, 3], [45, 1], [26, 3], [8, 5], [8, 5], [11, 5], [12, 3], [59, 5], [63, 1], [63, 1], [64, 5], [69, 1], [71, 3], [74, 3], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [56, 1], [56, 1], [79, 2], [78, 1], [86, 3], [86, 1], [6, 0], [6, 2], [17, 1], [17, 2], [21, 0], [21, 2], [22, 0], [22, 1], [25, 0], [25, 1], [28, 0], [28, 1], [30, 0], [30, 2], [31, 0], [31, 1], [32, 0], [32, 1], [35, 0], [35, 2], [36, 0], [36, 1], [37, 0], [37, 1], [40, 0], [40, 2], [41, 0], [41, 1], [42, 0], [42, 1], [46, 0], [46, 1], [49, 0], [49, 2], [50, 0], [50, 1], [52, 0], [52, 2], [53, 0], [53, 1], [57, 0], [57, 2], [58, 0], [58, 1], [61, 0], [61, 2], [62, 0], [62, 1], [66, 0], [66, 2], [67, 0], [67, 1], [70, 1], [70, 2], [76, 1], [76, 2]], - performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$ - /**/) { - - var $0 = $$.length - 1; - switch (yystate) { - case 1: - return $$[$0 - 1]; - break; - case 2: - this.$ = yy.prepareProgram($$[$0]); - break; - case 3: - this.$ = $$[$0]; - break; - case 4: - this.$ = $$[$0]; - break; - case 5: - this.$ = $$[$0]; - break; - case 6: - this.$ = $$[$0]; - break; - case 7: - this.$ = $$[$0]; - break; - case 8: - this.$ = $$[$0]; - break; - case 9: - this.$ = { - type: 'CommentStatement', - value: yy.stripComment($$[$0]), - strip: yy.stripFlags($$[$0], $$[$0]), - loc: yy.locInfo(this._$) - }; - - break; - case 10: - this.$ = { - type: 'ContentStatement', - original: $$[$0], - value: $$[$0], - loc: yy.locInfo(this._$) - }; - - break; - case 11: - this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); - break; - case 12: - this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] }; - break; - case 13: - this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$); - break; - case 14: - this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$); - break; - case 15: - this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; - break; - case 16: - this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; - break; - case 17: - this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; - break; - case 18: - this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] }; - break; - case 19: - var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$), - program = yy.prepareProgram([inverse], $$[$0 - 1].loc); - program.chained = true; - - this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true }; - - break; - case 20: - this.$ = $$[$0]; - break; - case 21: - this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) }; - break; - case 22: - this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); - break; - case 23: - this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); - break; - case 24: - this.$ = { - type: 'PartialStatement', - name: $$[$0 - 3], - params: $$[$0 - 2], - hash: $$[$0 - 1], - indent: '', - strip: yy.stripFlags($$[$0 - 4], $$[$0]), - loc: yy.locInfo(this._$) - }; - - break; - case 25: - this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); - break; - case 26: - this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) }; - break; - case 27: - this.$ = $$[$0]; - break; - case 28: - this.$ = $$[$0]; - break; - case 29: - this.$ = { - type: 'SubExpression', - path: $$[$0 - 3], - params: $$[$0 - 2], - hash: $$[$0 - 1], - loc: yy.locInfo(this._$) - }; - - break; - case 30: - this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) }; - break; - case 31: - this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) }; - break; - case 32: - this.$ = yy.id($$[$0 - 1]); - break; - case 33: - this.$ = $$[$0]; - break; - case 34: - this.$ = $$[$0]; - break; - case 35: - this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) }; - break; - case 36: - this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) }; - break; - case 37: - this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) }; - break; - case 38: - this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) }; - break; - case 39: - this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) }; - break; - case 40: - this.$ = $$[$0]; - break; - case 41: - this.$ = $$[$0]; - break; - case 42: - this.$ = yy.preparePath(true, $$[$0], this._$); - break; - case 43: - this.$ = yy.preparePath(false, $$[$0], this._$); - break; - case 44: - $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2]; - break; - case 45: - this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }]; - break; - case 46: - this.$ = []; - break; - case 47: - $$[$0 - 1].push($$[$0]); - break; - case 48: - this.$ = [$$[$0]]; - break; - case 49: - $$[$0 - 1].push($$[$0]); - break; - case 50: - this.$ = []; - break; - case 51: - $$[$0 - 1].push($$[$0]); - break; - case 58: - this.$ = []; - break; - case 59: - $$[$0 - 1].push($$[$0]); - break; - case 64: - this.$ = []; - break; - case 65: - $$[$0 - 1].push($$[$0]); - break; - case 70: - this.$ = []; - break; - case 71: - $$[$0 - 1].push($$[$0]); - break; - case 78: - this.$ = []; - break; - case 79: - $$[$0 - 1].push($$[$0]); - break; - case 82: - this.$ = []; - break; - case 83: - $$[$0 - 1].push($$[$0]); - break; - case 86: - this.$ = []; - break; - case 87: - $$[$0 - 1].push($$[$0]); - break; - case 90: - this.$ = []; - break; - case 91: - $$[$0 - 1].push($$[$0]); - break; - case 94: - this.$ = []; - break; - case 95: - $$[$0 - 1].push($$[$0]); - break; - case 98: - this.$ = [$$[$0]]; - break; - case 99: - $$[$0 - 1].push($$[$0]); - break; - case 100: - this.$ = [$$[$0]]; - break; - case 101: - $$[$0 - 1].push($$[$0]); - break; - } - }, - table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 13: 40, 15: [1, 20], 17: 39 }, { 20: 42, 56: 41, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 45, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 48, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 42, 56: 49, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 50, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 51] }, { 72: [1, 35], 86: 52 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 53, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 54, 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 55, 47: [2, 54] }, { 28: 60, 43: 61, 44: [1, 59], 47: [2, 56] }, { 13: 63, 15: [1, 20], 18: [1, 62] }, { 15: [2, 48], 18: [2, 48] }, { 33: [2, 86], 57: 64, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 65, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 66, 47: [1, 67] }, { 30: 68, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 69, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 70, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 71, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 75, 33: [2, 80], 50: 72, 63: 73, 64: 76, 65: [1, 44], 69: 74, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 80] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 51] }, { 20: 75, 53: 81, 54: [2, 84], 63: 82, 64: 76, 65: [1, 44], 69: 83, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 84, 47: [1, 67] }, { 47: [2, 55] }, { 4: 85, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 86, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 87, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 88, 47: [1, 67] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 75, 33: [2, 88], 58: 89, 63: 90, 64: 76, 65: [1, 44], 69: 91, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 92, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 93, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 31: 94, 33: [2, 60], 63: 95, 64: 76, 65: [1, 44], 69: 96, 70: 77, 71: 78, 72: [1, 79], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 66], 36: 97, 63: 98, 64: 76, 65: [1, 44], 69: 99, 70: 77, 71: 78, 72: [1, 79], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 22: 100, 23: [2, 52], 63: 101, 64: 76, 65: [1, 44], 69: 102, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 92], 62: 103, 63: 104, 64: 76, 65: [1, 44], 69: 105, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 106] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 107, 72: [1, 108], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 109], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 110] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 112, 46: 111, 47: [2, 76] }, { 33: [2, 70], 40: 113, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 114] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 75, 63: 116, 64: 76, 65: [1, 44], 67: 115, 68: [2, 96], 69: 117, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 118] }, { 32: 119, 33: [2, 62], 74: 120, 75: [1, 121] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 122, 74: 123, 75: [1, 121] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 124] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 125] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 109] }, { 20: 75, 63: 126, 64: 76, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 75, 33: [2, 72], 41: 127, 63: 128, 64: 76, 65: [1, 44], 69: 129, 70: 77, 71: 78, 72: [1, 79], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 130] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 131] }, { 33: [2, 63] }, { 72: [1, 133], 76: 132 }, { 33: [1, 134] }, { 33: [2, 69] }, { 15: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 135, 74: 136, 75: [1, 121] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 138], 77: [1, 137] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 139] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }], - defaultActions: { 4: [2, 1], 55: [2, 55], 57: [2, 20], 61: [2, 57], 74: [2, 81], 83: [2, 85], 87: [2, 18], 91: [2, 89], 102: [2, 53], 105: [2, 93], 111: [2, 19], 112: [2, 77], 117: [2, 97], 120: [2, 63], 123: [2, 69], 124: [2, 12], 136: [2, 75], 137: [2, 32] }, - parseError: function parseError(str, hash) { - throw new Error(str); - }, - parse: function parse(input) { - var self = this, - stack = [0], - vstack = [null], - lstack = [], - table = this.table, - yytext = "", - yylineno = 0, - yyleng = 0, - recovering = 0, - TERROR = 2, - EOF = 1; - this.lexer.setInput(input); - this.lexer.yy = this.yy; - this.yy.lexer = this.lexer; - this.yy.parser = this; - if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; - var yyloc = this.lexer.yylloc; - lstack.push(yyloc); - var ranges = this.lexer.options && this.lexer.options.ranges; - if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; - function popStack(n) { - stack.length = stack.length - 2 * n; - vstack.length = vstack.length - n; - lstack.length = lstack.length - n; - } - function lex() { - var token; - token = self.lexer.lex() || 1; - if (typeof token !== "number") { - token = self.symbols_[token] || token; - } - return token; - } - var symbol, - preErrorSymbol, - state, - action, - a, - r, - yyval = {}, - p, - len, - newState, - expected; - while (true) { - state = stack[stack.length - 1]; - if (this.defaultActions[state]) { - action = this.defaultActions[state]; - } else { - if (symbol === null || typeof symbol == "undefined") { - symbol = lex(); - } - action = table[state] && table[state][symbol]; - } - if (typeof action === "undefined" || !action.length || !action[0]) { - var errStr = ""; - if (!recovering) { - expected = []; - for (p in table[state]) if (this.terminals_[p] && p > 2) { - expected.push("'" + this.terminals_[p] + "'"); - } - if (this.lexer.showPosition) { - errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; - } else { - errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'"); - } - this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected }); - } - } - if (action[0] instanceof Array && action.length > 1) { - throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); - } - switch (action[0]) { - case 1: - stack.push(symbol); - vstack.push(this.lexer.yytext); - lstack.push(this.lexer.yylloc); - stack.push(action[1]); - symbol = null; - if (!preErrorSymbol) { - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - if (recovering > 0) recovering--; - } else { - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - case 2: - len = this.productions_[action[1]][1]; - yyval.$ = vstack[vstack.length - len]; - yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column }; - if (ranges) { - yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; - } - r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); - if (typeof r !== "undefined") { - return r; - } - if (len) { - stack = stack.slice(0, -1 * len * 2); - vstack = vstack.slice(0, -1 * len); - lstack = lstack.slice(0, -1 * len); - } - stack.push(this.productions_[action[1]][0]); - vstack.push(yyval.$); - lstack.push(yyval._$); - newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; - stack.push(newState); - break; - case 3: - return true; - } - } - return true; - } - }; - /* Jison generated lexer */ - var lexer = (function () { - var lexer = { EOF: 1, - parseError: function parseError(str, hash) { - if (this.yy.parser) { - this.yy.parser.parseError(str, hash); - } else { - throw new Error(str); - } - }, - setInput: function setInput(input) { - this._input = input; - this._more = this._less = this.done = false; - this.yylineno = this.yyleng = 0; - this.yytext = this.matched = this.match = ''; - this.conditionStack = ['INITIAL']; - this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 }; - if (this.options.ranges) this.yylloc.range = [0, 0]; - this.offset = 0; - return this; - }, - input: function input() { - var ch = this._input[0]; - this.yytext += ch; - this.yyleng++; - this.offset++; - this.match += ch; - this.matched += ch; - var lines = ch.match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno++; - this.yylloc.last_line++; - } else { - this.yylloc.last_column++; - } - if (this.options.ranges) this.yylloc.range[1]++; - - this._input = this._input.slice(1); - return ch; - }, - unput: function unput(ch) { - var len = ch.length; - var lines = ch.split(/(?:\r\n?|\n)/g); - - this._input = ch + this._input; - this.yytext = this.yytext.substr(0, this.yytext.length - len - 1); - //this.yyleng -= len; - this.offset -= len; - var oldLines = this.match.split(/(?:\r\n?|\n)/g); - this.match = this.match.substr(0, this.match.length - 1); - this.matched = this.matched.substr(0, this.matched.length - 1); - - if (lines.length - 1) this.yylineno -= lines.length - 1; - var r = this.yylloc.range; - - this.yylloc = { first_line: this.yylloc.first_line, - last_line: this.yylineno + 1, - first_column: this.yylloc.first_column, - last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len - }; - - if (this.options.ranges) { - this.yylloc.range = [r[0], r[0] + this.yyleng - len]; - } - return this; - }, - more: function more() { - this._more = true; - return this; - }, - less: function less(n) { - this.unput(this.match.slice(n)); - }, - pastInput: function pastInput() { - var past = this.matched.substr(0, this.matched.length - this.match.length); - return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, ""); - }, - upcomingInput: function upcomingInput() { - var next = this.match; - if (next.length < 20) { - next += this._input.substr(0, 20 - next.length); - } - return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); - }, - showPosition: function showPosition() { - var pre = this.pastInput(); - var c = new Array(pre.length + 1).join("-"); - return pre + this.upcomingInput() + "\n" + c + "^"; - }, - next: function next() { - if (this.done) { - return this.EOF; - } - if (!this._input) this.done = true; - - var token, match, tempMatch, index, col, lines; - if (!this._more) { - this.yytext = ''; - this.match = ''; - } - var rules = this._currentRules(); - for (var i = 0; i < rules.length; i++) { - tempMatch = this._input.match(this.rules[rules[i]]); - if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { - match = tempMatch; - index = i; - if (!this.options.flex) break; - } - } - if (match) { - lines = match[0].match(/(?:\r\n?|\n).*/g); - if (lines) this.yylineno += lines.length; - this.yylloc = { first_line: this.yylloc.last_line, - last_line: this.yylineno + 1, - first_column: this.yylloc.last_column, - last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length }; - this.yytext += match[0]; - this.match += match[0]; - this.matches = match; - this.yyleng = this.yytext.length; - if (this.options.ranges) { - this.yylloc.range = [this.offset, this.offset += this.yyleng]; - } - this._more = false; - this._input = this._input.slice(match[0].length); - this.matched += match[0]; - token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]); - if (this.done && this._input) this.done = false; - if (token) return token;else return; - } - if (this._input === "") { - return this.EOF; - } else { - return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno }); - } - }, - lex: function lex() { - var r = this.next(); - if (typeof r !== 'undefined') { - return r; - } else { - return this.lex(); - } - }, - begin: function begin(condition) { - this.conditionStack.push(condition); - }, - popState: function popState() { - return this.conditionStack.pop(); - }, - _currentRules: function _currentRules() { - return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; - }, - topState: function topState() { - return this.conditionStack[this.conditionStack.length - 2]; - }, - pushState: function begin(condition) { - this.begin(condition); - } }; - lexer.options = {}; - lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START - /**/) { - - function strip(start, end) { - return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end); - } - - var YYSTATE = YY_START; - switch ($avoiding_name_collisions) { - case 0: - if (yy_.yytext.slice(-2) === "\\\\") { - strip(0, 1); - this.begin("mu"); - } else if (yy_.yytext.slice(-1) === "\\") { - strip(0, 1); - this.begin("emu"); - } else { - this.begin("mu"); - } - if (yy_.yytext) return 15; - - break; - case 1: - return 15; - break; - case 2: - this.popState(); - return 15; - - break; - case 3: - this.begin('raw');return 15; - break; - case 4: - this.popState(); - // Should be using `this.topState()` below, but it currently - // returns the second top instead of the first top. Opened an - // issue about it at https://github.com/zaach/jison/issues/291 - if (this.conditionStack[this.conditionStack.length - 1] === 'raw') { - return 15; - } else { - yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9); - return 'END_RAW_BLOCK'; - } - - break; - case 5: - return 15; - break; - case 6: - this.popState(); - return 14; - - break; - case 7: - return 65; - break; - case 8: - return 68; - break; - case 9: - return 19; - break; - case 10: - this.popState(); - this.begin('raw'); - return 23; - - break; - case 11: - return 55; - break; - case 12: - return 60; - break; - case 13: - return 29; - break; - case 14: - return 47; - break; - case 15: - this.popState();return 44; - break; - case 16: - this.popState();return 44; - break; - case 17: - return 34; - break; - case 18: - return 39; - break; - case 19: - return 51; - break; - case 20: - return 48; - break; - case 21: - this.unput(yy_.yytext); - this.popState(); - this.begin('com'); - - break; - case 22: - this.popState(); - return 14; - - break; - case 23: - return 48; - break; - case 24: - return 73; - break; - case 25: - return 72; - break; - case 26: - return 72; - break; - case 27: - return 87; - break; - case 28: - // ignore whitespace - break; - case 29: - this.popState();return 54; - break; - case 30: - this.popState();return 33; - break; - case 31: - yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80; - break; - case 32: - yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80; - break; - case 33: - return 85; - break; - case 34: - return 82; - break; - case 35: - return 82; - break; - case 36: - return 83; - break; - case 37: - return 84; - break; - case 38: - return 81; - break; - case 39: - return 75; - break; - case 40: - return 77; - break; - case 41: - return 72; - break; - case 42: - yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72; - break; - case 43: - return 'INVALID'; - break; - case 44: - return 5; - break; - } - }; - lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]*?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/]; - lexer.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } }; - return lexer; - })(); - parser.lexer = lexer; - function Parser() { - this.yy = {}; - }Parser.prototype = parser;parser.Parser = Parser; - return new Parser(); - })();exports.__esModule = true; - exports['default'] = handlebars; - -/***/ }, -/* 24 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - - var _visitor = __webpack_require__(25); - - var _visitor2 = _interopRequireDefault(_visitor); - - function WhitespaceControl() { - var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; - - this.options = options; - } - WhitespaceControl.prototype = new _visitor2['default'](); - - WhitespaceControl.prototype.Program = function (program) { - var doStandalone = !this.options.ignoreStandalone; - - var isRoot = !this.isRootSeen; - this.isRootSeen = true; - - var body = program.body; - for (var i = 0, l = body.length; i < l; i++) { - var current = body[i], - strip = this.accept(current); - - if (!strip) { - continue; - } - - var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot), - _isNextWhitespace = isNextWhitespace(body, i, isRoot), - openStandalone = strip.openStandalone && _isPrevWhitespace, - closeStandalone = strip.closeStandalone && _isNextWhitespace, - inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace; - - if (strip.close) { - omitRight(body, i, true); - } - if (strip.open) { - omitLeft(body, i, true); - } - - if (doStandalone && inlineStandalone) { - omitRight(body, i); - - if (omitLeft(body, i)) { - // If we are on a standalone node, save the indent info for partials - if (current.type === 'PartialStatement') { - // Pull out the whitespace from the final line - current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1]; - } - } - } - if (doStandalone && openStandalone) { - omitRight((current.program || current.inverse).body); - - // Strip out the previous content node if it's whitespace only - omitLeft(body, i); - } - if (doStandalone && closeStandalone) { - // Always strip the next node - omitRight(body, i); - - omitLeft((current.inverse || current.program).body); - } - } - - return program; - }; - - WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) { - this.accept(block.program); - this.accept(block.inverse); - - // Find the inverse program that is involed with whitespace stripping. - var program = block.program || block.inverse, - inverse = block.program && block.inverse, - firstInverse = inverse, - lastInverse = inverse; - - if (inverse && inverse.chained) { - firstInverse = inverse.body[0].program; - - // Walk the inverse chain to find the last inverse that is actually in the chain. - while (lastInverse.chained) { - lastInverse = lastInverse.body[lastInverse.body.length - 1].program; - } - } - - var strip = { - open: block.openStrip.open, - close: block.closeStrip.close, - - // Determine the standalone candiacy. Basically flag our content as being possibly standalone - // so our parent can determine if we actually are standalone - openStandalone: isNextWhitespace(program.body), - closeStandalone: isPrevWhitespace((firstInverse || program).body) - }; - - if (block.openStrip.close) { - omitRight(program.body, null, true); - } - - if (inverse) { - var inverseStrip = block.inverseStrip; - - if (inverseStrip.open) { - omitLeft(program.body, null, true); - } - - if (inverseStrip.close) { - omitRight(firstInverse.body, null, true); - } - if (block.closeStrip.open) { - omitLeft(lastInverse.body, null, true); - } - - // Find standalone else statments - if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) { - omitLeft(program.body); - omitRight(firstInverse.body); - } - } else if (block.closeStrip.open) { - omitLeft(program.body, null, true); - } - - return strip; - }; - - WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) { - return mustache.strip; - }; - - WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) { - /* istanbul ignore next */ - var strip = node.strip || {}; - return { - inlineStandalone: true, - open: strip.open, - close: strip.close - }; - }; - - function isPrevWhitespace(body, i, isRoot) { - if (i === undefined) { - i = body.length; - } - - // Nodes that end with newlines are considered whitespace (but are special - // cased for strip operations) - var prev = body[i - 1], - sibling = body[i - 2]; - if (!prev) { - return isRoot; - } - - if (prev.type === 'ContentStatement') { - return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original); - } - } - function isNextWhitespace(body, i, isRoot) { - if (i === undefined) { - i = -1; - } - - var next = body[i + 1], - sibling = body[i + 2]; - if (!next) { - return isRoot; - } - - if (next.type === 'ContentStatement') { - return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original); - } - } - - // Marks the node to the right of the position as omitted. - // I.e. {{foo}}' ' will mark the ' ' node as omitted. - // - // If i is undefined, then the first child will be marked as such. - // - // If mulitple is truthy then all whitespace will be stripped out until non-whitespace - // content is met. - function omitRight(body, i, multiple) { - var current = body[i == null ? 0 : i + 1]; - if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) { - return; - } - - var original = current.value; - current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, ''); - current.rightStripped = current.value !== original; - } - - // Marks the node to the left of the position as omitted. - // I.e. ' '{{foo}} will mark the ' ' node as omitted. - // - // If i is undefined then the last child will be marked as such. - // - // If mulitple is truthy then all whitespace will be stripped out until non-whitespace - // content is met. - function omitLeft(body, i, multiple) { - var current = body[i == null ? body.length - 1 : i - 1]; - if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) { - return; - } - - // We omit the last node if it's whitespace only and not preceeded by a non-content node. - var original = current.value; - current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, ''); - current.leftStripped = current.value !== original; - return current.leftStripped; - } - - exports['default'] = WhitespaceControl; - module.exports = exports['default']; - -/***/ }, -/* 25 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - - var _exception = __webpack_require__(6); - - var _exception2 = _interopRequireDefault(_exception); - - function Visitor() { - this.parents = []; - } - - Visitor.prototype = { - constructor: Visitor, - mutating: false, - - // Visits a given value. If mutating, will replace the value if necessary. - acceptKey: function acceptKey(node, name) { - var value = this.accept(node[name]); - if (this.mutating) { - // Hacky sanity check: This may have a few false positives for type for the helper - // methods but will generally do the right thing without a lot of overhead. - if (value && !Visitor.prototype[value.type]) { - throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type); - } - node[name] = value; - } - }, - - // Performs an accept operation with added sanity check to ensure - // required keys are not removed. - acceptRequired: function acceptRequired(node, name) { - this.acceptKey(node, name); - - if (!node[name]) { - throw new _exception2['default'](node.type + ' requires ' + name); - } - }, - - // Traverses a given array. If mutating, empty respnses will be removed - // for child elements. - acceptArray: function acceptArray(array) { - for (var i = 0, l = array.length; i < l; i++) { - this.acceptKey(array, i); - - if (!array[i]) { - array.splice(i, 1); - i--; - l--; - } - } - }, - - accept: function accept(object) { - if (!object) { - return; - } - - /* istanbul ignore next: Sanity code */ - if (!this[object.type]) { - throw new _exception2['default']('Unknown type: ' + object.type, object); - } - - if (this.current) { - this.parents.unshift(this.current); - } - this.current = object; - - var ret = this[object.type](object); - - this.current = this.parents.shift(); - - if (!this.mutating || ret) { - return ret; - } else if (ret !== false) { - return object; - } - }, - - Program: function Program(program) { - this.acceptArray(program.body); - }, - - MustacheStatement: visitSubExpression, - Decorator: visitSubExpression, - - BlockStatement: visitBlock, - DecoratorBlock: visitBlock, - - PartialStatement: visitPartial, - PartialBlockStatement: function PartialBlockStatement(partial) { - visitPartial.call(this, partial); - - this.acceptKey(partial, 'program'); - }, - - ContentStatement: function ContentStatement() /* content */{}, - CommentStatement: function CommentStatement() /* comment */{}, - - SubExpression: visitSubExpression, - - PathExpression: function PathExpression() /* path */{}, - - StringLiteral: function StringLiteral() /* string */{}, - NumberLiteral: function NumberLiteral() /* number */{}, - BooleanLiteral: function BooleanLiteral() /* bool */{}, - UndefinedLiteral: function UndefinedLiteral() /* literal */{}, - NullLiteral: function NullLiteral() /* literal */{}, - - Hash: function Hash(hash) { - this.acceptArray(hash.pairs); - }, - HashPair: function HashPair(pair) { - this.acceptRequired(pair, 'value'); - } - }; - - function visitSubExpression(mustache) { - this.acceptRequired(mustache, 'path'); - this.acceptArray(mustache.params); - this.acceptKey(mustache, 'hash'); - } - function visitBlock(block) { - visitSubExpression.call(this, block); - - this.acceptKey(block, 'program'); - this.acceptKey(block, 'inverse'); - } - function visitPartial(partial) { - this.acceptRequired(partial, 'name'); - this.acceptArray(partial.params); - this.acceptKey(partial, 'hash'); - } - - exports['default'] = Visitor; - module.exports = exports['default']; - -/***/ }, -/* 26 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - exports.SourceLocation = SourceLocation; - exports.id = id; - exports.stripFlags = stripFlags; - exports.stripComment = stripComment; - exports.preparePath = preparePath; - exports.prepareMustache = prepareMustache; - exports.prepareRawBlock = prepareRawBlock; - exports.prepareBlock = prepareBlock; - exports.prepareProgram = prepareProgram; - exports.preparePartialBlock = preparePartialBlock; - - var _exception = __webpack_require__(6); - - var _exception2 = _interopRequireDefault(_exception); - - function validateClose(open, close) { - close = close.path ? close.path.original : close; - - if (open.path.original !== close) { - var errorNode = { loc: open.path.loc }; - - throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode); - } - } - - function SourceLocation(source, locInfo) { - this.source = source; - this.start = { - line: locInfo.first_line, - column: locInfo.first_column - }; - this.end = { - line: locInfo.last_line, - column: locInfo.last_column - }; - } - - function id(token) { - if (/^\[.*\]$/.test(token)) { - return token.substr(1, token.length - 2); - } else { - return token; - } - } - - function stripFlags(open, close) { - return { - open: open.charAt(2) === '~', - close: close.charAt(close.length - 3) === '~' - }; - } - - function stripComment(comment) { - return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, ''); - } - - function preparePath(data, parts, loc) { - loc = this.locInfo(loc); - - var original = data ? '@' : '', - dig = [], - depth = 0, - depthString = ''; - - for (var i = 0, l = parts.length; i < l; i++) { - var part = parts[i].part, - - // If we have [] syntax then we do not treat path references as operators, - // i.e. foo.[this] resolves to approximately context.foo['this'] - isLiteral = parts[i].original !== part; - original += (parts[i].separator || '') + part; - - if (!isLiteral && (part === '..' || part === '.' || part === 'this')) { - if (dig.length > 0) { - throw new _exception2['default']('Invalid path: ' + original, { loc: loc }); - } else if (part === '..') { - depth++; - depthString += '../'; - } - } else { - dig.push(part); - } - } - - return { - type: 'PathExpression', - data: data, - depth: depth, - parts: dig, - original: original, - loc: loc - }; - } - - function prepareMustache(path, params, hash, open, strip, locInfo) { - // Must use charAt to support IE pre-10 - var escapeFlag = open.charAt(3) || open.charAt(2), - escaped = escapeFlag !== '{' && escapeFlag !== '&'; - - var decorator = /\*/.test(open); - return { - type: decorator ? 'Decorator' : 'MustacheStatement', - path: path, - params: params, - hash: hash, - escaped: escaped, - strip: strip, - loc: this.locInfo(locInfo) - }; - } - - function prepareRawBlock(openRawBlock, contents, close, locInfo) { - validateClose(openRawBlock, close); - - locInfo = this.locInfo(locInfo); - var program = { - type: 'Program', - body: contents, - strip: {}, - loc: locInfo - }; - - return { - type: 'BlockStatement', - path: openRawBlock.path, - params: openRawBlock.params, - hash: openRawBlock.hash, - program: program, - openStrip: {}, - inverseStrip: {}, - closeStrip: {}, - loc: locInfo - }; - } - - function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) { - if (close && close.path) { - validateClose(openBlock, close); - } - - var decorator = /\*/.test(openBlock.open); - - program.blockParams = openBlock.blockParams; - - var inverse = undefined, - inverseStrip = undefined; - - if (inverseAndProgram) { - if (decorator) { - throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram); - } - - if (inverseAndProgram.chain) { - inverseAndProgram.program.body[0].closeStrip = close.strip; - } - - inverseStrip = inverseAndProgram.strip; - inverse = inverseAndProgram.program; - } - - if (inverted) { - inverted = inverse; - inverse = program; - program = inverted; - } - - return { - type: decorator ? 'DecoratorBlock' : 'BlockStatement', - path: openBlock.path, - params: openBlock.params, - hash: openBlock.hash, - program: program, - inverse: inverse, - openStrip: openBlock.strip, - inverseStrip: inverseStrip, - closeStrip: close && close.strip, - loc: this.locInfo(locInfo) - }; - } - - function prepareProgram(statements, loc) { - if (!loc && statements.length) { - var firstLoc = statements[0].loc, - lastLoc = statements[statements.length - 1].loc; - - /* istanbul ignore else */ - if (firstLoc && lastLoc) { - loc = { - source: firstLoc.source, - start: { - line: firstLoc.start.line, - column: firstLoc.start.column - }, - end: { - line: lastLoc.end.line, - column: lastLoc.end.column - } - }; - } - } - - return { - type: 'Program', - body: statements, - strip: {}, - loc: loc - }; - } - - function preparePartialBlock(open, program, close, locInfo) { - validateClose(open, close); - - return { - type: 'PartialBlockStatement', - name: open.path, - params: open.params, - hash: open.hash, - program: program, - openStrip: open.strip, - closeStrip: close && close.strip, - loc: this.locInfo(locInfo) - }; - } - -/***/ }, -/* 27 */ -/***/ function(module, exports, __webpack_require__) { - - /* eslint-disable new-cap */ - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - exports.Compiler = Compiler; - exports.precompile = precompile; - exports.compile = compile; - - var _exception = __webpack_require__(6); - - var _exception2 = _interopRequireDefault(_exception); - - var _utils = __webpack_require__(5); - - var _ast = __webpack_require__(21); - - var _ast2 = _interopRequireDefault(_ast); - - var slice = [].slice; - - function Compiler() {} - - // the foundHelper register will disambiguate helper lookup from finding a - // function in a context. This is necessary for mustache compatibility, which - // requires that context functions in blocks are evaluated by blockHelperMissing, - // and then proceed as if the resulting value was provided to blockHelperMissing. - - Compiler.prototype = { - compiler: Compiler, - - equals: function equals(other) { - var len = this.opcodes.length; - if (other.opcodes.length !== len) { - return false; - } - - for (var i = 0; i < len; i++) { - var opcode = this.opcodes[i], - otherOpcode = other.opcodes[i]; - if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) { - return false; - } - } - - // We know that length is the same between the two arrays because they are directly tied - // to the opcode behavior above. - len = this.children.length; - for (var i = 0; i < len; i++) { - if (!this.children[i].equals(other.children[i])) { - return false; - } - } - - return true; - }, - - guid: 0, - - compile: function compile(program, options) { - this.sourceNode = []; - this.opcodes = []; - this.children = []; - this.options = options; - this.stringParams = options.stringParams; - this.trackIds = options.trackIds; - - options.blockParams = options.blockParams || []; - - // These changes will propagate to the other compiler components - var knownHelpers = options.knownHelpers; - options.knownHelpers = { - 'helperMissing': true, - 'blockHelperMissing': true, - 'each': true, - 'if': true, - 'unless': true, - 'with': true, - 'log': true, - 'lookup': true - }; - if (knownHelpers) { - for (var _name in knownHelpers) { - /* istanbul ignore else */ - if (_name in knownHelpers) { - options.knownHelpers[_name] = knownHelpers[_name]; - } - } - } - - return this.accept(program); - }, - - compileProgram: function compileProgram(program) { - var childCompiler = new this.compiler(), - // eslint-disable-line new-cap - result = childCompiler.compile(program, this.options), - guid = this.guid++; - - this.usePartial = this.usePartial || result.usePartial; - - this.children[guid] = result; - this.useDepths = this.useDepths || result.useDepths; - - return guid; - }, - - accept: function accept(node) { - /* istanbul ignore next: Sanity code */ - if (!this[node.type]) { - throw new _exception2['default']('Unknown type: ' + node.type, node); - } - - this.sourceNode.unshift(node); - var ret = this[node.type](node); - this.sourceNode.shift(); - return ret; - }, - - Program: function Program(program) { - this.options.blockParams.unshift(program.blockParams); - - var body = program.body, - bodyLength = body.length; - for (var i = 0; i < bodyLength; i++) { - this.accept(body[i]); - } - - this.options.blockParams.shift(); - - this.isSimple = bodyLength === 1; - this.blockParams = program.blockParams ? program.blockParams.length : 0; - - return this; - }, - - BlockStatement: function BlockStatement(block) { - transformLiteralToPath(block); - - var program = block.program, - inverse = block.inverse; - - program = program && this.compileProgram(program); - inverse = inverse && this.compileProgram(inverse); - - var type = this.classifySexpr(block); - - if (type === 'helper') { - this.helperSexpr(block, program, inverse); - } else if (type === 'simple') { - this.simpleSexpr(block); - - // now that the simple mustache is resolved, we need to - // evaluate it by executing `blockHelperMissing` - this.opcode('pushProgram', program); - this.opcode('pushProgram', inverse); - this.opcode('emptyHash'); - this.opcode('blockValue', block.path.original); - } else { - this.ambiguousSexpr(block, program, inverse); - - // now that the simple mustache is resolved, we need to - // evaluate it by executing `blockHelperMissing` - this.opcode('pushProgram', program); - this.opcode('pushProgram', inverse); - this.opcode('emptyHash'); - this.opcode('ambiguousBlockValue'); - } - - this.opcode('append'); - }, - - DecoratorBlock: function DecoratorBlock(decorator) { - var program = decorator.program && this.compileProgram(decorator.program); - var params = this.setupFullMustacheParams(decorator, program, undefined), - path = decorator.path; - - this.useDecorators = true; - this.opcode('registerDecorator', params.length, path.original); - }, - - PartialStatement: function PartialStatement(partial) { - this.usePartial = true; - - var program = partial.program; - if (program) { - program = this.compileProgram(partial.program); - } - - var params = partial.params; - if (params.length > 1) { - throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial); - } else if (!params.length) { - if (this.options.explicitPartialContext) { - this.opcode('pushLiteral', 'undefined'); - } else { - params.push({ type: 'PathExpression', parts: [], depth: 0 }); - } - } - - var partialName = partial.name.original, - isDynamic = partial.name.type === 'SubExpression'; - if (isDynamic) { - this.accept(partial.name); - } - - this.setupFullMustacheParams(partial, program, undefined, true); - - var indent = partial.indent || ''; - if (this.options.preventIndent && indent) { - this.opcode('appendContent', indent); - indent = ''; - } - - this.opcode('invokePartial', isDynamic, partialName, indent); - this.opcode('append'); - }, - PartialBlockStatement: function PartialBlockStatement(partialBlock) { - this.PartialStatement(partialBlock); - }, - - MustacheStatement: function MustacheStatement(mustache) { - this.SubExpression(mustache); - - if (mustache.escaped && !this.options.noEscape) { - this.opcode('appendEscaped'); - } else { - this.opcode('append'); - } - }, - Decorator: function Decorator(decorator) { - this.DecoratorBlock(decorator); - }, - - ContentStatement: function ContentStatement(content) { - if (content.value) { - this.opcode('appendContent', content.value); - } - }, - - CommentStatement: function CommentStatement() {}, - - SubExpression: function SubExpression(sexpr) { - transformLiteralToPath(sexpr); - var type = this.classifySexpr(sexpr); - - if (type === 'simple') { - this.simpleSexpr(sexpr); - } else if (type === 'helper') { - this.helperSexpr(sexpr); - } else { - this.ambiguousSexpr(sexpr); - } - }, - ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) { - var path = sexpr.path, - name = path.parts[0], - isBlock = program != null || inverse != null; - - this.opcode('getContext', path.depth); - - this.opcode('pushProgram', program); - this.opcode('pushProgram', inverse); - - path.strict = true; - this.accept(path); - - this.opcode('invokeAmbiguous', name, isBlock); - }, - - simpleSexpr: function simpleSexpr(sexpr) { - var path = sexpr.path; - path.strict = true; - this.accept(path); - this.opcode('resolvePossibleLambda'); - }, - - helperSexpr: function helperSexpr(sexpr, program, inverse) { - var params = this.setupFullMustacheParams(sexpr, program, inverse), - path = sexpr.path, - name = path.parts[0]; - - if (this.options.knownHelpers[name]) { - this.opcode('invokeKnownHelper', params.length, name); - } else if (this.options.knownHelpersOnly) { - throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr); - } else { - path.strict = true; - path.falsy = true; - - this.accept(path); - this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path)); - } - }, - - PathExpression: function PathExpression(path) { - this.addDepth(path.depth); - this.opcode('getContext', path.depth); - - var name = path.parts[0], - scoped = _ast2['default'].helpers.scopedId(path), - blockParamId = !path.depth && !scoped && this.blockParamIndex(name); - - if (blockParamId) { - this.opcode('lookupBlockParam', blockParamId, path.parts); - } else if (!name) { - // Context reference, i.e. `{{foo .}}` or `{{foo ..}}` - this.opcode('pushContext'); - } else if (path.data) { - this.options.data = true; - this.opcode('lookupData', path.depth, path.parts, path.strict); - } else { - this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped); - } - }, - - StringLiteral: function StringLiteral(string) { - this.opcode('pushString', string.value); - }, - - NumberLiteral: function NumberLiteral(number) { - this.opcode('pushLiteral', number.value); - }, - - BooleanLiteral: function BooleanLiteral(bool) { - this.opcode('pushLiteral', bool.value); - }, - - UndefinedLiteral: function UndefinedLiteral() { - this.opcode('pushLiteral', 'undefined'); - }, - - NullLiteral: function NullLiteral() { - this.opcode('pushLiteral', 'null'); - }, - - Hash: function Hash(hash) { - var pairs = hash.pairs, - i = 0, - l = pairs.length; - - this.opcode('pushHash'); - - for (; i < l; i++) { - this.pushParam(pairs[i].value); - } - while (i--) { - this.opcode('assignToHash', pairs[i].key); - } - this.opcode('popHash'); - }, - - // HELPERS - opcode: function opcode(name) { - this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc }); - }, - - addDepth: function addDepth(depth) { - if (!depth) { - return; - } - - this.useDepths = true; - }, - - classifySexpr: function classifySexpr(sexpr) { - var isSimple = _ast2['default'].helpers.simpleId(sexpr.path); - - var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]); - - // a mustache is an eligible helper if: - // * its id is simple (a single part, not `this` or `..`) - var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr); - - // if a mustache is an eligible helper but not a definite - // helper, it is ambiguous, and will be resolved in a later - // pass or at runtime. - var isEligible = !isBlockParam && (isHelper || isSimple); - - // if ambiguous, we can possibly resolve the ambiguity now - // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc. - if (isEligible && !isHelper) { - var _name2 = sexpr.path.parts[0], - options = this.options; - - if (options.knownHelpers[_name2]) { - isHelper = true; - } else if (options.knownHelpersOnly) { - isEligible = false; - } - } - - if (isHelper) { - return 'helper'; - } else if (isEligible) { - return 'ambiguous'; - } else { - return 'simple'; - } - }, - - pushParams: function pushParams(params) { - for (var i = 0, l = params.length; i < l; i++) { - this.pushParam(params[i]); - } - }, - - pushParam: function pushParam(val) { - var value = val.value != null ? val.value : val.original || ''; - - if (this.stringParams) { - if (value.replace) { - value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.'); - } - - if (val.depth) { - this.addDepth(val.depth); - } - this.opcode('getContext', val.depth || 0); - this.opcode('pushStringParam', value, val.type); - - if (val.type === 'SubExpression') { - // SubExpressions get evaluated and passed in - // in string params mode. - this.accept(val); - } - } else { - if (this.trackIds) { - var blockParamIndex = undefined; - if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) { - blockParamIndex = this.blockParamIndex(val.parts[0]); - } - if (blockParamIndex) { - var blockParamChild = val.parts.slice(1).join('.'); - this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild); - } else { - value = val.original || value; - if (value.replace) { - value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, ''); - } - - this.opcode('pushId', val.type, value); - } - } - this.accept(val); - } - }, - - setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) { - var params = sexpr.params; - this.pushParams(params); - - this.opcode('pushProgram', program); - this.opcode('pushProgram', inverse); - - if (sexpr.hash) { - this.accept(sexpr.hash); - } else { - this.opcode('emptyHash', omitEmpty); - } - - return params; - }, - - blockParamIndex: function blockParamIndex(name) { - for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) { - var blockParams = this.options.blockParams[depth], - param = blockParams && _utils.indexOf(blockParams, name); - if (blockParams && param >= 0) { - return [depth, param]; - } - } - } - }; - - function precompile(input, options, env) { - if (input == null || typeof input !== 'string' && input.type !== 'Program') { - throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input); - } - - options = options || {}; - if (!('data' in options)) { - options.data = true; - } - if (options.compat) { - options.useDepths = true; - } - - var ast = env.parse(input, options), - environment = new env.Compiler().compile(ast, options); - return new env.JavaScriptCompiler().compile(environment, options); - } - - function compile(input, options, env) { - if (options === undefined) options = {}; - - if (input == null || typeof input !== 'string' && input.type !== 'Program') { - throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input); - } - - if (!('data' in options)) { - options.data = true; - } - if (options.compat) { - options.useDepths = true; - } - - var compiled = undefined; - - function compileInput() { - var ast = env.parse(input, options), - environment = new env.Compiler().compile(ast, options), - templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true); - return env.template(templateSpec); - } - - // Template is only compiled on first use and cached after that point. - function ret(context, execOptions) { - if (!compiled) { - compiled = compileInput(); - } - return compiled.call(this, context, execOptions); - } - ret._setup = function (setupOptions) { - if (!compiled) { - compiled = compileInput(); - } - return compiled._setup(setupOptions); - }; - ret._child = function (i, data, blockParams, depths) { - if (!compiled) { - compiled = compileInput(); - } - return compiled._child(i, data, blockParams, depths); - }; - return ret; - } - - function argEquals(a, b) { - if (a === b) { - return true; - } - - if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) { - for (var i = 0; i < a.length; i++) { - if (!argEquals(a[i], b[i])) { - return false; - } - } - return true; - } - } - - function transformLiteralToPath(sexpr) { - if (!sexpr.path.parts) { - var literal = sexpr.path; - // Casting to string here to make false and 0 literal values play nicely with the rest - // of the system. - sexpr.path = { - type: 'PathExpression', - data: false, - depth: 0, - parts: [literal.original + ''], - original: literal.original + '', - loc: literal.loc - }; - } - } - -/***/ }, -/* 28 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _interopRequireDefault = __webpack_require__(1)['default']; - - exports.__esModule = true; - - var _base = __webpack_require__(4); - - var _exception = __webpack_require__(6); - - var _exception2 = _interopRequireDefault(_exception); - - var _utils = __webpack_require__(5); - - var _codeGen = __webpack_require__(29); - - var _codeGen2 = _interopRequireDefault(_codeGen); - - function Literal(value) { - this.value = value; - } - - function JavaScriptCompiler() {} - - JavaScriptCompiler.prototype = { - // PUBLIC API: You can override these methods in a subclass to provide - // alternative compiled forms for name lookup and buffering semantics - nameLookup: function nameLookup(parent, name /* , type*/) { - if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) { - return [parent, '.', name]; - } else { - return [parent, '[', JSON.stringify(name), ']']; - } - }, - depthedLookup: function depthedLookup(name) { - return [this.aliasable('container.lookup'), '(depths, "', name, '")']; - }, - - compilerInfo: function compilerInfo() { - var revision = _base.COMPILER_REVISION, - versions = _base.REVISION_CHANGES[revision]; - return [revision, versions]; - }, - - appendToBuffer: function appendToBuffer(source, location, explicit) { - // Force a source as this simplifies the merge logic. - if (!_utils.isArray(source)) { - source = [source]; - } - source = this.source.wrap(source, location); - - if (this.environment.isSimple) { - return ['return ', source, ';']; - } else if (explicit) { - // This is a case where the buffer operation occurs as a child of another - // construct, generally braces. We have to explicitly output these buffer - // operations to ensure that the emitted code goes in the correct location. - return ['buffer += ', source, ';']; - } else { - source.appendToBuffer = true; - return source; - } - }, - - initializeBuffer: function initializeBuffer() { - return this.quotedString(''); - }, - // END PUBLIC API - - compile: function compile(environment, options, context, asObject) { - this.environment = environment; - this.options = options; - this.stringParams = this.options.stringParams; - this.trackIds = this.options.trackIds; - this.precompile = !asObject; - - this.name = this.environment.name; - this.isChild = !!context; - this.context = context || { - decorators: [], - programs: [], - environments: [] - }; - - this.preamble(); - - this.stackSlot = 0; - this.stackVars = []; - this.aliases = {}; - this.registers = { list: [] }; - this.hashes = []; - this.compileStack = []; - this.inlineStack = []; - this.blockParams = []; - - this.compileChildren(environment, options); - - this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat; - this.useBlockParams = this.useBlockParams || environment.useBlockParams; - - var opcodes = environment.opcodes, - opcode = undefined, - firstLoc = undefined, - i = undefined, - l = undefined; - - for (i = 0, l = opcodes.length; i < l; i++) { - opcode = opcodes[i]; - - this.source.currentLocation = opcode.loc; - firstLoc = firstLoc || opcode.loc; - this[opcode.opcode].apply(this, opcode.args); - } - - // Flush any trailing content that might be pending. - this.source.currentLocation = firstLoc; - this.pushSource(''); - - /* istanbul ignore next */ - if (this.stackSlot || this.inlineStack.length || this.compileStack.length) { - throw new _exception2['default']('Compile completed with content left on stack'); - } - - if (!this.decorators.isEmpty()) { - this.useDecorators = true; - - this.decorators.prepend('var decorators = container.decorators;\n'); - this.decorators.push('return fn;'); - - if (asObject) { - this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]); - } else { - this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n'); - this.decorators.push('}\n'); - this.decorators = this.decorators.merge(); - } - } else { - this.decorators = undefined; - } - - var fn = this.createFunctionContext(asObject); - if (!this.isChild) { - var ret = { - compiler: this.compilerInfo(), - main: fn - }; - - if (this.decorators) { - ret.main_d = this.decorators; // eslint-disable-line camelcase - ret.useDecorators = true; - } - - var _context = this.context; - var programs = _context.programs; - var decorators = _context.decorators; - - for (i = 0, l = programs.length; i < l; i++) { - if (programs[i]) { - ret[i] = programs[i]; - if (decorators[i]) { - ret[i + '_d'] = decorators[i]; - ret.useDecorators = true; - } - } - } - - if (this.environment.usePartial) { - ret.usePartial = true; - } - if (this.options.data) { - ret.useData = true; - } - if (this.useDepths) { - ret.useDepths = true; - } - if (this.useBlockParams) { - ret.useBlockParams = true; - } - if (this.options.compat) { - ret.compat = true; - } - - if (!asObject) { - ret.compiler = JSON.stringify(ret.compiler); - - this.source.currentLocation = { start: { line: 1, column: 0 } }; - ret = this.objectLiteral(ret); - - if (options.srcName) { - ret = ret.toStringWithSourceMap({ file: options.destName }); - ret.map = ret.map && ret.map.toString(); - } else { - ret = ret.toString(); - } - } else { - ret.compilerOptions = this.options; - } - - return ret; - } else { - return fn; - } - }, - - preamble: function preamble() { - // track the last context pushed into place to allow skipping the - // getContext opcode when it would be a noop - this.lastContext = 0; - this.source = new _codeGen2['default'](this.options.srcName); - this.decorators = new _codeGen2['default'](this.options.srcName); - }, - - createFunctionContext: function createFunctionContext(asObject) { - var varDeclarations = ''; - - var locals = this.stackVars.concat(this.registers.list); - if (locals.length > 0) { - varDeclarations += ', ' + locals.join(', '); - } - - // Generate minimizer alias mappings - // - // When using true SourceNodes, this will update all references to the given alias - // as the source nodes are reused in situ. For the non-source node compilation mode, - // aliases will not be used, but this case is already being run on the client and - // we aren't concern about minimizing the template size. - var aliasCount = 0; - for (var alias in this.aliases) { - // eslint-disable-line guard-for-in - var node = this.aliases[alias]; - - if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) { - varDeclarations += ', alias' + ++aliasCount + '=' + alias; - node.children[0] = 'alias' + aliasCount; - } - } - - var params = ['container', 'depth0', 'helpers', 'partials', 'data']; - - if (this.useBlockParams || this.useDepths) { - params.push('blockParams'); - } - if (this.useDepths) { - params.push('depths'); - } - - // Perform a second pass over the output to merge content when possible - var source = this.mergeSource(varDeclarations); - - if (asObject) { - params.push(source); - - return Function.apply(this, params); - } else { - return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']); - } - }, - mergeSource: function mergeSource(varDeclarations) { - var isSimple = this.environment.isSimple, - appendOnly = !this.forceBuffer, - appendFirst = undefined, - sourceSeen = undefined, - bufferStart = undefined, - bufferEnd = undefined; - this.source.each(function (line) { - if (line.appendToBuffer) { - if (bufferStart) { - line.prepend(' + '); - } else { - bufferStart = line; - } - bufferEnd = line; - } else { - if (bufferStart) { - if (!sourceSeen) { - appendFirst = true; - } else { - bufferStart.prepend('buffer += '); - } - bufferEnd.add(';'); - bufferStart = bufferEnd = undefined; - } - - sourceSeen = true; - if (!isSimple) { - appendOnly = false; - } - } - }); - - if (appendOnly) { - if (bufferStart) { - bufferStart.prepend('return '); - bufferEnd.add(';'); - } else if (!sourceSeen) { - this.source.push('return "";'); - } - } else { - varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer()); - - if (bufferStart) { - bufferStart.prepend('return buffer + '); - bufferEnd.add(';'); - } else { - this.source.push('return buffer;'); - } - } - - if (varDeclarations) { - this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n')); - } - - return this.source.merge(); - }, - - // [blockValue] - // - // On stack, before: hash, inverse, program, value - // On stack, after: return value of blockHelperMissing - // - // The purpose of this opcode is to take a block of the form - // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and - // replace it on the stack with the result of properly - // invoking blockHelperMissing. - blockValue: function blockValue(name) { - var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'), - params = [this.contextName(0)]; - this.setupHelperArgs(name, 0, params); - - var blockName = this.popStack(); - params.splice(1, 0, blockName); - - this.push(this.source.functionCall(blockHelperMissing, 'call', params)); - }, - - // [ambiguousBlockValue] - // - // On stack, before: hash, inverse, program, value - // Compiler value, before: lastHelper=value of last found helper, if any - // On stack, after, if no lastHelper: same as [blockValue] - // On stack, after, if lastHelper: value - ambiguousBlockValue: function ambiguousBlockValue() { - // We're being a bit cheeky and reusing the options value from the prior exec - var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'), - params = [this.contextName(0)]; - this.setupHelperArgs('', 0, params, true); - - this.flushInline(); - - var current = this.topStack(); - params.splice(1, 0, current); - - this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']); - }, - - // [appendContent] - // - // On stack, before: ... - // On stack, after: ... - // - // Appends the string value of `content` to the current buffer - appendContent: function appendContent(content) { - if (this.pendingContent) { - content = this.pendingContent + content; - } else { - this.pendingLocation = this.source.currentLocation; - } - - this.pendingContent = content; - }, - - // [append] - // - // On stack, before: value, ... - // On stack, after: ... - // - // Coerces `value` to a String and appends it to the current buffer. - // - // If `value` is truthy, or 0, it is coerced into a string and appended - // Otherwise, the empty string is appended - append: function append() { - if (this.isInline()) { - this.replaceStack(function (current) { - return [' != null ? ', current, ' : ""']; - }); - - this.pushSource(this.appendToBuffer(this.popStack())); - } else { - var local = this.popStack(); - this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']); - if (this.environment.isSimple) { - this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']); - } - } - }, - - // [appendEscaped] - // - // On stack, before: value, ... - // On stack, after: ... - // - // Escape `value` and append it to the buffer - appendEscaped: function appendEscaped() { - this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')'])); - }, - - // [getContext] - // - // On stack, before: ... - // On stack, after: ... - // Compiler value, after: lastContext=depth - // - // Set the value of the `lastContext` compiler value to the depth - getContext: function getContext(depth) { - this.lastContext = depth; - }, - - // [pushContext] - // - // On stack, before: ... - // On stack, after: currentContext, ... - // - // Pushes the value of the current context onto the stack. - pushContext: function pushContext() { - this.pushStackLiteral(this.contextName(this.lastContext)); - }, - - // [lookupOnContext] - // - // On stack, before: ... - // On stack, after: currentContext[name], ... - // - // Looks up the value of `name` on the current context and pushes - // it onto the stack. - lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) { - var i = 0; - - if (!scoped && this.options.compat && !this.lastContext) { - // The depthed query is expected to handle the undefined logic for the root level that - // is implemented below, so we evaluate that directly in compat mode - this.push(this.depthedLookup(parts[i++])); - } else { - this.pushContext(); - } - - this.resolvePath('context', parts, i, falsy, strict); - }, - - // [lookupBlockParam] - // - // On stack, before: ... - // On stack, after: blockParam[name], ... - // - // Looks up the value of `parts` on the given block param and pushes - // it onto the stack. - lookupBlockParam: function lookupBlockParam(blockParamId, parts) { - this.useBlockParams = true; - - this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']); - this.resolvePath('context', parts, 1); - }, - - // [lookupData] - // - // On stack, before: ... - // On stack, after: data, ... - // - // Push the data lookup operator - lookupData: function lookupData(depth, parts, strict) { - if (!depth) { - this.pushStackLiteral('data'); - } else { - this.pushStackLiteral('container.data(data, ' + depth + ')'); - } - - this.resolvePath('data', parts, 0, true, strict); - }, - - resolvePath: function resolvePath(type, parts, i, falsy, strict) { - // istanbul ignore next - - var _this = this; - - if (this.options.strict || this.options.assumeObjects) { - this.push(strictLookup(this.options.strict && strict, this, parts, type)); - return; - } - - var len = parts.length; - for (; i < len; i++) { - /* eslint-disable no-loop-func */ - this.replaceStack(function (current) { - var lookup = _this.nameLookup(current, parts[i], type); - // We want to ensure that zero and false are handled properly if the context (falsy flag) - // needs to have the special handling for these values. - if (!falsy) { - return [' != null ? ', lookup, ' : ', current]; - } else { - // Otherwise we can use generic falsy handling - return [' && ', lookup]; - } - }); - /* eslint-enable no-loop-func */ - } - }, - - // [resolvePossibleLambda] - // - // On stack, before: value, ... - // On stack, after: resolved value, ... - // - // If the `value` is a lambda, replace it on the stack by - // the return value of the lambda - resolvePossibleLambda: function resolvePossibleLambda() { - this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']); - }, - - // [pushStringParam] - // - // On stack, before: ... - // On stack, after: string, currentContext, ... - // - // This opcode is designed for use in string mode, which - // provides the string value of a parameter along with its - // depth rather than resolving it immediately. - pushStringParam: function pushStringParam(string, type) { - this.pushContext(); - this.pushString(type); - - // If it's a subexpression, the string result - // will be pushed after this opcode. - if (type !== 'SubExpression') { - if (typeof string === 'string') { - this.pushString(string); - } else { - this.pushStackLiteral(string); - } - } - }, - - emptyHash: function emptyHash(omitEmpty) { - if (this.trackIds) { - this.push('{}'); // hashIds - } - if (this.stringParams) { - this.push('{}'); // hashContexts - this.push('{}'); // hashTypes - } - this.pushStackLiteral(omitEmpty ? 'undefined' : '{}'); - }, - pushHash: function pushHash() { - if (this.hash) { - this.hashes.push(this.hash); - } - this.hash = { values: [], types: [], contexts: [], ids: [] }; - }, - popHash: function popHash() { - var hash = this.hash; - this.hash = this.hashes.pop(); - - if (this.trackIds) { - this.push(this.objectLiteral(hash.ids)); - } - if (this.stringParams) { - this.push(this.objectLiteral(hash.contexts)); - this.push(this.objectLiteral(hash.types)); - } - - this.push(this.objectLiteral(hash.values)); - }, - - // [pushString] - // - // On stack, before: ... - // On stack, after: quotedString(string), ... - // - // Push a quoted version of `string` onto the stack - pushString: function pushString(string) { - this.pushStackLiteral(this.quotedString(string)); - }, - - // [pushLiteral] - // - // On stack, before: ... - // On stack, after: value, ... - // - // Pushes a value onto the stack. This operation prevents - // the compiler from creating a temporary variable to hold - // it. - pushLiteral: function pushLiteral(value) { - this.pushStackLiteral(value); - }, - - // [pushProgram] - // - // On stack, before: ... - // On stack, after: program(guid), ... - // - // Push a program expression onto the stack. This takes - // a compile-time guid and converts it into a runtime-accessible - // expression. - pushProgram: function pushProgram(guid) { - if (guid != null) { - this.pushStackLiteral(this.programExpression(guid)); - } else { - this.pushStackLiteral(null); - } - }, - - // [registerDecorator] - // - // On stack, before: hash, program, params..., ... - // On stack, after: ... - // - // Pops off the decorator's parameters, invokes the decorator, - // and inserts the decorator into the decorators list. - registerDecorator: function registerDecorator(paramSize, name) { - var foundDecorator = this.nameLookup('decorators', name, 'decorator'), - options = this.setupHelperArgs(name, paramSize); - - this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']); - }, - - // [invokeHelper] - // - // On stack, before: hash, inverse, program, params..., ... - // On stack, after: result of helper invocation - // - // Pops off the helper's parameters, invokes the helper, - // and pushes the helper's return value onto the stack. - // - // If the helper is not found, `helperMissing` is called. - invokeHelper: function invokeHelper(paramSize, name, isSimple) { - var nonHelper = this.popStack(), - helper = this.setupHelper(paramSize, name), - simple = isSimple ? [helper.name, ' || '] : ''; - - var lookup = ['('].concat(simple, nonHelper); - if (!this.options.strict) { - lookup.push(' || ', this.aliasable('helpers.helperMissing')); - } - lookup.push(')'); - - this.push(this.source.functionCall(lookup, 'call', helper.callParams)); - }, - - // [invokeKnownHelper] - // - // On stack, before: hash, inverse, program, params..., ... - // On stack, after: result of helper invocation - // - // This operation is used when the helper is known to exist, - // so a `helperMissing` fallback is not required. - invokeKnownHelper: function invokeKnownHelper(paramSize, name) { - var helper = this.setupHelper(paramSize, name); - this.push(this.source.functionCall(helper.name, 'call', helper.callParams)); - }, - - // [invokeAmbiguous] - // - // On stack, before: hash, inverse, program, params..., ... - // On stack, after: result of disambiguation - // - // This operation is used when an expression like `{{foo}}` - // is provided, but we don't know at compile-time whether it - // is a helper or a path. - // - // This operation emits more code than the other options, - // and can be avoided by passing the `knownHelpers` and - // `knownHelpersOnly` flags at compile-time. - invokeAmbiguous: function invokeAmbiguous(name, helperCall) { - this.useRegister('helper'); - - var nonHelper = this.popStack(); - - this.emptyHash(); - var helper = this.setupHelper(0, name, helperCall); - - var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper'); - - var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')']; - if (!this.options.strict) { - lookup[0] = '(helper = '; - lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing')); - } - - this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']); - }, - - // [invokePartial] - // - // On stack, before: context, ... - // On stack after: result of partial invocation - // - // This operation pops off a context, invokes a partial with that context, - // and pushes the result of the invocation back. - invokePartial: function invokePartial(isDynamic, name, indent) { - var params = [], - options = this.setupParams(name, 1, params); - - if (isDynamic) { - name = this.popStack(); - delete options.name; - } - - if (indent) { - options.indent = JSON.stringify(indent); - } - options.helpers = 'helpers'; - options.partials = 'partials'; - options.decorators = 'container.decorators'; - - if (!isDynamic) { - params.unshift(this.nameLookup('partials', name, 'partial')); - } else { - params.unshift(name); - } - - if (this.options.compat) { - options.depths = 'depths'; - } - options = this.objectLiteral(options); - params.push(options); - - this.push(this.source.functionCall('container.invokePartial', '', params)); - }, - - // [assignToHash] - // - // On stack, before: value, ..., hash, ... - // On stack, after: ..., hash, ... - // - // Pops a value off the stack and assigns it to the current hash - assignToHash: function assignToHash(key) { - var value = this.popStack(), - context = undefined, - type = undefined, - id = undefined; - - if (this.trackIds) { - id = this.popStack(); - } - if (this.stringParams) { - type = this.popStack(); - context = this.popStack(); - } - - var hash = this.hash; - if (context) { - hash.contexts[key] = context; - } - if (type) { - hash.types[key] = type; - } - if (id) { - hash.ids[key] = id; - } - hash.values[key] = value; - }, - - pushId: function pushId(type, name, child) { - if (type === 'BlockParam') { - this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : '')); - } else if (type === 'PathExpression') { - this.pushString(name); - } else if (type === 'SubExpression') { - this.pushStackLiteral('true'); - } else { - this.pushStackLiteral('null'); - } - }, - - // HELPERS - - compiler: JavaScriptCompiler, - - compileChildren: function compileChildren(environment, options) { - var children = environment.children, - child = undefined, - compiler = undefined; - - for (var i = 0, l = children.length; i < l; i++) { - child = children[i]; - compiler = new this.compiler(); // eslint-disable-line new-cap - - var index = this.matchExistingProgram(child); - - if (index == null) { - this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children - index = this.context.programs.length; - child.index = index; - child.name = 'program' + index; - this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile); - this.context.decorators[index] = compiler.decorators; - this.context.environments[index] = child; - - this.useDepths = this.useDepths || compiler.useDepths; - this.useBlockParams = this.useBlockParams || compiler.useBlockParams; - } else { - child.index = index; - child.name = 'program' + index; - - this.useDepths = this.useDepths || child.useDepths; - this.useBlockParams = this.useBlockParams || child.useBlockParams; - } - } - }, - matchExistingProgram: function matchExistingProgram(child) { - for (var i = 0, len = this.context.environments.length; i < len; i++) { - var environment = this.context.environments[i]; - if (environment && environment.equals(child)) { - return i; - } - } - }, - - programExpression: function programExpression(guid) { - var child = this.environment.children[guid], - programParams = [child.index, 'data', child.blockParams]; - - if (this.useBlockParams || this.useDepths) { - programParams.push('blockParams'); - } - if (this.useDepths) { - programParams.push('depths'); - } - - return 'container.program(' + programParams.join(', ') + ')'; - }, - - useRegister: function useRegister(name) { - if (!this.registers[name]) { - this.registers[name] = true; - this.registers.list.push(name); - } - }, - - push: function push(expr) { - if (!(expr instanceof Literal)) { - expr = this.source.wrap(expr); - } - - this.inlineStack.push(expr); - return expr; - }, - - pushStackLiteral: function pushStackLiteral(item) { - this.push(new Literal(item)); - }, - - pushSource: function pushSource(source) { - if (this.pendingContent) { - this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation)); - this.pendingContent = undefined; - } - - if (source) { - this.source.push(source); - } - }, - - replaceStack: function replaceStack(callback) { - var prefix = ['('], - stack = undefined, - createdStack = undefined, - usedLiteral = undefined; - - /* istanbul ignore next */ - if (!this.isInline()) { - throw new _exception2['default']('replaceStack on non-inline'); - } - - // We want to merge the inline statement into the replacement statement via ',' - var top = this.popStack(true); - - if (top instanceof Literal) { - // Literals do not need to be inlined - stack = [top.value]; - prefix = ['(', stack]; - usedLiteral = true; - } else { - // Get or create the current stack name for use by the inline - createdStack = true; - var _name = this.incrStack(); - - prefix = ['((', this.push(_name), ' = ', top, ')']; - stack = this.topStack(); - } - - var item = callback.call(this, stack); - - if (!usedLiteral) { - this.popStack(); - } - if (createdStack) { - this.stackSlot--; - } - this.push(prefix.concat(item, ')')); - }, - - incrStack: function incrStack() { - this.stackSlot++; - if (this.stackSlot > this.stackVars.length) { - this.stackVars.push('stack' + this.stackSlot); - } - return this.topStackName(); - }, - topStackName: function topStackName() { - return 'stack' + this.stackSlot; - }, - flushInline: function flushInline() { - var inlineStack = this.inlineStack; - this.inlineStack = []; - for (var i = 0, len = inlineStack.length; i < len; i++) { - var entry = inlineStack[i]; - /* istanbul ignore if */ - if (entry instanceof Literal) { - this.compileStack.push(entry); - } else { - var stack = this.incrStack(); - this.pushSource([stack, ' = ', entry, ';']); - this.compileStack.push(stack); - } - } - }, - isInline: function isInline() { - return this.inlineStack.length; - }, - - popStack: function popStack(wrapped) { - var inline = this.isInline(), - item = (inline ? this.inlineStack : this.compileStack).pop(); - - if (!wrapped && item instanceof Literal) { - return item.value; - } else { - if (!inline) { - /* istanbul ignore next */ - if (!this.stackSlot) { - throw new _exception2['default']('Invalid stack pop'); - } - this.stackSlot--; - } - return item; - } - }, - - topStack: function topStack() { - var stack = this.isInline() ? this.inlineStack : this.compileStack, - item = stack[stack.length - 1]; - - /* istanbul ignore if */ - if (item instanceof Literal) { - return item.value; - } else { - return item; - } - }, - - contextName: function contextName(context) { - if (this.useDepths && context) { - return 'depths[' + context + ']'; - } else { - return 'depth' + context; - } - }, - - quotedString: function quotedString(str) { - return this.source.quotedString(str); - }, - - objectLiteral: function objectLiteral(obj) { - return this.source.objectLiteral(obj); - }, - - aliasable: function aliasable(name) { - var ret = this.aliases[name]; - if (ret) { - ret.referenceCount++; - return ret; - } - - ret = this.aliases[name] = this.source.wrap(name); - ret.aliasable = true; - ret.referenceCount = 1; - - return ret; - }, - - setupHelper: function setupHelper(paramSize, name, blockHelper) { - var params = [], - paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper); - var foundHelper = this.nameLookup('helpers', name, 'helper'), - callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : {}'); - - return { - params: params, - paramsInit: paramsInit, - name: foundHelper, - callParams: [callContext].concat(params) - }; - }, - - setupParams: function setupParams(helper, paramSize, params) { - var options = {}, - contexts = [], - types = [], - ids = [], - objectArgs = !params, - param = undefined; - - if (objectArgs) { - params = []; - } - - options.name = this.quotedString(helper); - options.hash = this.popStack(); - - if (this.trackIds) { - options.hashIds = this.popStack(); - } - if (this.stringParams) { - options.hashTypes = this.popStack(); - options.hashContexts = this.popStack(); - } - - var inverse = this.popStack(), - program = this.popStack(); - - // Avoid setting fn and inverse if neither are set. This allows - // helpers to do a check for `if (options.fn)` - if (program || inverse) { - options.fn = program || 'container.noop'; - options.inverse = inverse || 'container.noop'; - } - - // The parameters go on to the stack in order (making sure that they are evaluated in order) - // so we need to pop them off the stack in reverse order - var i = paramSize; - while (i--) { - param = this.popStack(); - params[i] = param; - - if (this.trackIds) { - ids[i] = this.popStack(); - } - if (this.stringParams) { - types[i] = this.popStack(); - contexts[i] = this.popStack(); - } - } - - if (objectArgs) { - options.args = this.source.generateArray(params); - } - - if (this.trackIds) { - options.ids = this.source.generateArray(ids); - } - if (this.stringParams) { - options.types = this.source.generateArray(types); - options.contexts = this.source.generateArray(contexts); - } - - if (this.options.data) { - options.data = 'data'; - } - if (this.useBlockParams) { - options.blockParams = 'blockParams'; - } - return options; - }, - - setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) { - var options = this.setupParams(helper, paramSize, params); - options = this.objectLiteral(options); - if (useRegister) { - this.useRegister('options'); - params.push('options'); - return ['options=', options]; - } else if (params) { - params.push(options); - return ''; - } else { - return options; - } - } - }; - - (function () { - var reservedWords = ('break else new var' + ' case finally return void' + ' catch for switch while' + ' continue function this with' + ' default if throw' + ' delete in try' + ' do instanceof typeof' + ' abstract enum int short' + ' boolean export interface static' + ' byte extends long super' + ' char final native synchronized' + ' class float package throws' + ' const goto private transient' + ' debugger implements protected volatile' + ' double import public let yield await' + ' null true false').split(' '); - - var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {}; - - for (var i = 0, l = reservedWords.length; i < l; i++) { - compilerWords[reservedWords[i]] = true; - } - })(); - - JavaScriptCompiler.isValidJavaScriptVariableName = function (name) { - return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name); - }; - - function strictLookup(requireTerminal, compiler, parts, type) { - var stack = compiler.popStack(), - i = 0, - len = parts.length; - if (requireTerminal) { - len--; - } - - for (; i < len; i++) { - stack = compiler.nameLookup(stack, parts[i], type); - } - - if (requireTerminal) { - return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')']; - } else { - return stack; - } - } - - exports['default'] = JavaScriptCompiler; - module.exports = exports['default']; - -/***/ }, -/* 29 */ -/***/ function(module, exports, __webpack_require__) { - - /* global define */ - 'use strict'; - - exports.__esModule = true; - - var _utils = __webpack_require__(5); - - var SourceNode = undefined; - - try { - /* istanbul ignore next */ - if (false) { - // We don't support this in AMD environments. For these environments, we asusme that - // they are running on the browser and thus have no need for the source-map library. - var SourceMap = require('source-map'); - SourceNode = SourceMap.SourceNode; - } - } catch (err) {} - /* NOP */ - - /* istanbul ignore if: tested but not covered in istanbul due to dist build */ - if (!SourceNode) { - SourceNode = function (line, column, srcFile, chunks) { - this.src = ''; - if (chunks) { - this.add(chunks); - } - }; - /* istanbul ignore next */ - SourceNode.prototype = { - add: function add(chunks) { - if (_utils.isArray(chunks)) { - chunks = chunks.join(''); - } - this.src += chunks; - }, - prepend: function prepend(chunks) { - if (_utils.isArray(chunks)) { - chunks = chunks.join(''); - } - this.src = chunks + this.src; - }, - toStringWithSourceMap: function toStringWithSourceMap() { - return { code: this.toString() }; - }, - toString: function toString() { - return this.src; - } - }; - } - - function castChunk(chunk, codeGen, loc) { - if (_utils.isArray(chunk)) { - var ret = []; - - for (var i = 0, len = chunk.length; i < len; i++) { - ret.push(codeGen.wrap(chunk[i], loc)); - } - return ret; - } else if (typeof chunk === 'boolean' || typeof chunk === 'number') { - // Handle primitives that the SourceNode will throw up on - return chunk + ''; - } - return chunk; - } - - function CodeGen(srcFile) { - this.srcFile = srcFile; - this.source = []; - } - - CodeGen.prototype = { - isEmpty: function isEmpty() { - return !this.source.length; - }, - prepend: function prepend(source, loc) { - this.source.unshift(this.wrap(source, loc)); - }, - push: function push(source, loc) { - this.source.push(this.wrap(source, loc)); - }, - - merge: function merge() { - var source = this.empty(); - this.each(function (line) { - source.add([' ', line, '\n']); - }); - return source; - }, - - each: function each(iter) { - for (var i = 0, len = this.source.length; i < len; i++) { - iter(this.source[i]); - } - }, - - empty: function empty() { - var loc = this.currentLocation || { start: {} }; - return new SourceNode(loc.start.line, loc.start.column, this.srcFile); - }, - wrap: function wrap(chunk) { - var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1]; - - if (chunk instanceof SourceNode) { - return chunk; - } - - chunk = castChunk(chunk, this, loc); - - return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk); - }, - - functionCall: function functionCall(fn, type, params) { - params = this.generateList(params); - return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']); - }, - - quotedString: function quotedString(str) { - return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 - .replace(/\u2029/g, '\\u2029') + '"'; - }, - - objectLiteral: function objectLiteral(obj) { - var pairs = []; - - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - var value = castChunk(obj[key], this); - if (value !== 'undefined') { - pairs.push([this.quotedString(key), ':', value]); - } - } - } - - var ret = this.generateList(pairs); - ret.prepend('{'); - ret.add('}'); - return ret; - }, - - generateList: function generateList(entries) { - var ret = this.empty(); - - for (var i = 0, len = entries.length; i < len; i++) { - if (i) { - ret.add(','); - } - - ret.add(castChunk(entries[i], this)); - } - - return ret; - }, - - generateArray: function generateArray(entries) { - var ret = this.generateList(entries); - ret.prepend('['); - ret.add(']'); - - return ret; - } - }; - - exports['default'] = CodeGen; - module.exports = exports['default']; - -/***/ } -/******/ ]) -}); -; -\ No newline at end of file diff --git a/extension/lib/vendor/mithril.js b/extension/lib/vendor/mithril.js @@ -1404,5 +1404,3 @@ var m = (function app(window, undefined) { return m; })(typeof window !== "undefined" ? window : {}); -if (typeof module === "object" && module != null && module.exports) module.exports = m; -else if (typeof define === "function" && define.amd) define(function() { return m }); diff --git a/extension/lib/vendor/system-csp-production.src.js b/extension/lib/vendor/system-csp-production.src.js @@ -0,0 +1,4155 @@ +/* + * SystemJS v0.19.17 + */ +(function() { +function bootstrap() {(function(__global) { + + var isWorker = typeof window == 'undefined' && typeof self != 'undefined' && typeof importScripts != 'undefined'; + var isBrowser = typeof window != 'undefined' && typeof document != 'undefined'; + var isWindows = typeof process != 'undefined' && typeof process.platform != 'undefined' && !!process.platform.match(/^win/); + + if (!__global.console) + __global.console = { assert: function() {} }; + + // IE8 support + var indexOf = Array.prototype.indexOf || function(item) { + for (var i = 0, thisLen = this.length; i < thisLen; i++) { + if (this[i] === item) { + return i; + } + } + return -1; + }; + + var defineProperty; + (function () { + try { + if (!!Object.defineProperty({}, 'a', {})) + defineProperty = Object.defineProperty; + } + catch (e) { + defineProperty = function(obj, prop, opt) { + try { + obj[prop] = opt.value || opt.get.call(obj); + } + catch(e) {} + } + } + })(); + + function addToError(err, msg) { + var newErr; + if (err instanceof Error) { + newErr = new Error(err.message, err.fileName, err.lineNumber); + if (isBrowser) { + newErr.message = err.message + '\n\t' + msg; + newErr.stack = err.stack; + } + else { + // node errors only look correct with the stack modified + newErr.message = err.message; + newErr.stack = err.stack + '\n\t' + msg; + } + } + else { + newErr = err + '\n\t' + msg; + } + + return newErr; + } + + function __eval(source, debugName, context) { + try { + new Function(source).call(context); + } + catch(e) { + throw addToError(e, 'Evaluating ' + debugName); + } + } + + var baseURI; + // environent baseURI detection + if (typeof document != 'undefined' && document.getElementsByTagName) { + baseURI = document.baseURI; + + if (!baseURI) { + var bases = document.getElementsByTagName('base'); + baseURI = bases[0] && bases[0].href || window.location.href; + } + + // sanitize out the hash and querystring + baseURI = baseURI.split('#')[0].split('?')[0]; + baseURI = baseURI.substr(0, baseURI.lastIndexOf('/') + 1); + } + else if (typeof process != 'undefined' && process.cwd) { + baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd() + '/'; + if (isWindows) + baseURI = baseURI.replace(/\\/g, '/'); + } + else if (typeof location != 'undefined') { + baseURI = __global.location.href; + } + else { + throw new TypeError('No environment baseURI'); + } + + var URL = __global.URLPolyfill || __global.URL; +/* +********************************************************************************************* + + Dynamic Module Loader Polyfill + + - Implemented exactly to the former 2014-08-24 ES6 Specification Draft Rev 27, Section 15 + http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts#august_24_2014_draft_rev_27 + + - Functions are commented with their spec numbers, with spec differences commented. + + - Spec bugs are commented in this code with links. + + - Abstract functions have been combined where possible, and their associated functions + commented. + + - Realm implementation is entirely omitted. + +********************************************************************************************* +*/ + +function Module() {} +// http://www.ecma-international.org/ecma-262/6.0/#sec-@@tostringtag +defineProperty(Module.prototype, 'toString', { + value: function() { + return 'Module'; + } +}); +function Loader(options) { + this._loader = { + loaderObj: this, + loads: [], + modules: {}, + importPromises: {}, + moduleRecords: {} + }; + + // 26.3.3.6 + defineProperty(this, 'global', { + get: function() { + return __global; + } + }); + + // 26.3.3.13 realm not implemented +} + +(function() { + +// Some Helpers + +// logs a linkset snapshot for debugging +/* function snapshot(loader) { + console.log('---Snapshot---'); + for (var i = 0; i < loader.loads.length; i++) { + var load = loader.loads[i]; + var linkSetLog = ' ' + load.name + ' (' + load.status + '): '; + + for (var j = 0; j < load.linkSets.length; j++) { + linkSetLog += '{' + logloads(load.linkSets[j].loads) + '} '; + } + console.log(linkSetLog); + } + console.log(''); +} +function logloads(loads) { + var log = ''; + for (var k = 0; k < loads.length; k++) + log += loads[k].name + (k != loads.length - 1 ? ' ' : ''); + return log; +} */ + + +/* function checkInvariants() { + // see https://bugs.ecmascript.org/show_bug.cgi?id=2603#c1 + + var loads = System._loader.loads; + var linkSets = []; + + for (var i = 0; i < loads.length; i++) { + var load = loads[i]; + console.assert(load.status == 'loading' || load.status == 'loaded', 'Each load is loading or loaded'); + + for (var j = 0; j < load.linkSets.length; j++) { + var linkSet = load.linkSets[j]; + + for (var k = 0; k < linkSet.loads.length; k++) + console.assert(loads.indexOf(linkSet.loads[k]) != -1, 'linkSet loads are a subset of loader loads'); + + if (linkSets.indexOf(linkSet) == -1) + linkSets.push(linkSet); + } + } + + for (var i = 0; i < loads.length; i++) { + var load = loads[i]; + for (var j = 0; j < linkSets.length; j++) { + var linkSet = linkSets[j]; + + if (linkSet.loads.indexOf(load) != -1) + console.assert(load.linkSets.indexOf(linkSet) != -1, 'linkSet contains load -> load contains linkSet'); + + if (load.linkSets.indexOf(linkSet) != -1) + console.assert(linkSet.loads.indexOf(load) != -1, 'load contains linkSet -> linkSet contains load'); + } + } + + for (var i = 0; i < linkSets.length; i++) { + var linkSet = linkSets[i]; + for (var j = 0; j < linkSet.loads.length; j++) { + var load = linkSet.loads[j]; + + for (var k = 0; k < load.dependencies.length; k++) { + var depName = load.dependencies[k].value; + var depLoad; + for (var l = 0; l < loads.length; l++) { + if (loads[l].name != depName) + continue; + depLoad = loads[l]; + break; + } + + // loading records are allowed not to have their dependencies yet + // if (load.status != 'loading') + // console.assert(depLoad, 'depLoad found'); + + // console.assert(linkSet.loads.indexOf(depLoad) != -1, 'linkset contains all dependencies'); + } + } + } +} */ + + // 15.2.3 - Runtime Semantics: Loader State + + // 15.2.3.11 + function createLoaderLoad(object) { + return { + // modules is an object for ES5 implementation + modules: {}, + loads: [], + loaderObj: object + }; + } + + // 15.2.3.2 Load Records and LoadRequest Objects + + // 15.2.3.2.1 + function createLoad(name) { + return { + status: 'loading', + name: name, + linkSets: [], + dependencies: [], + metadata: {} + }; + } + + // 15.2.3.2.2 createLoadRequestObject, absorbed into calling functions + + // 15.2.4 + + // 15.2.4.1 + function loadModule(loader, name, options) { + return new Promise(asyncStartLoadPartwayThrough({ + step: options.address ? 'fetch' : 'locate', + loader: loader, + moduleName: name, + // allow metadata for import https://bugs.ecmascript.org/show_bug.cgi?id=3091 + moduleMetadata: options && options.metadata || {}, + moduleSource: options.source, + moduleAddress: options.address + })); + } + + // 15.2.4.2 + function requestLoad(loader, request, refererName, refererAddress) { + // 15.2.4.2.1 CallNormalize + return new Promise(function(resolve, reject) { + resolve(loader.loaderObj.normalize(request, refererName, refererAddress)); + }) + // 15.2.4.2.2 GetOrCreateLoad + .then(function(name) { + var load; + if (loader.modules[name]) { + load = createLoad(name); + load.status = 'linked'; + // https://bugs.ecmascript.org/show_bug.cgi?id=2795 + load.module = loader.modules[name]; + return load; + } + + for (var i = 0, l = loader.loads.length; i < l; i++) { + load = loader.loads[i]; + if (load.name != name) + continue; + console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded'); + return load; + } + + load = createLoad(name); + loader.loads.push(load); + + proceedToLocate(loader, load); + + return load; + }); + } + + // 15.2.4.3 + function proceedToLocate(loader, load) { + proceedToFetch(loader, load, + Promise.resolve() + // 15.2.4.3.1 CallLocate + .then(function() { + return loader.loaderObj.locate({ name: load.name, metadata: load.metadata }); + }) + ); + } + + // 15.2.4.4 + function proceedToFetch(loader, load, p) { + proceedToTranslate(loader, load, + p + // 15.2.4.4.1 CallFetch + .then(function(address) { + // adjusted, see https://bugs.ecmascript.org/show_bug.cgi?id=2602 + if (load.status != 'loading') + return; + load.address = address; + + return loader.loaderObj.fetch({ name: load.name, metadata: load.metadata, address: address }); + }) + ); + } + + var anonCnt = 0; + + // 15.2.4.5 + function proceedToTranslate(loader, load, p) { + p + // 15.2.4.5.1 CallTranslate + .then(function(source) { + if (load.status != 'loading') + return; + + return Promise.resolve(loader.loaderObj.translate({ name: load.name, metadata: load.metadata, address: load.address, source: source })) + + // 15.2.4.5.2 CallInstantiate + .then(function(source) { + load.source = source; + return loader.loaderObj.instantiate({ name: load.name, metadata: load.metadata, address: load.address, source: source }); + }) + + // 15.2.4.5.3 InstantiateSucceeded + .then(function(instantiateResult) { + if (instantiateResult === undefined) { + load.address = load.address || '<Anonymous Module ' + ++anonCnt + '>'; + + // instead of load.kind, use load.isDeclarative + load.isDeclarative = true; + return transpile.call(loader.loaderObj, load) + .then(function(transpiled) { + // Hijack System.register to set declare function + var curSystem = __global.System; + var curRegister = curSystem.register; + curSystem.register = function(name, deps, declare) { + if (typeof name != 'string') { + declare = deps; + deps = name; + } + // store the registered declaration as load.declare + // store the deps as load.deps + load.declare = declare; + load.depsList = deps; + } + // empty {} context is closest to undefined 'this' we can get + __eval(transpiled, load.address, {}); + curSystem.register = curRegister; + }); + } + else if (typeof instantiateResult == 'object') { + load.depsList = instantiateResult.deps || []; + load.execute = instantiateResult.execute; + load.isDeclarative = false; + } + else + throw TypeError('Invalid instantiate return value'); + }) + // 15.2.4.6 ProcessLoadDependencies + .then(function() { + load.dependencies = []; + var depsList = load.depsList; + + var loadPromises = []; + for (var i = 0, l = depsList.length; i < l; i++) (function(request, index) { + loadPromises.push( + requestLoad(loader, request, load.name, load.address) + + // 15.2.4.6.1 AddDependencyLoad (load is parentLoad) + .then(function(depLoad) { + + // adjusted from spec to maintain dependency order + // this is due to the System.register internal implementation needs + load.dependencies[index] = { + key: request, + value: depLoad.name + }; + + if (depLoad.status != 'linked') { + var linkSets = load.linkSets.concat([]); + for (var i = 0, l = linkSets.length; i < l; i++) + addLoadToLinkSet(linkSets[i], depLoad); + } + + // console.log('AddDependencyLoad ' + depLoad.name + ' for ' + load.name); + // snapshot(loader); + }) + ); + })(depsList[i], i); + + return Promise.all(loadPromises); + }) + + // 15.2.4.6.2 LoadSucceeded + .then(function() { + // console.log('LoadSucceeded ' + load.name); + // snapshot(loader); + + console.assert(load.status == 'loading', 'is loading'); + + load.status = 'loaded'; + + var linkSets = load.linkSets.concat([]); + for (var i = 0, l = linkSets.length; i < l; i++) + updateLinkSetOnLoad(linkSets[i], load); + }); + }) + // 15.2.4.5.4 LoadFailed + ['catch'](function(exc) { + load.status = 'failed'; + load.exception = exc; + + var linkSets = load.linkSets.concat([]); + for (var i = 0, l = linkSets.length; i < l; i++) { + linkSetFailed(linkSets[i], load, exc); + } + + console.assert(load.linkSets.length == 0, 'linkSets not removed'); + }); + } + + // 15.2.4.7 PromiseOfStartLoadPartwayThrough absorbed into calling functions + + // 15.2.4.7.1 + function asyncStartLoadPartwayThrough(stepState) { + return function(resolve, reject) { + var loader = stepState.loader; + var name = stepState.moduleName; + var step = stepState.step; + + if (loader.modules[name]) + throw new TypeError('"' + name + '" already exists in the module table'); + + // adjusted to pick up existing loads + var existingLoad; + for (var i = 0, l = loader.loads.length; i < l; i++) { + if (loader.loads[i].name == name) { + existingLoad = loader.loads[i]; + + if (step == 'translate' && !existingLoad.source) { + existingLoad.address = stepState.moduleAddress; + proceedToTranslate(loader, existingLoad, Promise.resolve(stepState.moduleSource)); + } + + // a primary load -> use that existing linkset if it is for the direct load here + // otherwise create a new linkset unit + if (existingLoad.linkSets.length && existingLoad.linkSets[0].loads[0].name == existingLoad.name) + return existingLoad.linkSets[0].done.then(function() { + resolve(existingLoad); + }); + } + } + + var load = existingLoad || createLoad(name); + + load.metadata = stepState.moduleMetadata; + + var linkSet = createLinkSet(loader, load); + + loader.loads.push(load); + + resolve(linkSet.done); + + if (step == 'locate') + proceedToLocate(loader, load); + + else if (step == 'fetch') + proceedToFetch(loader, load, Promise.resolve(stepState.moduleAddress)); + + else { + console.assert(step == 'translate', 'translate step'); + load.address = stepState.moduleAddress; + proceedToTranslate(loader, load, Promise.resolve(stepState.moduleSource)); + } + } + } + + // Declarative linking functions run through alternative implementation: + // 15.2.5.1.1 CreateModuleLinkageRecord not implemented + // 15.2.5.1.2 LookupExport not implemented + // 15.2.5.1.3 LookupModuleDependency not implemented + + // 15.2.5.2.1 + function createLinkSet(loader, startingLoad) { + var linkSet = { + loader: loader, + loads: [], + startingLoad: startingLoad, // added see spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995 + loadingCount: 0 + }; + linkSet.done = new Promise(function(resolve, reject) { + linkSet.resolve = resolve; + linkSet.reject = reject; + }); + addLoadToLinkSet(linkSet, startingLoad); + return linkSet; + } + // 15.2.5.2.2 + function addLoadToLinkSet(linkSet, load) { + if (load.status == 'failed') + return; + + console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded on link set'); + + for (var i = 0, l = linkSet.loads.length; i < l; i++) + if (linkSet.loads[i] == load) + return; + + linkSet.loads.push(load); + load.linkSets.push(linkSet); + + // adjustment, see https://bugs.ecmascript.org/show_bug.cgi?id=2603 + if (load.status != 'loaded') { + linkSet.loadingCount++; + } + + var loader = linkSet.loader; + + for (var i = 0, l = load.dependencies.length; i < l; i++) { + if (!load.dependencies[i]) + continue; + + var name = load.dependencies[i].value; + + if (loader.modules[name]) + continue; + + for (var j = 0, d = loader.loads.length; j < d; j++) { + if (loader.loads[j].name != name) + continue; + + addLoadToLinkSet(linkSet, loader.loads[j]); + break; + } + } + // console.log('add to linkset ' + load.name); + // snapshot(linkSet.loader); + } + + // linking errors can be generic or load-specific + // this is necessary for debugging info + function doLink(linkSet) { + var error = false; + try { + link(linkSet, function(load, exc) { + linkSetFailed(linkSet, load, exc); + error = true; + }); + } + catch(e) { + linkSetFailed(linkSet, null, e); + error = true; + } + return error; + } + + // 15.2.5.2.3 + function updateLinkSetOnLoad(linkSet, load) { + // console.log('update linkset on load ' + load.name); + // snapshot(linkSet.loader); + + console.assert(load.status == 'loaded' || load.status == 'linked', 'loaded or linked'); + + linkSet.loadingCount--; + + if (linkSet.loadingCount > 0) + return; + + // adjusted for spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995 + var startingLoad = linkSet.startingLoad; + + // non-executing link variation for loader tracing + // on the server. Not in spec. + /***/ + if (linkSet.loader.loaderObj.execute === false) { + var loads = [].concat(linkSet.loads); + for (var i = 0, l = loads.length; i < l; i++) { + var load = loads[i]; + load.module = !load.isDeclarative ? { + module: _newModule({}) + } : { + name: load.name, + module: _newModule({}), + evaluated: true + }; + load.status = 'linked'; + finishLoad(linkSet.loader, load); + } + return linkSet.resolve(startingLoad); + } + /***/ + + var abrupt = doLink(linkSet); + + if (abrupt) + return; + + console.assert(linkSet.loads.length == 0, 'loads cleared'); + + linkSet.resolve(startingLoad); + } + + // 15.2.5.2.4 + function linkSetFailed(linkSet, load, exc) { + var loader = linkSet.loader; + var requests; + + checkError: + if (load) { + if (linkSet.loads[0].name == load.name) { + exc = addToError(exc, 'Error loading ' + load.name); + } + else { + for (var i = 0; i < linkSet.loads.length; i++) { + var pLoad = linkSet.loads[i]; + for (var j = 0; j < pLoad.dependencies.length; j++) { + var dep = pLoad.dependencies[j]; + if (dep.value == load.name) { + exc = addToError(exc, 'Error loading ' + load.name + ' as "' + dep.key + '" from ' + pLoad.name); + break checkError; + } + } + } + exc = addToError(exc, 'Error loading ' + load.name + ' from ' + linkSet.loads[0].name); + } + } + else { + exc = addToError(exc, 'Error linking ' + linkSet.loads[0].name); + } + + + var loads = linkSet.loads.concat([]); + for (var i = 0, l = loads.length; i < l; i++) { + var load = loads[i]; + + // store all failed load records + loader.loaderObj.failed = loader.loaderObj.failed || []; + if (indexOf.call(loader.loaderObj.failed, load) == -1) + loader.loaderObj.failed.push(load); + + var linkIndex = indexOf.call(load.linkSets, linkSet); + console.assert(linkIndex != -1, 'link not present'); + load.linkSets.splice(linkIndex, 1); + if (load.linkSets.length == 0) { + var globalLoadsIndex = indexOf.call(linkSet.loader.loads, load); + if (globalLoadsIndex != -1) + linkSet.loader.loads.splice(globalLoadsIndex, 1); + } + } + linkSet.reject(exc); + } + + // 15.2.5.2.5 + function finishLoad(loader, load) { + // add to global trace if tracing + if (loader.loaderObj.trace) { + if (!loader.loaderObj.loads) + loader.loaderObj.loads = {}; + var depMap = {}; + load.dependencies.forEach(function(dep) { + depMap[dep.key] = dep.value; + }); + loader.loaderObj.loads[load.name] = { + name: load.name, + deps: load.dependencies.map(function(dep){ return dep.key }), + depMap: depMap, + address: load.address, + metadata: load.metadata, + source: load.source, + kind: load.isDeclarative ? 'declarative' : 'dynamic' + }; + } + // if not anonymous, add to the module table + if (load.name) { + console.assert(!loader.modules[load.name], 'load not in module table'); + loader.modules[load.name] = load.module; + } + var loadIndex = indexOf.call(loader.loads, load); + if (loadIndex != -1) + loader.loads.splice(loadIndex, 1); + for (var i = 0, l = load.linkSets.length; i < l; i++) { + loadIndex = indexOf.call(load.linkSets[i].loads, load); + if (loadIndex != -1) + load.linkSets[i].loads.splice(loadIndex, 1); + } + load.linkSets.splice(0, load.linkSets.length); + } + + function doDynamicExecute(linkSet, load, linkError) { + try { + var module = load.execute(); + } + catch(e) { + linkError(load, e); + return; + } + if (!module || !(module instanceof Module)) + linkError(load, new TypeError('Execution must define a Module instance')); + else + return module; + } + + // 26.3 Loader + + // 26.3.1.1 + // defined at top + + // importPromises adds ability to import a module twice without error - https://bugs.ecmascript.org/show_bug.cgi?id=2601 + function createImportPromise(loader, name, promise) { + var importPromises = loader._loader.importPromises; + return importPromises[name] = promise.then(function(m) { + importPromises[name] = undefined; + return m; + }, function(e) { + importPromises[name] = undefined; + throw e; + }); + } + + Loader.prototype = { + // 26.3.3.1 + constructor: Loader, + // 26.3.3.2 + define: function(name, source, options) { + // check if already defined + if (this._loader.importPromises[name]) + throw new TypeError('Module is already loading.'); + return createImportPromise(this, name, new Promise(asyncStartLoadPartwayThrough({ + step: 'translate', + loader: this._loader, + moduleName: name, + moduleMetadata: options && options.metadata || {}, + moduleSource: source, + moduleAddress: options && options.address + }))); + }, + // 26.3.3.3 + 'delete': function(name) { + var loader = this._loader; + delete loader.importPromises[name]; + delete loader.moduleRecords[name]; + return loader.modules[name] ? delete loader.modules[name] : false; + }, + // 26.3.3.4 entries not implemented + // 26.3.3.5 + get: function(key) { + if (!this._loader.modules[key]) + return; + doEnsureEvaluated(this._loader.modules[key], [], this); + return this._loader.modules[key].module; + }, + // 26.3.3.7 + has: function(name) { + return !!this._loader.modules[name]; + }, + // 26.3.3.8 + 'import': function(name, parentName, parentAddress) { + if (typeof parentName == 'object') + parentName = parentName.name; + + // run normalize first + var loaderObj = this; + + // added, see https://bugs.ecmascript.org/show_bug.cgi?id=2659 + return Promise.resolve(loaderObj.normalize(name, parentName)) + .then(function(name) { + var loader = loaderObj._loader; + + if (loader.modules[name]) { + doEnsureEvaluated(loader.modules[name], [], loader._loader); + return loader.modules[name].module; + } + + return loader.importPromises[name] || createImportPromise(loaderObj, name, + loadModule(loader, name, {}) + .then(function(load) { + delete loader.importPromises[name]; + return evaluateLoadedModule(loader, load); + })); + }); + }, + // 26.3.3.9 keys not implemented + // 26.3.3.10 + load: function(name) { + var loader = this._loader; + if (loader.modules[name]) + return Promise.resolve(); + return loader.importPromises[name] || createImportPromise(this, name, new Promise(asyncStartLoadPartwayThrough({ + step: 'locate', + loader: loader, + moduleName: name, + moduleMetadata: {}, + moduleSource: undefined, + moduleAddress: undefined + })) + .then(function() { + delete loader.importPromises[name]; + })); + }, + // 26.3.3.11 + module: function(source, options) { + var load = createLoad(); + load.address = options && options.address; + var linkSet = createLinkSet(this._loader, load); + var sourcePromise = Promise.resolve(source); + var loader = this._loader; + var p = linkSet.done.then(function() { + return evaluateLoadedModule(loader, load); + }); + proceedToTranslate(loader, load, sourcePromise); + return p; + }, + // 26.3.3.12 + newModule: function (obj) { + if (typeof obj != 'object') + throw new TypeError('Expected object'); + + var m = new Module(); + + var pNames = []; + if (Object.getOwnPropertyNames && obj != null) + pNames = Object.getOwnPropertyNames(obj); + else + for (var key in obj) + pNames.push(key); + + for (var i = 0; i < pNames.length; i++) (function(key) { + defineProperty(m, key, { + configurable: false, + enumerable: true, + get: function () { + return obj[key]; + } + }); + })(pNames[i]); + + return m; + }, + // 26.3.3.14 + set: function(name, module) { + if (!(module instanceof Module)) + throw new TypeError('Loader.set(' + name + ', module) must be a module'); + this._loader.modules[name] = { + module: module + }; + }, + // 26.3.3.15 values not implemented + // 26.3.3.16 @@iterator not implemented + // 26.3.3.17 @@toStringTag not implemented + + // 26.3.3.18.1 + normalize: function(name, referrerName, referrerAddress) { + return name; + }, + // 26.3.3.18.2 + locate: function(load) { + return load.name; + }, + // 26.3.3.18.3 + fetch: function(load) { + }, + // 26.3.3.18.4 + translate: function(load) { + return load.source; + }, + // 26.3.3.18.5 + instantiate: function(load) { + } + }; + + var _newModule = Loader.prototype.newModule; +/* + * ES6 Module Declarative Linking Code - Dev Build Only + */ + function link(linkSet, linkError) { + + var loader = linkSet.loader; + + if (!linkSet.loads.length) + return; + + var loads = linkSet.loads.concat([]); + + for (var i = 0; i < loads.length; i++) { + var load = loads[i]; + + var module = doDynamicExecute(linkSet, load, linkError); + if (!module) + return; + load.module = { + name: load.name, + module: module + }; + load.status = 'linked'; + + finishLoad(loader, load); + } + } + + function evaluateLoadedModule(loader, load) { + console.assert(load.status == 'linked', 'is linked ' + load.name); + return load.module.module; + } + + function doEnsureEvaluated() {} + + function transpile() { + throw new TypeError('ES6 transpilation is only provided in the dev module loader build.'); + } +})();/* +********************************************************************************************* + + System Loader Implementation + + - Implemented to https://github.com/jorendorff/js-loaders/blob/master/browser-loader.js + + - <script type="module"> supported + +********************************************************************************************* +*/ + +var System; + +function SystemLoader() { + Loader.call(this); + this.paths = {}; +} + +// NB no specification provided for System.paths, used ideas discussed in https://github.com/jorendorff/js-loaders/issues/25 +function applyPaths(paths, name) { + // most specific (most number of slashes in path) match wins + var pathMatch = '', wildcard, maxWildcardPrefixLen = 0; + + // check to see if we have a paths entry + for (var p in paths) { + var pathParts = p.split('*'); + if (pathParts.length > 2) + throw new TypeError('Only one wildcard in a path is permitted'); + + // exact path match + if (pathParts.length == 1) { + if (name == p) + return paths[p]; + + // support trailing / in paths rules + else if (name.substr(0, p.length - 1) == p.substr(0, p.length - 1) && (name.length < p.length || name[p.length - 1] == p[p.length - 1]) && paths[p][paths[p].length - 1] == '/') + return paths[p].substr(0, paths[p].length - 1) + (name.length > p.length ? '/' + name.substr(p.length) : ''); + } + // wildcard path match + else { + var wildcardPrefixLen = pathParts[0].length; + if (wildcardPrefixLen >= maxWildcardPrefixLen && + name.substr(0, pathParts[0].length) == pathParts[0] && + name.substr(name.length - pathParts[1].length) == pathParts[1]) { + maxWildcardPrefixLen = wildcardPrefixLen; + pathMatch = p; + wildcard = name.substr(pathParts[0].length, name.length - pathParts[1].length - pathParts[0].length); + } + } + } + + var outPath = paths[pathMatch]; + if (typeof wildcard == 'string') + outPath = outPath.replace('*', wildcard); + + return outPath; +} + +// inline Object.create-style class extension +function LoaderProto() {} +LoaderProto.prototype = Loader.prototype; +SystemLoader.prototype = new LoaderProto(); +// SystemJS Loader Class and Extension helpers + +function SystemJSLoader() { + SystemLoader.call(this); + + systemJSConstructor.call(this); +} + +// inline Object.create-style class extension +function SystemProto() {}; +SystemProto.prototype = SystemLoader.prototype; +SystemJSLoader.prototype = new SystemProto(); +SystemJSLoader.prototype.constructor = SystemJSLoader; + +// remove ESML instantiate +SystemJSLoader.prototype.instantiate = function() {}; + +var systemJSConstructor; + +function hook(name, hook) { + SystemJSLoader.prototype[name] = hook(SystemJSLoader.prototype[name] || function() {}); +} +function hookConstructor(hook) { + systemJSConstructor = hook(systemJSConstructor || function() {}); +} + +function dedupe(deps) { + var newDeps = []; + for (var i = 0, l = deps.length; i < l; i++) + if (indexOf.call(newDeps, deps[i]) == -1) + newDeps.push(deps[i]) + return newDeps; +} + +function group(deps) { + var names = []; + var indices = []; + for (var i = 0, l = deps.length; i < l; i++) { + var index = indexOf.call(names, deps[i]); + if (index === -1) { + names.push(deps[i]); + indices.push([i]); + } + else { + indices[index].push(i); + } + } + return { names: names, indices: indices }; +} + +var getOwnPropertyDescriptor = true; +try { + Object.getOwnPropertyDescriptor({ a: 0 }, 'a'); +} +catch(e) { + getOwnPropertyDescriptor = false; +} + +// converts any module.exports object into an object ready for SystemJS.newModule +function getESModule(exports) { + var esModule = {}; + // don't trigger getters/setters in environments that support them + if (typeof exports == 'object' || typeof exports == 'function') { + if (getOwnPropertyDescriptor) { + var d; + for (var p in exports) + if (d = Object.getOwnPropertyDescriptor(exports, p)) + defineProperty(esModule, p, d); + } + else { + var hasOwnProperty = exports && exports.hasOwnProperty; + for (var p in exports) { + if (!hasOwnProperty || exports.hasOwnProperty(p)) + esModule[p] = exports[p]; + } + } + } + esModule['default'] = exports; + defineProperty(esModule, '__useDefault', { + value: true + }); + return esModule; +} + +function extend(a, b, prepend) { + for (var p in b) { + if (!prepend || !(p in a)) + a[p] = b[p]; + } + return a; +} + +// package configuration options +var packageProperties = ['main', 'format', 'defaultExtension', 'meta', 'map', 'basePath', 'depCache']; + +// meta first-level extends where: +// array + array appends +// object + object extends +// other properties replace +function extendMeta(a, b, prepend) { + for (var p in b) { + var val = b[p]; + if (!(p in a)) + a[p] = val; + else if (val instanceof Array && a[p] instanceof Array) + a[p] = [].concat(prepend ? val : a[p]).concat(prepend ? a[p] : val); + else if (typeof val == 'object' && val !== null && typeof a[p] == 'object') + a[p] = extend(extend({}, a[p]), val, prepend); + else if (!prepend) + a[p] = val; + } +} + +function warn(msg) { + if (this.warnings && typeof console != 'undefined' && console.warn) + console.warn(msg); +}var absURLRegEx = /^[^\/]+:\/\//; + +function readMemberExpression(p, value) { + var pParts = p.split('.'); + while (pParts.length) + value = value[pParts.shift()]; + return value; +} + +var baseURLCache = {}; +function getBaseURLObj() { + if (baseURLCache[this.baseURL]) + return baseURLCache[this.baseURL]; + + // normalize baseURL if not already + if (this.baseURL[this.baseURL.length - 1] != '/') + this.baseURL += '/'; + + var baseURL = new URL(this.baseURL, baseURI); + + this.baseURL = baseURL.href; + + return (baseURLCache[this.baseURL] = baseURL); +} + +function getMapMatch(map, name) { + var bestMatch, bestMatchLength = 0; + + for (var p in map) { + if (name.substr(0, p.length) == p && (name.length == p.length || name[p.length] == '/')) { + var curMatchLength = p.split('/').length; + if (curMatchLength <= bestMatchLength) + continue; + bestMatch = p; + bestMatchLength = curMatchLength; + } + } + + return bestMatch; +} + +function setProduction(isProduction) { + this.set('@system-env', this.newModule({ + browser: isBrowser, + node: !!this._nodeRequire, + production: isProduction + })); +} + +var baseURIObj = new URL(baseURI); + +hookConstructor(function(constructor) { + return function() { + constructor.call(this); + + // support baseURL + this.baseURL = baseURI.substr(0, baseURI.lastIndexOf('/') + 1); + + // support map + this.map = {}; + + // global behaviour flags + this.warnings = false; + this.defaultJSExtensions = false; + this.globalEvaluationScope = true; + this.pluginFirst = false; + + // by default load ".json" files as json + // leading * meta doesn't need normalization + // NB add this in next breaking release + // this.meta['*.json'] = { format: 'json' }; + + // Default settings for globalEvaluationScope: + // Disabled for WebWorker, Chrome Extensions and jsdom + if (isWorker + || isBrowser && window.chrome && window.chrome.extension + || isBrowser && navigator.userAgent.match(/^Node\.js/)) + this.globalEvaluationScope = false; + + // support the empty module, as a concept + this.set('@empty', this.newModule({})); + + setProduction.call(this, false); + }; +}); + +// include the node require since we're overriding it +if (typeof require != 'undefined' && typeof process != 'undefined' && !process.browser) + SystemJSLoader.prototype._nodeRequire = require; + +var nodeCoreModules = ['assert', 'buffer', 'child_process', 'cluster', 'console', 'constants', + 'crypto', 'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'https', 'module', 'net', 'os', 'path', + 'process', 'punycode', 'querystring', 'readline', 'repl', 'stream', 'string_decoder', 'sys', 'timers', + 'tls', 'tty', 'url', 'util', 'vm', 'zlib']; + +/* + Core SystemJS Normalization + + If a name is relative, we apply URL normalization to the page + If a name is an absolute URL, we leave it as-is + + Plain names (neither of the above) run through the map and paths + normalization phases. + + The paths normalization phase applies last (paths extension), which + defines the `decanonicalize` function and normalizes everything into + a URL. + */ +hook('normalize', function(normalize) { + return function(name, parentName) { + // first run map config + if (name[0] != '.' && name[0] != '/' && !name.match(absURLRegEx)) { + var mapMatch = getMapMatch(this.map, name); + if (mapMatch) + name = this.map[mapMatch] + name.substr(mapMatch.length); + } + + // dynamically load node-core modules when requiring `@node/fs` for example + if (name.substr(0, 6) == '@node/' && nodeCoreModules.indexOf(name.substr(6)) != -1) { + if (!this._nodeRequire) + throw new TypeError('Error loading ' + name + '. Can only load node core modules in Node.'); + this.set(name, this.newModule(getESModule(this._nodeRequire(name.substr(6))))); + } + + // relative URL-normalization + if (name[0] == '.' || name[0] == '/') { + if (parentName) + name = new URL(name, parentName.replace(/#/g, '%05')).href.replace(/%05/g, '#'); + else + name = new URL(name, baseURIObj).href; + } + + // if the module is in the registry already, use that + if (this.has(name)) + return name; + + if (name.match(absURLRegEx)) { + // defaultJSExtensions backwards compatibility + if (this.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js') + name += '.js'; + return name; + } + + // applyPaths implementation provided from ModuleLoader system.js source + name = applyPaths(this.paths, name) || name; + + // defaultJSExtensions backwards compatibility + if (this.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js') + name += '.js'; + + // ./x, /x -> page-relative + if (name[0] == '.' || name[0] == '/') + return new URL(name, baseURIObj).href; + // x -> baseURL-relative + else + return new URL(name, getBaseURLObj.call(this)).href; + }; +}); + +// percent encode just '#' in urls if using HTTP requests +var httpRequest = typeof XMLHttpRequest != 'undefined'; +hook('locate', function(locate) { + return function(load) { + return Promise.resolve(locate.call(this, load)) + .then(function(address) { + if (httpRequest) + return address.replace(/#/g, '%23'); + return address; + }); + }; +}); + +/* + * Fetch with authorization + */ +hook('fetch', function() { + return function(load) { + return new Promise(function(resolve, reject) { + fetchTextFromURL(load.address, load.metadata.authorization, resolve, reject); + }); + }; +}); + +/* + __useDefault + + When a module object looks like: + newModule( + __useDefault: true, + default: 'some-module' + }) + + Then importing that module provides the 'some-module' + result directly instead of the full module. + + Useful for eg module.exports = function() {} +*/ +hook('import', function(systemImport) { + return function(name, parentName, parentAddress) { + if (parentName && parentName.name) + warn.call(this, 'SystemJS.import(name, { name: parentName }) is deprecated for SystemJS.import(name, parentName), while importing ' + name + ' from ' + parentName.name); + return systemImport.call(this, name, parentName, parentAddress).then(function(module) { + return module.__useDefault ? module['default'] : module; + }); + }; +}); + +/* + * Allow format: 'detect' meta to enable format detection + */ +hook('translate', function(systemTranslate) { + return function(load) { + if (load.metadata.format == 'detect') + load.metadata.format = undefined; + return systemTranslate.call(this, load); + }; +}); + + +/* + * JSON format support + * + * Supports loading JSON files as a module format itself + * + * Usage: + * + * SystemJS.config({ + * meta: { + * '*.json': { format: 'json' } + * } + * }); + * + * Module is returned as if written: + * + * export default {JSON} + * + * No named exports are provided + * + * Files ending in ".json" are treated as json automatically by SystemJS + */ +hook('instantiate', function(instantiate) { + return function(load) { + if (load.metadata.format == 'json' && !this.builder) { + var entry = load.metadata.entry = createEntry(); + entry.deps = []; + entry.execute = function() { + try { + return JSON.parse(load.source); + } + catch(e) { + throw new Error("Invalid JSON file " + load.name); + } + }; + } + }; +}) + +/* + Extend config merging one deep only + + loader.config({ + some: 'random', + config: 'here', + deep: { + config: { too: 'too' } + } + }); + + <=> + + loader.some = 'random'; + loader.config = 'here' + loader.deep = loader.deep || {}; + loader.deep.config = { too: 'too' }; + + + Normalizes meta and package configs allowing for: + + SystemJS.config({ + meta: { + './index.js': {} + } + }); + + To become + + SystemJS.meta['https://thissite.com/index.js'] = {}; + + For easy normalization canonicalization with latest URL support. + +*/ +SystemJSLoader.prototype.env = 'development'; + +SystemJSLoader.prototype.config = function(cfg) { + var loader = this; + + if ('warnings' in cfg) + loader.warnings = cfg.warnings; + + // transpiler deprecation path + if (cfg.transpilerRuntime === false) + loader._loader.loadedTranspilerRuntime = true; + + // always configure baseURL first + if (cfg.baseURL) { + var hasConfig = false; + function checkHasConfig(obj) { + for (var p in obj) + return true; + } + if (checkHasConfig(loader.packages) || checkHasConfig(loader.meta) || checkHasConfig(loader.depCache) || checkHasConfig(loader.bundles) || checkHasConfig(loader.packageConfigPaths)) + throw new TypeError('Incorrect configuration order. The baseURL must be configured with the first SystemJS.config call.'); + + loader.baseURL = cfg.baseURL; + + // sanitize baseURL + getBaseURLObj.call(loader); + } + + if (cfg.defaultJSExtensions) { + loader.defaultJSExtensions = cfg.defaultJSExtensions; + warn.call(loader, 'The defaultJSExtensions configuration option is deprecated, use packages configuration instead.'); + } + + if (cfg.pluginFirst) + loader.pluginFirst = cfg.pluginFirst; + + if (cfg.production) + setProduction.call(loader, true); + + if (cfg.paths) { + for (var p in cfg.paths) + loader.paths[p] = cfg.paths[p]; + } + + if (cfg.map) { + var objMaps = ''; + for (var p in cfg.map) { + var v = cfg.map[p]; + + // object map backwards-compat into packages configuration + if (typeof v !== 'string') { + objMaps += (objMaps.length ? ', ' : '') + '"' + p + '"'; + + var prop = loader.decanonicalize(p + (p[p.length - 1] != '/' ? '/' : '')); + + // allow trailing '/' in package config + if (prop[prop.length - 1] == '/') + prop = prop.substr(0, prop.length - 1); + + // if a package main, revert it + var pkgMatch = ''; + for (var pkg in loader.packages) { + if (prop.substr(0, pkg.length) == pkg + && (!prop[pkg.length] || prop[pkg.length] == '/') + && pkgMatch.split('/').length < pkg.split('/').length) + pkgMatch = pkg; + } + if (pkgMatch && loader.packages[pkgMatch].main) + prop = prop.substr(0, prop.length - loader.packages[pkgMatch].main.length - 1); + + var pkg = loader.packages[prop] = loader.packages[prop] || {}; + pkg.map = v; + } + else { + loader.map[p] = v; + } + } + if (objMaps) + warn.call(loader, 'The map configuration for ' + objMaps + ' uses object submaps, which is deprecated in global map.\nUpdate this to use package contextual map with configs like SystemJS.config({ packages: { "' + p + '": { map: {...} } } }).'); + } + + if (cfg.packageConfigPaths) { + var packageConfigPaths = []; + for (var i = 0; i < cfg.packageConfigPaths.length; i++) { + var path = cfg.packageConfigPaths[i]; + var packageLength = Math.max(path.lastIndexOf('*') + 1, path.lastIndexOf('/')); + var normalized = loader.decanonicalize(path.substr(0, packageLength) + '/'); + normalized = normalized.substr(0, normalized.length - 1) + path.substr(packageLength); + packageConfigPaths[i] = normalized; + } + loader.packageConfigPaths = packageConfigPaths; + } + + if (cfg.bundles) { + for (var p in cfg.bundles) { + var bundle = []; + for (var i = 0; i < cfg.bundles[p].length; i++) + bundle.push(loader.decanonicalize(cfg.bundles[p][i])); + loader.bundles[p] = bundle; + } + } + + if (cfg.packages) { + for (var p in cfg.packages) { + if (p.match(/^([^\/]+:)?\/\/$/)) + throw new TypeError('"' + p + '" is not a valid package name.'); + + // trailing slash allows paths matches here + // NB deprecate this to just remove trailing / + // as decanonicalize doesn't respond to trailing / + // and paths wildcards should deprecate + var prop = loader.decanonicalize(p + (p[p.length - 1] != '/' ? '/' : '')); + + // allow trailing '/' in package config + if (prop[prop.length - 1] == '/') + prop = prop.substr(0, prop.length - 1); + + loader.packages[prop] = loader.packages[prop] || {}; + + // meta backwards compatibility + if (cfg.packages[p].modules) { + warn.call(loader, 'Package ' + p + ' is configured with "modules", which is deprecated as it has been renamed to "meta".'); + cfg.packages[p].meta = cfg.packages[p].modules; + delete cfg.packages[p].modules; + } + + for (var q in cfg.packages[p]) + if (indexOf.call(packageProperties, q) == -1) + warn.call(loader, '"' + q + '" is not a valid package configuration option in package ' + p); + + extendMeta(loader.packages[prop], cfg.packages[p]); + } + } + + for (var c in cfg) { + var v = cfg[c]; + var normalizeProp = false; + + if (c == 'baseURL' || c == 'map' || c == 'packages' || c == 'bundles' || c == 'paths' || c == 'warnings' || c == 'packageConfigPaths') + continue; + + if (typeof v != 'object' || v instanceof Array) { + loader[c] = v; + } + else { + loader[c] = loader[c] || {}; + + if (c == 'meta' || c == 'depCache') + normalizeProp = true; + + for (var p in v) { + // base-level wildcard meta does not normalize to retain catch-all quality + if (c == 'meta' && p[0] == '*') + loader[c][p] = v[p]; + else if (normalizeProp) + loader[c][loader.decanonicalize(p)] = v[p]; + else + loader[c][p] = v[p]; + } + } + } +};/* + * Package Configuration Extension + * + * Example: + * + * SystemJS.packages = { + * jquery: { + * basePath: 'lib', // optionally only use a subdirectory within the package + * main: 'index.js', // when not set, package name is requested directly + * format: 'amd', + * defaultExtension: 'ts', // defaults to 'js', can be set to false + * modules: { + * '*.ts': { + * loader: 'typescript' + * }, + * 'vendor/sizzle.js': { + * format: 'global' + * } + * }, + * map: { + * // map internal require('sizzle') to local require('./vendor/sizzle') + * sizzle: './vendor/sizzle.js', + * // map any internal or external require of 'jquery/vendor/another' to 'another/index.js' + * './vendor/another.js': './another/index.js', + * // test.js / test -> lib/test.js + * './test.js': './lib/test.js', + * + * // environment-specific map configurations + * './index.js': { + * '~browser': './index-node.js' + * } + * }, + * // allows for setting package-prefixed depCache + * // keys are normalized module names relative to the package itself + * depCache: { + * // import 'package/index.js' loads in parallel package/lib/test.js,package/vendor/sizzle.js + * './index.js': ['./test'], + * './test.js': ['external-dep'], + * 'external-dep/path.js': ['./another.js'] + * } + * } + * }; + * + * Then: + * import 'jquery' -> jquery/index.js + * import 'jquery/submodule' -> jquery/submodule.js + * import 'jquery/submodule.ts' -> jquery/submodule.ts loaded as typescript + * import 'jquery/vendor/another' -> another/index.js + * + * Detailed Behaviours + * - main can have a leading "./" can be added optionally + * - map and defaultExtension are applied to the main + * - defaultExtension adds the extension only if the exact extension is not present + * - defaultJSExtensions applies after map when defaultExtension is not set + * - if a meta value is available for a module, map and defaultExtension are skipped + * - like global map, package map also applies to subpaths (sizzle/x, ./vendor/another/sub) + * - condition module map is '@env' module in package or '@system-env' globally + * - map targets support conditional interpolation ('./x': './x.#{|env}.js') + * - internal package map targets cannot use boolean conditionals + * + * In addition, the following modules properties will be allowed to be package + * -relative as well in the package module config: + * + * - loader + * - alias + * + * + * Package Configuration Loading + * + * Not all packages may already have their configuration present in the System config + * For these cases, a list of packageConfigPaths can be provided, which when matched against + * a request, will first request a ".json" file by the package name to derive the package + * configuration from. This allows dynamic loading of non-predetermined code, a key use + * case in SystemJS. + * + * Example: + * + * SystemJS.packageConfigPaths = ['packages/test/package.json', 'packages/*.json']; + * + * // will first request 'packages/new-package/package.json' for the package config + * // before completing the package request to 'packages/new-package/path' + * SystemJS.import('packages/new-package/path'); + * + * // will first request 'packages/test/package.json' before the main + * SystemJS.import('packages/test'); + * + * When a package matches packageConfigPaths, it will always send a config request for + * the package configuration. + * The package name itself is taken to be the match up to and including the last wildcard + * or trailing slash. + * The most specific package config path will be used. + * Any existing package configurations for the package will deeply merge with the + * package config, with the existing package configurations taking preference. + * To opt-out of the package configuration request for a package that matches + * packageConfigPaths, use the { configured: true } package config option. + * + */ +(function() { + + hookConstructor(function(constructor) { + return function() { + constructor.call(this); + this.packages = {}; + this.packageConfigPaths = {}; + }; + }); + + function getPackage(loader, normalized) { + // use most specific package + var curPkg, curPkgLen = 0, pkgLen; + for (var p in loader.packages) { + if (normalized.substr(0, p.length) === p && (normalized.length === p.length || normalized[p.length] === '/')) { + pkgLen = p.split('/').length; + if (pkgLen > curPkgLen) { + curPkg = p; + curPkgLen = pkgLen; + } + } + } + return curPkg; + } + + function getBasePath(pkg) { + // sanitize basePath + var basePath = pkg.basePath && pkg.basePath != '.' ? pkg.basePath : ''; + if (basePath) { + if (basePath.substr(0, 2) == './') + basePath = basePath.substr(2); + if (basePath[basePath.length - 1] != '/') + basePath += '/'; + } + return basePath; + } + + function addDefaultExtension(loader, pkg, pkgName, basePath, subPath, skipExtensions) { + // don't apply extensions to folders or if defaultExtension = false + if (!subPath || subPath[subPath.length - 1] == '/' || skipExtensions || pkg.defaultExtension === false) + return subPath; + + // NB are you sure about this? + // skip if we have interpolation conditional syntax in subPath? + if (subPath.match(interpolationRegEx)) + return subPath; + + var metaMatch = false; + + // exact meta or meta with any content after the last wildcard skips extension + if (pkg.meta) + getMetaMatches(pkg.meta, subPath, function(metaPattern, matchMeta, matchDepth) { + if (matchDepth == 0 || metaPattern.lastIndexOf('*') != metaPattern.length - 1) + return metaMatch = true; + }); + + // exact global meta or meta with any content after the last wildcard skips extension + if (!metaMatch && loader.meta) + getMetaMatches(loader.meta, pkgName + '/' + basePath + subPath, function(metaPattern, matchMeta, matchDepth) { + if (matchDepth == 0 || metaPattern.lastIndexOf('*') != metaPattern.length - 1) + return metaMatch = true; + }); + + if (metaMatch) + return subPath; + + // work out what the defaultExtension is and add if not there already + // NB reconsider if default should really be ".js"? + var defaultExtension = '.' + (pkg.defaultExtension || 'js'); + if (subPath.substr(subPath.length - defaultExtension.length) != defaultExtension) + return subPath + defaultExtension; + else + return subPath; + } + + function applyPackageConfigSync(loader, pkg, pkgName, subPath, skipExtensions) { + // main + if (!subPath) { + if (pkg.main) + subPath = pkg.main.substr(0, 2) == './' ? pkg.main.substr(2) : pkg.main; + // also no submap if name is package itself (import 'pkg' -> 'path/to/pkg.js') + else + // NB can add a default package main convention here when defaultJSExtensions is deprecated + // if it becomes internal to the package then it would no longer be an exit path + return pkgName + (loader.defaultJSExtensions ? '.js' : ''); + } + + var basePath = getBasePath(pkg); + + // map config checking without then with extensions + if (pkg.map) { + var mapPath = './' + subPath; + + var mapMatch = getMapMatch(pkg.map, mapPath); + + // we then check map with the default extension adding + if (!mapMatch) { + mapPath = './' + addDefaultExtension(loader, pkg, pkgName, basePath, subPath, skipExtensions); + if (mapPath != './' + subPath) + mapMatch = getMapMatch(pkg.map, mapPath); + } + if (mapMatch) + return doMapSync(loader, pkg, pkgName, basePath, mapMatch, mapPath, skipExtensions); + } + + // normal package resolution + return pkgName + '/' + basePath + addDefaultExtension(loader, pkg, pkgName, basePath, subPath, skipExtensions); + } + + function doMapSync(loader, pkg, pkgName, basePath, mapMatch, path, skipExtensions) { + var mapped = pkg.map[mapMatch]; + + // ignore conditionals in sync + if (typeof mapped != 'string') + mapped = mapMatch = path; + + // package map to main / base-level + if (mapped == '.') + mapped = pkgName; + + // internal package map + else if (mapped.substr(0, 2) == './') + return pkgName + '/' + basePath + addDefaultExtension(loader, pkg, pkgName, basePath, mapped.substr(2) + path.substr(mapMatch.length), skipExtensions); + + // external map reference + return loader.normalizeSync(mapped + path.substr(mapMatch.length), pkgName + '/'); + } + + function applyPackageConfig(loader, pkg, pkgName, subPath, skipExtensions) { + // main + if (!subPath) { + if (pkg.main) + subPath = pkg.main.substr(0, 2) == './' ? pkg.main.substr(2) : pkg.main; + // also no submap if name is package itself (import 'pkg' -> 'path/to/pkg.js') + else + // NB can add a default package main convention here when defaultJSExtensions is deprecated + // if it becomes internal to the package then it would no longer be an exit path + return Promise.resolve(pkgName + (loader.defaultJSExtensions ? '.js' : '')); + } + + var basePath = getBasePath(pkg); + + // map config checking without then with extensions + var mapPath, mapMatch; + + if (pkg.map) { + mapPath = './' + subPath; + mapMatch = getMapMatch(pkg.map, mapPath); + + // we then check map with the default extension adding + if (!mapMatch) { + mapPath = './' + addDefaultExtension(loader, pkg, pkgName, basePath, subPath, skipExtensions); + if (mapPath != './' + subPath) + mapMatch = getMapMatch(pkg.map, mapPath); + } + } + + return (mapMatch ? doMap(loader, pkg, pkgName, basePath, mapMatch, mapPath, skipExtensions) : Promise.resolve()) + .then(function(mapped) { + if (mapped) + return Promise.resolve(mapped); + + // normal package resolution / fallback resolution for no conditional match + return Promise.resolve(pkgName + '/' + basePath + addDefaultExtension(loader, pkg, pkgName, basePath, subPath, skipExtensions)); + }); + } + + function doStringMap(loader, pkg, pkgName, basePath, mapMatch, mapped, path, skipExtensions) { + // NB the interpolation cases should strictly skip subsequent interpolation + + // package map to main / base-level + if (mapped == '.') + mapped = pkgName; + + // internal package map + else if (mapped.substr(0, 2) == './') + return Promise.resolve(pkgName + '/' + basePath + addDefaultExtension(loader, pkg, pkgName, basePath, mapped.substr(2) + path.substr(mapMatch.length), skipExtensions)) + .then(function(name) { + return interpolateConditional.call(loader, name, pkgName + '/'); + }); + + // external map reference + // NB deprecate the use of the second argument here -> should be fully global reference + return loader.normalize(mapped + path.substr(mapMatch.length), pkgName + '/'); + } + + function doMap(loader, pkg, pkgName, basePath, mapMatch, path, skipExtensions) { + var mapped = pkg.map[mapMatch]; + + if (typeof mapped == 'string') + return doStringMap(loader, pkg, pkgName, basePath, mapMatch, mapped, path, skipExtensions); + + // we use a special conditional syntax to allow the builder to handle conditional branch points further + if (loader.builder) + return Promise.resolve(pkgName + '/#:' + path); + + // map object -> conditional map + return loader['import'](pkg.map['@env'] || '@system-env', pkgName) + .then(function(env) { + // first map condition to match is used + for (var e in mapped) { + var negate = e[0] == '~'; + + var value = readMemberExpression(negate ? e.substr(1) : e, env); + + if (!negate && value || negate && !value) + return mapped[e]; + } + }) + .then(function(mapped) { + if (mapped) + return doStringMap(loader, pkg, pkgName, basePath, mapMatch, mapped, path, skipExtensions); + + // no environment match -> fallback to original subPath by returning undefined + }); + } + + // normalizeSync = decanonicalize + package resolution + SystemJSLoader.prototype.normalizeSync = SystemJSLoader.prototype.decanonicalize = SystemJSLoader.prototype.normalize; + + // decanonicalize must JUST handle package defaultExtension: false case when defaultJSExtensions is set + // to be deprecated! + hook('decanonicalize', function(decanonicalize) { + return function(name, parentName) { + var decanonicalized = decanonicalize.call(this, name, parentName); + + if (!this.defaultJSExtensions) + return decanonicalized; + + var pkgName = getPackage(this, decanonicalized); + + var defaultExtension = name[name.length - 1] == '/' ? false : pkgName && this.packages[pkgName].defaultExtension; + + if ((defaultExtension === false || defaultExtension && defaultExtension != '.js') && name.substr(name.length - 3, 3) != '.js' && decanonicalized.substr(decanonicalized.length - 3, 3) == '.js') + decanonicalized = decanonicalized.substr(0, decanonicalized.length - 3); + + return decanonicalized; + }; + }); + + hook('normalizeSync', function(normalizeSync) { + return function(name, parentName, isPlugin) { + warn.call(this, 'SystemJS.normalizeSync has been deprecated for SystemJS.decanonicalize.'); + + var loader = this; + isPlugin = isPlugin === true; + + // apply contextual package map first + // (we assume the parent package config has already been loaded) + if (parentName) + var parentPackageName = getPackage(loader, parentName) || + loader.defaultJSExtensions && parentName.substr(parentName.length - 3, 3) == '.js' && + getPackage(loader, parentName.substr(0, parentName.length - 3)); + + var parentPackage = parentPackageName && loader.packages[parentPackageName]; + + // remove any parent basePath from parentName + if (parentPackage) { + var parentBasePath = getBasePath(parentPackage); + if (parentBasePath && parentName.substr(parentPackageName.length + 1, parentBasePath.length) == parentBasePath) + parentName = parentPackageName + parentName.substr(parentPackageName.length + parentBasePath.length); + } + + // ignore . since internal maps handled by standard package resolution + if (parentPackage && name[0] != '.') { + var parentMap = parentPackage.map; + var parentMapMatch = parentMap && getMapMatch(parentMap, name); + + if (parentMapMatch && typeof parentMap[parentMapMatch] == 'string') + return doMapSync(loader, parentPackage, parentPackageName, getBasePath(parentPackage), parentMapMatch, name, isPlugin); + } + + var defaultJSExtension = loader.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js'; + + // apply map, core, paths, contextual package map + var normalized = normalizeSync.call(loader, name, parentName); + + // undo defaultJSExtension + if (defaultJSExtension && normalized.substr(normalized.length - 3, 3) != '.js') + defaultJSExtension = false; + if (defaultJSExtension) + normalized = normalized.substr(0, normalized.length - 3); + + var pkgConfigMatch = getPackageConfigMatch(loader, normalized); + var pkgName = pkgConfigMatch && pkgConfigMatch.packageName || getPackage(loader, normalized); + + if (!pkgName) + return normalized + (defaultJSExtension ? '.js' : ''); + + var subPath = normalized.substr(pkgName.length + 1); + + return applyPackageConfigSync(loader, loader.packages[pkgName] || {}, pkgName, subPath, isPlugin); + }; + }); + + hook('normalize', function(normalize) { + return function(name, parentName, isPlugin) { + var loader = this; + isPlugin = isPlugin === true; + + return Promise.resolve() + .then(function() { + // apply contextual package map first + // (we assume the parent package config has already been loaded) + if (parentName) + var parentPackageName = getPackage(loader, parentName) || + loader.defaultJSExtensions && parentName.substr(parentName.length - 3, 3) == '.js' && + getPackage(loader, parentName.substr(0, parentName.length - 3)); + + var parentPackage = parentPackageName && loader.packages[parentPackageName]; + + // remove any parent basePath from parentName + if (parentPackage) { + var parentBasePath = getBasePath(parentPackage); + if (parentBasePath && parentName.substr(parentPackageName.length + 1, parentBasePath.length) == parentBasePath) + parentName = parentPackageName + parentName.substr(parentPackageName.length + parentBasePath.length); + } + + // ignore . since internal maps handled by standard package resolution + if (parentPackage && name.substr(0, 2) != './') { + var parentMap = parentPackage.map; + var parentMapMatch = parentMap && getMapMatch(parentMap, name); + + if (parentMapMatch) + return doMap(loader, parentPackage, parentPackageName, parentBasePath, parentMapMatch, name, isPlugin); + } + + return Promise.resolve(); + }) + .then(function(mapped) { + if (mapped) + return mapped; + + var defaultJSExtension = loader.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js'; + + // apply map, core, paths, contextual package map + var normalized = normalize.call(loader, name, parentName); + + // undo defaultJSExtension + if (defaultJSExtension && normalized.substr(normalized.length - 3, 3) != '.js') + defaultJSExtension = false; + if (defaultJSExtension) + normalized = normalized.substr(0, normalized.length - 3); + + var pkgConfigMatch = getPackageConfigMatch(loader, normalized); + var pkgName = pkgConfigMatch && pkgConfigMatch.packageName || getPackage(loader, normalized); + + if (!pkgName) + return Promise.resolve(normalized + (defaultJSExtension ? '.js' : '')); + + var pkg = loader.packages[pkgName]; + + // if package is already configured or not a dynamic config package, use existing package config + var isConfigured = pkg && (pkg.configured || !pkgConfigMatch); + return (isConfigured ? Promise.resolve(pkg) : loadPackageConfigPath(loader, pkgName, pkgConfigMatch.configPath)) + .then(function(pkg) { + var subPath = normalized.substr(pkgName.length + 1); + + return applyPackageConfig(loader, pkg, pkgName, subPath, isPlugin); + }); + }); + }; + }); + + // check if the given normalized name matches a packageConfigPath + // if so, loads the config + var packageConfigPaths = {}; + + // data object for quick checks against package paths + function createPkgConfigPathObj(path) { + var lastWildcard = path.lastIndexOf('*'); + var length = Math.max(lastWildcard + 1, path.lastIndexOf('/')); + return { + length: length, + // NB handle regex control character escapes or simply create a test function here + regEx: new RegExp('^(' + path.substr(0, length).replace(/\*/g, '[^\\/]+') + ')(\\/|$)'), + wildcard: lastWildcard != -1 + }; + } + + // most specific match wins + function getPackageConfigMatch(loader, normalized) { + var pkgName, exactMatch = false, configPath; + for (var i = 0; i < loader.packageConfigPaths.length; i++) { + var packageConfigPath = loader.packageConfigPaths[i]; + var p = packageConfigPaths[packageConfigPath] || (packageConfigPaths[packageConfigPath] = createPkgConfigPathObj(packageConfigPath)); + if (normalized.length < p.length) + continue; + var match = normalized.match(p.regEx); + if (match && (!pkgName || (!(exactMatch && p.wildcard) && pkgName.length < match[1].length))) { + pkgName = match[1]; + exactMatch = !p.wildcard; + configPath = pkgName + packageConfigPath.substr(p.length); + } + } + + if (!pkgName) + return; + + return { + packageName: pkgName, + configPath: configPath + }; + } + + function loadPackageConfigPath(loader, pkgName, pkgConfigPath) { + var configLoader = loader.pluginLoader || loader; + + // NB remove this when json is default + (configLoader.meta[pkgConfigPath] = configLoader.meta[pkgConfigPath] || {}).format = 'json'; + + return configLoader.load(pkgConfigPath) + .then(function() { + pkgConfig = configLoader.get(pkgConfigPath); + + var cfg = pkgConfig['default']; + + // support "systemjs" prefixing + if (cfg.systemjs) + cfg = cfg.systemjs; + + // modules backwards compatibility + if (cfg.modules) { + cfg.meta = cfg.modules; + warn.call(loader, 'Package config file ' + pkgConfigPath + ' is configured with "modules", which is deprecated as it has been renamed to "meta".'); + } + + // remove any non-system properties if generic config file (eg package.json) + for (var p in cfg) { + if (indexOf.call(packageProperties, p) == -1) + delete cfg[p]; + } + + // deeply-merge (to first level) config with any existing package config + var pkg = loader.packages[pkgName] = loader.packages[pkgName] || {}; + extendMeta(pkg, cfg, true); + + // support external depCache + var basePath = getBasePath(pkg); + if (cfg.depCache) { + for (var d in cfg.depCache) { + var dNormalized; + + if (d.substr(0, 2) == './') + dNormalized = pkgName + '/' + basePath + d.substr(2); + else + dNormalized = coreResolve.call(loader, d); + loader.depCache[dNormalized] = (loader.depCache[dNormalized] || []).concat(cfg.depCache[d]); + } + delete cfg.depCache; + } + + return pkg; + }); + } + + function getMetaMatches(pkgMeta, subPath, matchFn) { + // wildcard meta + var meta = {}; + var wildcardIndex; + for (var module in pkgMeta) { + // allow meta to start with ./ for flexibility + var dotRel = module.substr(0, 2) == './' ? './' : ''; + if (dotRel) + module = module.substr(2); + + wildcardIndex = module.indexOf('*'); + if (wildcardIndex === -1) + continue; + + if (module.substr(0, wildcardIndex) == subPath.substr(0, wildcardIndex) + && module.substr(wildcardIndex + 1) == subPath.substr(subPath.length - module.length + wildcardIndex + 1)) { + // alow match function to return true for an exit path + if (matchFn(module, pkgMeta[dotRel + module], module.split('/').length)) + return; + } + } + // exact meta + var exactMeta = pkgMeta[subPath] || pkgMeta['./' + subPath]; + if (exactMeta) + matchFn(exactMeta, exactMeta, 0); + } + + hook('locate', function(locate) { + return function(load) { + var loader = this; + return Promise.resolve(locate.call(this, load)) + .then(function(address) { + var pkgName = getPackage(loader, load.name); + if (pkgName) { + var pkg = loader.packages[pkgName]; + var basePath = getBasePath(pkg); + var subPath = load.name.substr(pkgName.length + basePath.length + 1); + + // format + if (pkg.format) + load.metadata.format = load.metadata.format || pkg.format; + + var meta = {}; + if (pkg.meta) { + var bestDepth = 0; + + // NB support a main shorthand in meta here? + getMetaMatches(pkg.meta, subPath, function(metaPattern, matchMeta, matchDepth) { + if (matchDepth > bestDepth) + bestDepth = matchDepth; + extendMeta(meta, matchMeta, matchDepth && bestDepth > matchDepth); + }); + + // allow alias and loader to be package-relative + if (meta.alias && meta.alias.substr(0, 2) == './') + meta.alias = pkgName + meta.alias.substr(1); + if (meta.loader && meta.loader.substr(0, 2) == './') + meta.loader = pkgName + meta.loader.substr(1); + extendMeta(load.metadata, meta); + } + } + + return address; + }); + }; + }); + +})(); +/* + * Script tag fetch + * + * When load.metadata.scriptLoad is true, we load via script tag injection. + */ +(function() { + + if (typeof document != 'undefined') + var head = document.getElementsByTagName('head')[0]; + + var curSystem; + + // if doing worker executing, this is set to the load record being executed + var workerLoad = null; + + // interactive mode handling method courtesy RequireJS + var ieEvents = head && (function() { + var s = document.createElement('script'); + var isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]'; + return s.attachEvent && !(s.attachEvent.toString && s.attachEvent.toString().indexOf('[native code') < 0) && !isOpera; + })(); + + // IE interactive-only part + // we store loading scripts array as { script: <script>, load: {...} } + var interactiveLoadingScripts = []; + var interactiveScript; + function getInteractiveScriptLoad() { + if (interactiveScript && interactiveScript.script.readyState === 'interactive') + return interactiveScript.load; + + for (var i = 0; i < interactiveLoadingScripts.length; i++) + if (interactiveLoadingScripts[i].script.readyState == 'interactive') { + interactiveScript = interactiveLoadingScripts[i]; + return interactiveScript.load; + } + } + + // System.register, System.registerDynamic, AMD define pipeline + // this is called by the above methods when they execute + // we then run the reduceRegister_ collection function either immediately + // if we are in IE and know the currently executing script (interactive) + // or later if we need to wait for the synchronous load callback to know the script + var loadingCnt = 0; + var registerQueue = []; + hook('pushRegister_', function(pushRegister) { + return function(register) { + // if using eval-execution then skip + if (pushRegister.call(this, register)) + return false; + + // if using worker execution, then we're done + if (workerLoad) + this.reduceRegister_(workerLoad, register); + + // detect if we know the currently executing load (IE) + // if so, immediately call reduceRegister + else if (ieEvents) + this.reduceRegister_(getInteractiveScriptLoad(), register); + + // otherwise, add to our execution queue + // to call reduceRegister on sync script load event + else if (loadingCnt) + registerQueue.push(register); + + // if we're not currently loading anything though + // then do the reduction against a null load + // (out of band named define or named register) + // note even in non-script environments, this catch is used + else + this.reduceRegister_(null, register); + + return true; + }; + }); + + function webWorkerImport(loader, load) { + return new Promise(function(resolve, reject) { + if (load.metadata.integrity) + reject(new Error('Subresource integrity checking is not supported in web workers.')); + + workerLoad = load; + try { + importScripts(load.address); + } + catch(e) { + workerLoad = null; + reject(e); + } + workerLoad = null; + + // if nothing registered, then something went wrong + if (!load.metadata.entry) + reject(new Error(load.address + ' did not call System.register or AMD define')); + + resolve(''); + }); + } + + // override fetch to use script injection + hook('fetch', function(fetch) { + return function(load) { + var loader = this; + + if (!load.metadata.scriptLoad || (!isBrowser && !isWorker)) + return fetch.call(this, load); + + if (isWorker) + return webWorkerImport(loader, load); + + return new Promise(function(resolve, reject) { + var s = document.createElement('script'); + + s.async = true; + + if (load.metadata.integrity) + s.setAttribute('integrity', load.metadata.integrity); + + if (ieEvents) { + s.attachEvent('onreadystatechange', complete); + interactiveLoadingScripts.push({ + script: s, + load: load + }); + } + else { + s.addEventListener('load', complete, false); + s.addEventListener('error', error, false); + } + + loadingCnt++; + + curSystem = __global.System; + + s.src = load.address; + head.appendChild(s); + + function complete(evt) { + if (s.readyState && s.readyState != 'loaded' && s.readyState != 'complete') + return; + + loadingCnt--; + + // complete call is sync on execution finish + // (in ie already done reductions) + if (!load.metadata.entry && !registerQueue.length) { + loader.reduceRegister_(load); + } + else if (!ieEvents) { + for (var i = 0; i < registerQueue.length; i++) + loader.reduceRegister_(load, registerQueue[i]); + registerQueue = []; + } + + cleanup(); + + // if nothing registered, then something went wrong + if (!load.metadata.entry && !load.metadata.bundle) + reject(new Error(load.name + ' did not call System.register or AMD define. If loading a global module configure the global name via the meta exports property for script injection support.')); + + resolve(''); + } + + function error(evt) { + cleanup(); + reject(new Error('Unable to load script ' + load.address)); + } + + function cleanup() { + __global.System = curSystem; + + if (s.detachEvent) { + s.detachEvent('onreadystatechange', complete); + for (var i = 0; i < interactiveLoadingScripts.length; i++) + if (interactiveLoadingScripts[i].script == s) { + if (interactiveScript && interactiveScript.script == s) + interactiveScript = null; + interactiveLoadingScripts.splice(i, 1); + } + } + else { + s.removeEventListener('load', complete, false); + s.removeEventListener('error', error, false); + } + + head.removeChild(s); + } + }); + }; + }); +})(); +/* + * Instantiate registry extension + * + * Supports Traceur System.register 'instantiate' output for loading ES6 as ES5. + * + * - Creates the loader.register function + * - Also supports metadata.format = 'register' in instantiate for anonymous register modules + * - Also supports metadata.deps, metadata.execute and metadata.executingRequire + * for handling dynamic modules alongside register-transformed ES6 modules + * + * + * The code here replicates the ES6 linking groups algorithm to ensure that + * circular ES6 compiled into System.register can work alongside circular AMD + * and CommonJS, identically to the actual ES6 loader. + * + */ + + +/* + * Registry side table entries in loader.defined + * Registry Entry Contains: + * - name + * - deps + * - declare for declarative modules + * - execute for dynamic modules, different to declarative execute on module + * - executingRequire indicates require drives execution for circularity of dynamic modules + * - declarative optional boolean indicating which of the above + * + * Can preload modules directly on SystemJS.defined['my/module'] = { deps, execute, executingRequire } + * + * Then the entry gets populated with derived information during processing: + * - normalizedDeps derived from deps, created in instantiate + * - groupIndex used by group linking algorithm + * - evaluated indicating whether evaluation has happend + * - module the module record object, containing: + * - exports actual module exports + * + * For dynamic we track the es module with: + * - esModule actual es module value + * - esmExports whether to extend the esModule with named exports + * + * Then for declarative only we track dynamic bindings with the 'module' records: + * - name + * - exports + * - setters declarative setter functions + * - dependencies, module records of dependencies + * - importers, module records of dependents + * + * After linked and evaluated, entries are removed, declarative module records remain in separate + * module binding table + * + */ + +var leadingCommentAndMetaRegEx = /^\s*(\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\s*\/\/[^\n]*|\s*"[^"]+"\s*;?|\s*'[^']+'\s*;?)*\s*/; +function detectRegisterFormat(source) { + var leadingCommentAndMeta = source.match(leadingCommentAndMetaRegEx); + return leadingCommentAndMeta && source.substr(leadingCommentAndMeta[0].length, 15) == 'System.register'; +} + +function createEntry() { + return { + name: null, + deps: null, + originalIndices: null, + declare: null, + execute: null, + executingRequire: false, + declarative: false, + normalizedDeps: null, + groupIndex: null, + evaluated: false, + module: null, + esModule: null, + esmExports: false + }; +} + +(function() { + + /* + * There are two variations of System.register: + * 1. System.register for ES6 conversion (2-3 params) - System.register([name, ]deps, declare) + * see https://github.com/ModuleLoader/es6-module-loader/wiki/System.register-Explained + * + * 2. System.registerDynamic for dynamic modules (3-4 params) - System.registerDynamic([name, ]deps, executingRequire, execute) + * the true or false statement + * + * this extension implements the linking algorithm for the two variations identical to the spec + * allowing compiled ES6 circular references to work alongside AMD and CJS circular references. + * + */ + SystemJSLoader.prototype.register = function(name, deps, declare) { + if (typeof name != 'string') { + declare = deps; + deps = name; + name = null; + } + + // dynamic backwards-compatibility + // can be deprecated eventually + if (typeof declare == 'boolean') + return this.registerDynamic.apply(this, arguments); + + var entry = createEntry(); + // ideally wouldn't apply map config to bundle names but + // dependencies go through map regardless so we can't restrict + // could reconsider in shift to new spec + entry.name = name && (this.decanonicalize || this.normalize).call(this, name); + entry.declarative = true; + entry.deps = deps; + entry.declare = declare; + + this.pushRegister_({ + amd: false, + entry: entry + }); + }; + SystemJSLoader.prototype.registerDynamic = function(name, deps, declare, execute) { + if (typeof name != 'string') { + execute = declare; + declare = deps; + deps = name; + name = null; + } + + // dynamic + var entry = createEntry(); + entry.name = name && (this.decanonicalize || this.normalize).call(this, name); + entry.deps = deps; + entry.execute = execute; + entry.executingRequire = declare; + + this.pushRegister_({ + amd: false, + entry: entry + }); + }; + hook('reduceRegister_', function() { + return function(load, register) { + if (!register) + return; + + var entry = register.entry; + var curMeta = load && load.metadata; + + // named register + if (entry.name) { + if (!(entry.name in this.defined)) + this.defined[entry.name] = entry; + + if (curMeta) + curMeta.bundle = true; + } + // anonymous register + if (!entry.name || load && entry.name == load.name) { + if (!curMeta) + throw new TypeError('Unexpected anonymous System.register call.'); + if (curMeta.entry) { + if (curMeta.format == 'register') + throw new Error('Multiple anonymous System.register calls in module ' + load.name + '. If loading a bundle, ensure all the System.register calls are named.'); + else + throw new Error('Module ' + load.name + ' interpreted as ' + curMeta.format + ' module format, but called System.register.'); + } + if (!curMeta.format) + curMeta.format = 'register'; + curMeta.entry = entry; + } + }; + }); + + hookConstructor(function(constructor) { + return function() { + constructor.call(this); + + this.defined = {}; + this._loader.moduleRecords = {}; + }; + }); + + function buildGroups(entry, loader, groups) { + groups[entry.groupIndex] = groups[entry.groupIndex] || []; + + if (indexOf.call(groups[entry.groupIndex], entry) != -1) + return; + + groups[entry.groupIndex].push(entry); + + for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { + var depName = entry.normalizedDeps[i]; + var depEntry = loader.defined[depName]; + + // not in the registry means already linked / ES6 + if (!depEntry || depEntry.evaluated) + continue; + + // now we know the entry is in our unlinked linkage group + var depGroupIndex = entry.groupIndex + (depEntry.declarative != entry.declarative); + + // the group index of an entry is always the maximum + if (depEntry.groupIndex === null || depEntry.groupIndex < depGroupIndex) { + + // if already in a group, remove from the old group + if (depEntry.groupIndex !== null) { + groups[depEntry.groupIndex].splice(indexOf.call(groups[depEntry.groupIndex], depEntry), 1); + + // if the old group is empty, then we have a mixed depndency cycle + if (groups[depEntry.groupIndex].length == 0) + throw new Error("Mixed dependency cycle detected"); + } + + depEntry.groupIndex = depGroupIndex; + } + + buildGroups(depEntry, loader, groups); + } + } + + function link(name, loader) { + var startEntry = loader.defined[name]; + + // skip if already linked + if (startEntry.module) + return; + + startEntry.groupIndex = 0; + + var groups = []; + + buildGroups(startEntry, loader, groups); + + var curGroupDeclarative = !!startEntry.declarative == groups.length % 2; + for (var i = groups.length - 1; i >= 0; i--) { + var group = groups[i]; + for (var j = 0; j < group.length; j++) { + var entry = group[j]; + + // link each group + if (curGroupDeclarative) + linkDeclarativeModule(entry, loader); + else + linkDynamicModule(entry, loader); + } + curGroupDeclarative = !curGroupDeclarative; + } + } + + // module binding records + function Module() {} + defineProperty(Module, 'toString', { + value: function() { + return 'Module'; + } + }); + + function getOrCreateModuleRecord(name, moduleRecords) { + return moduleRecords[name] || (moduleRecords[name] = { + name: name, + dependencies: [], + exports: new Module(), // start from an empty module and extend + importers: [] + }); + } + + function linkDeclarativeModule(entry, loader) { + // only link if already not already started linking (stops at circular) + if (entry.module) + return; + + var moduleRecords = loader._loader.moduleRecords; + var module = entry.module = getOrCreateModuleRecord(entry.name, moduleRecords); + var exports = entry.module.exports; + + var declaration = entry.declare.call(__global, function(name, value) { + module.locked = true; + + if (typeof name == 'object') { + for (var p in name) + exports[p] = name[p]; + } + else { + exports[name] = value; + } + + for (var i = 0, l = module.importers.length; i < l; i++) { + var importerModule = module.importers[i]; + if (!importerModule.locked) { + var importerIndex = indexOf.call(importerModule.dependencies, module); + importerModule.setters[importerIndex](exports); + } + } + + module.locked = false; + return value; + }, entry.name); + + module.setters = declaration.setters; + module.execute = declaration.execute; + + if (!module.setters || !module.execute) { + throw new TypeError('Invalid System.register form for ' + entry.name); + } + + // now link all the module dependencies + for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { + var depName = entry.normalizedDeps[i]; + var depEntry = loader.defined[depName]; + var depModule = moduleRecords[depName]; + + // work out how to set depExports based on scenarios... + var depExports; + + if (depModule) { + depExports = depModule.exports; + } + // dynamic, already linked in our registry + else if (depEntry && !depEntry.declarative) { + depExports = depEntry.esModule; + } + // in the loader registry + else if (!depEntry) { + depExports = loader.get(depName); + } + // we have an entry -> link + else { + linkDeclarativeModule(depEntry, loader); + depModule = depEntry.module; + depExports = depModule.exports; + } + + // only declarative modules have dynamic bindings + if (depModule && depModule.importers) { + depModule.importers.push(module); + module.dependencies.push(depModule); + } + else { + module.dependencies.push(null); + } + + // run setters for all entries with the matching dependency name + var originalIndices = entry.originalIndices[i]; + for (var j = 0, len = originalIndices.length; j < len; ++j) { + var index = originalIndices[j]; + if (module.setters[index]) { + module.setters[index](depExports); + } + } + } + } + + // An analog to loader.get covering execution of all three layers (real declarative, simulated declarative, simulated dynamic) + function getModule(name, loader) { + var exports; + var entry = loader.defined[name]; + + if (!entry) { + exports = loader.get(name); + if (!exports) + throw new Error('Unable to load dependency ' + name + '.'); + } + + else { + if (entry.declarative) + ensureEvaluated(name, [], loader); + + else if (!entry.evaluated) + linkDynamicModule(entry, loader); + + exports = entry.module.exports; + } + + if ((!entry || entry.declarative) && exports && exports.__useDefault) + return exports['default']; + + return exports; + } + + function linkDynamicModule(entry, loader) { + if (entry.module) + return; + + var exports = {}; + + var module = entry.module = { exports: exports, id: entry.name }; + + // AMD requires execute the tree first + if (!entry.executingRequire) { + for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { + var depName = entry.normalizedDeps[i]; + // we know we only need to link dynamic due to linking algorithm + var depEntry = loader.defined[depName]; + if (depEntry) + linkDynamicModule(depEntry, loader); + } + } + + // now execute + entry.evaluated = true; + var output = entry.execute.call(__global, function(name) { + for (var i = 0, l = entry.deps.length; i < l; i++) { + if (entry.deps[i] != name) + continue; + return getModule(entry.normalizedDeps[i], loader); + } + throw new Error('Module ' + name + ' not declared as a dependency.'); + }, exports, module); + + if (output) + module.exports = output; + + // create the esModule object, which allows ES6 named imports of dynamics + exports = module.exports; + + // __esModule flag treats as already-named + if (exports && exports.__esModule) + entry.esModule = exports; + // set module as 'default' export, then fake named exports by iterating properties + else if (entry.esmExports && exports !== __global) + entry.esModule = getESModule(exports); + // just use the 'default' export + else + entry.esModule = { 'default': exports }; + } + + /* + * Given a module, and the list of modules for this current branch, + * ensure that each of the dependencies of this module is evaluated + * (unless one is a circular dependency already in the list of seen + * modules, in which case we execute it) + * + * Then we evaluate the module itself depth-first left to right + * execution to match ES6 modules + */ + function ensureEvaluated(moduleName, seen, loader) { + var entry = loader.defined[moduleName]; + + // if already seen, that means it's an already-evaluated non circular dependency + if (!entry || entry.evaluated || !entry.declarative) + return; + + // this only applies to declarative modules which late-execute + + seen.push(moduleName); + + for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { + var depName = entry.normalizedDeps[i]; + if (indexOf.call(seen, depName) == -1) { + if (!loader.defined[depName]) + loader.get(depName); + else + ensureEvaluated(depName, seen, loader); + } + } + + if (entry.evaluated) + return; + + entry.evaluated = true; + entry.module.execute.call(__global); + } + + // override the delete method to also clear the register caches + hook('delete', function(del) { + return function(name) { + delete this._loader.moduleRecords[name]; + delete this.defined[name]; + return del.call(this, name); + }; + }); + + hook('fetch', function(fetch) { + return function(load) { + if (this.defined[load.name]) { + load.metadata.format = 'defined'; + return ''; + } + + if (load.metadata.format == 'register' && !load.metadata.authorization && load.metadata.scriptLoad !== false) + load.metadata.scriptLoad = true; + + load.metadata.deps = load.metadata.deps || []; + + return fetch.call(this, load); + }; + }); + + hook('translate', function(translate) { + // we run the meta detection here (register is after meta) + return function(load) { + load.metadata.deps = load.metadata.deps || []; + return Promise.resolve(translate.call(this, load)).then(function(source) { + // run detection for register format + if (load.metadata.format == 'register' || !load.metadata.format && detectRegisterFormat(load.source)) + load.metadata.format = 'register'; + return source; + }); + }; + }); + + hook('instantiate', function(instantiate) { + return function(load) { + if (load.metadata.format == 'detect') + load.metadata.format = undefined; + + // assumes previous instantiate is sync + // (core json support) + instantiate.call(this, load); + + var loader = this; + + var entry; + + // first we check if this module has already been defined in the registry + if (loader.defined[load.name]) { + entry = loader.defined[load.name]; + // don't support deps for ES modules + if (!entry.declarative) + entry.deps = entry.deps.concat(load.metadata.deps); + } + + // picked up already by an anonymous System.register script injection + // or via the dynamic formats + else if (load.metadata.entry) { + entry = load.metadata.entry; + entry.deps = entry.deps.concat(load.metadata.deps); + } + + // Contains System.register calls + // (dont run bundles in the builder) + else if (!(loader.builder && load.metadata.bundle) + && (load.metadata.format == 'register' || load.metadata.format == 'esm' || load.metadata.format == 'es6')) { + + if (typeof __exec != 'undefined') + __exec.call(loader, load); + + if (!load.metadata.entry && !load.metadata.bundle) + throw new Error(load.name + ' detected as ' + load.metadata.format + ' but didn\'t execute.'); + + entry = load.metadata.entry; + + // support metadata deps for System.register + if (entry && load.metadata.deps) + entry.deps = entry.deps.concat(load.metadata.deps); + } + + // named bundles are just an empty module + if (!entry) { + entry = createEntry(); + entry.deps = load.metadata.deps; + entry.execute = function() {}; + } + + // place this module onto defined for circular references + loader.defined[load.name] = entry; + + var grouped = group(entry.deps); + + entry.deps = grouped.names; + entry.originalIndices = grouped.indices; + entry.name = load.name; + entry.esmExports = load.metadata.esmExports !== false; + + // first, normalize all dependencies + var normalizePromises = []; + for (var i = 0, l = entry.deps.length; i < l; i++) + normalizePromises.push(Promise.resolve(loader.normalize(entry.deps[i], load.name))); + + return Promise.all(normalizePromises).then(function(normalizedDeps) { + + entry.normalizedDeps = normalizedDeps; + + return { + deps: entry.deps, + execute: function() { + // recursively ensure that the module and all its + // dependencies are linked (with dependency group handling) + link(load.name, loader); + + // now handle dependency execution in correct order + ensureEvaluated(load.name, [], loader); + + // remove from the registry + loader.defined[load.name] = undefined; + + // return the defined module object + return loader.newModule(entry.declarative ? entry.module.exports : entry.esModule); + } + }; + }); + }; + }); +})(); +hook('reduceRegister_', function(reduceRegister) { + return function(load, register) { + if (register || !load.metadata.exports) + return reduceRegister.call(this, load, register); + + load.metadata.format = 'global'; + var entry = load.metadata.entry = createEntry(); + entry.deps = load.metadata.deps; + var globalValue = readMemberExpression(load.metadata.exports, __global); + entry.execute = function() { + return globalValue; + }; + }; +}); + +hookConstructor(function(constructor) { + return function() { + var loader = this; + constructor.call(loader); + + var hasOwnProperty = Object.prototype.hasOwnProperty; + + // bare minimum ignores for IE8 + var ignoredGlobalProps = ['_g', 'sessionStorage', 'localStorage', 'clipboardData', 'frames', 'frameElement', 'external', + 'mozAnimationStartTime', 'webkitStorageInfo', 'webkitIndexedDB', 'mozInnerScreenY', 'mozInnerScreenX']; + + var globalSnapshot; + + function forEachGlobal(callback) { + if (Object.keys) + Object.keys(__global).forEach(callback); + else + for (var g in __global) { + if (!hasOwnProperty.call(__global, g)) + continue; + callback(g); + } + } + + function forEachGlobalValue(callback) { + forEachGlobal(function(globalName) { + if (indexOf.call(ignoredGlobalProps, globalName) != -1) + return; + try { + var value = __global[globalName]; + } + catch (e) { + ignoredGlobalProps.push(globalName); + } + callback(globalName, value); + }); + } + + loader.set('@@global-helpers', loader.newModule({ + prepareGlobal: function(moduleName, exportName, globals) { + // disable module detection + var curDefine = __global.define; + + __global.define = undefined; + __global.exports = undefined; + if (__global.module && __global.module.exports) + __global.module = undefined; + + // set globals + var oldGlobals; + if (globals) { + oldGlobals = {}; + for (var g in globals) { + oldGlobals[g] = __global[g]; + __global[g] = globals[g]; + } + } + + // store a complete copy of the global object in order to detect changes + if (!exportName) { + globalSnapshot = {}; + + forEachGlobalValue(function(name, value) { + globalSnapshot[name] = value; + }); + } + + // return function to retrieve global + return function() { + var globalValue; + + if (exportName) { + globalValue = readMemberExpression(exportName, __global); + } + else { + var singleGlobal; + var multipleExports; + var exports = {}; + + forEachGlobalValue(function(name, value) { + if (globalSnapshot[name] === value) + return; + if (typeof value == 'undefined') + return; + exports[name] = value; + + if (typeof singleGlobal != 'undefined') { + if (!multipleExports && singleGlobal !== value) + multipleExports = true; + } + else { + singleGlobal = value; + } + }); + globalValue = multipleExports ? exports : singleGlobal; + } + + // revert globals + if (oldGlobals) { + for (var g in oldGlobals) + __global[g] = oldGlobals[g]; + } + __global.define = curDefine; + + return globalValue; + }; + } + })); + }; +}); +hookConstructor(function(constructor) { + return function() { + var loader = this; + constructor.call(loader); + + if (typeof window != 'undefined' && typeof document != 'undefined' && window.location) + var windowOrigin = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : ''); + + loader.set('@@cjs-helpers', loader.newModule({ + getPathVars: function(moduleId) { + // remove any plugin syntax + var pluginIndex = moduleId.lastIndexOf('!'); + var filename; + if (pluginIndex != -1) + filename = moduleId.substr(0, pluginIndex); + else + filename = moduleId; + + var dirname = filename.split('/'); + dirname.pop(); + dirname = dirname.join('/'); + + if (filename.substr(0, 8) == 'file:///') { + filename = filename.substr(7); + dirname = dirname.substr(7); + + // on windows remove leading '/' + if (isWindows) { + filename = filename.substr(1); + dirname = dirname.substr(1); + } + } + else if (windowOrigin && filename.substr(0, windowOrigin.length) === windowOrigin) { + filename = filename.substr(windowOrigin.length); + dirname = dirname.substr(windowOrigin.length); + } + + return { + filename: filename, + dirname: dirname + }; + } + })) + }; +});/* + * AMD Helper function module + * Separated into its own file as this is the part needed for full AMD support in SFX builds + * NB since implementations have now diverged this can be merged back with amd.js + */ +hookConstructor(function(constructor) { + return function() { + var loader = this; + constructor.call(this); + + var commentRegEx = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg; + var cjsRequirePre = "(?:^|[^$_a-zA-Z\\xA0-\\uFFFF.])"; + var cjsRequirePost = "\\s*\\(\\s*(\"([^\"]+)\"|'([^']+)')\\s*\\)"; + var fnBracketRegEx = /\(([^\)]*)\)/; + var wsRegEx = /^\s+|\s+$/g; + + var requireRegExs = {}; + + function getCJSDeps(source, requireIndex) { + + // remove comments + source = source.replace(commentRegEx, ''); + + // determine the require alias + var params = source.match(fnBracketRegEx); + var requireAlias = (params[1].split(',')[requireIndex] || 'require').replace(wsRegEx, ''); + + // find or generate the regex for this requireAlias + var requireRegEx = requireRegExs[requireAlias] || (requireRegExs[requireAlias] = new RegExp(cjsRequirePre + requireAlias + cjsRequirePost, 'g')); + + requireRegEx.lastIndex = 0; + + var deps = []; + + var match; + while (match = requireRegEx.exec(source)) + deps.push(match[2] || match[3]); + + return deps; + } + + /* + AMD-compatible require + To copy RequireJS, set window.require = window.requirejs = loader.amdRequire + */ + function require(names, callback, errback, referer) { + // in amd, first arg can be a config object... we just ignore + if (typeof names == 'object' && !(names instanceof Array)) + return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1)); + + // amd require + if (typeof names == 'string' && typeof callback == 'function') + names = [names]; + if (names instanceof Array) { + var dynamicRequires = []; + for (var i = 0; i < names.length; i++) + dynamicRequires.push(loader['import'](names[i], referer)); + Promise.all(dynamicRequires).then(function(modules) { + if (callback) + callback.apply(null, modules); + }, errback); + } + + // commonjs require + else if (typeof names == 'string') { + var module = loader.get(loader.decanonicalize(names, referer)); + if (!module) + throw new Error('Module not already loaded loading "' + names + '" from "' + referer + '".'); + return module.__useDefault ? module['default'] : module; + } + + else + throw new TypeError('Invalid require'); + } + + function define(name, deps, factory) { + if (typeof name != 'string') { + factory = deps; + deps = name; + name = null; + } + if (!(deps instanceof Array)) { + factory = deps; + deps = ['require', 'exports', 'module'].splice(0, factory.length); + } + + if (typeof factory != 'function') + factory = (function(factory) { + return function() { return factory; } + })(factory); + + // in IE8, a trailing comma becomes a trailing undefined entry + if (deps[deps.length - 1] === undefined) + deps.pop(); + + // remove system dependencies + var requireIndex, exportsIndex, moduleIndex; + + if ((requireIndex = indexOf.call(deps, 'require')) != -1) { + + deps.splice(requireIndex, 1); + + // only trace cjs requires for non-named + // named defines assume the trace has already been done + if (!name) + deps = deps.concat(getCJSDeps(factory.toString(), requireIndex)); + } + + if ((exportsIndex = indexOf.call(deps, 'exports')) != -1) + deps.splice(exportsIndex, 1); + + if ((moduleIndex = indexOf.call(deps, 'module')) != -1) + deps.splice(moduleIndex, 1); + + function execute(req, exports, module) { + var depValues = []; + for (var i = 0; i < deps.length; i++) + depValues.push(req(deps[i])); + + module.uri = module.id; + + module.config = function() {}; + + // add back in system dependencies + if (moduleIndex != -1) + depValues.splice(moduleIndex, 0, module); + + if (exportsIndex != -1) + depValues.splice(exportsIndex, 0, exports); + + if (requireIndex != -1) { + function contextualRequire(names, callback, errback) { + if (typeof names == 'string' && typeof callback != 'function') + return req(names); + return require.call(loader, names, callback, errback, module.id); + } + contextualRequire.toUrl = function(name) { + // normalize without defaultJSExtensions + var defaultJSExtension = loader.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js'; + var url = loader.decanonicalize(name, module.id); + if (defaultJSExtension && url.substr(url.length - 3, 3) == '.js') + url = url.substr(0, url.length - 3); + return url; + }; + depValues.splice(requireIndex, 0, contextualRequire); + } + + // set global require to AMD require + var curRequire = __global.require; + __global.require = require; + + var output = factory.apply(exportsIndex == -1 ? __global : exports, depValues); + + __global.require = curRequire; + + if (typeof output == 'undefined' && module) + output = module.exports; + + if (typeof output != 'undefined') + return output; + } + + var entry = createEntry(); + entry.name = name && (loader.decanonicalize || loader.normalize).call(loader, name); + entry.deps = deps; + entry.execute = execute; + + loader.pushRegister_({ + amd: true, + entry: entry + }); + } + define.amd = {}; + + // reduction function to attach defines to a load record + hook('reduceRegister_', function(reduceRegister) { + return function(load, register) { + // only handle AMD registers here + if (!register || !register.amd) + return reduceRegister.call(this, load, register); + + var curMeta = load && load.metadata; + var entry = register.entry; + + if (curMeta) + curMeta.format = 'amd'; + + // anonymous define + if (!entry.name) { + if (!curMeta) + throw new TypeError('Unexpected anonymous AMD define.'); + + // already defined anonymously -> throw + if (curMeta.entry) + throw new TypeError('Multiple defines for anonymous module ' + load.name); + + curMeta.entry = entry; + } + // named define + else { + // if we don't have any other defines, + // then let this be an anonymous define + // this is just to support single modules of the form: + // define('jquery') + // still loading anonymously + // because it is done widely enough to be useful + // as soon as there is more than one define, this gets removed though + if (curMeta) { + if (!curMeta.entry && !curMeta.bundle) + curMeta.entry = entry; + else + curMeta.entry = undefined; + + // note this is now a bundle + curMeta.bundle = true; + } + + // define the module through the register registry + if (!(entry.name in this.defined)) + this.defined[entry.name] = entry; + } + }; + }); + + // adds define as a global (potentially just temporarily) + function createDefine() { + // ensure no NodeJS environment detection + var oldModule = __global.module; + var oldExports = __global.exports; + var oldDefine = __global.define; + + __global.module = undefined; + __global.exports = undefined; + __global.define = define; + + return function() { + __global.define = oldDefine; + __global.module = oldModule; + __global.exports = oldExports; + }; + } + + loader.set('@@amd-helpers', loader.newModule({ + createDefine: createDefine, + require: require, + define: define + })); + loader.amdDefine = define; + loader.amdRequire = require; + }; +});/* + SystemJS Loader Plugin Support + + Supports plugin loader syntax with "!", or via metadata.loader + + The plugin name is loaded as a module itself, and can override standard loader hooks + for the plugin resource. See the plugin section of the systemjs readme. +*/ + +(function() { + function getParentName(loader, parentName) { + // if parent is a plugin, normalize against the parent plugin argument only + if (parentName) { + var parentPluginIndex; + if (loader.pluginFirst) { + if ((parentPluginIndex = parentName.lastIndexOf('!')) != -1) + return parentName.substr(parentPluginIndex + 1); + } + else { + if ((parentPluginIndex = parentName.indexOf('!')) != -1) + return parentName.substr(0, parentPluginIndex); + } + + return parentName; + } + } + + function parsePlugin(loader, name) { + var argumentName; + var pluginName; + + var pluginIndex = name.lastIndexOf('!'); + + if (pluginIndex == -1) + return; + + if (loader.pluginFirst) { + argumentName = name.substr(pluginIndex + 1); + pluginName = name.substr(0, pluginIndex); + } + else { + argumentName = name.substr(0, pluginIndex); + pluginName = name.substr(pluginIndex + 1) || argumentName.substr(argumentName.lastIndexOf('.') + 1); + } + + return { + argument: argumentName, + plugin: pluginName + }; + } + + // put name back together after parts have been normalized + function combinePluginParts(loader, argumentName, pluginName, defaultExtension) { + if (defaultExtension && argumentName.substr(argumentName.length - 3, 3) == '.js') + argumentName = argumentName.substr(0, argumentName.length - 3); + + if (loader.pluginFirst) { + return pluginName + '!' + argumentName; + } + else { + return argumentName + '!' + pluginName; + } + } + + // note if normalize will add a default js extension + // if so, remove for backwards compat + // this is strange and sucks, but will be deprecated + function checkDefaultExtension(loader, arg) { + return loader.defaultJSExtensions && arg.substr(arg.length - 3, 3) != '.js'; + } + + function createNormalizeSync(normalizeSync) { + return function(name, parentName, isPlugin) { + var loader = this; + + parentName = getParentName(this, parentName); + var parsed = parsePlugin(loader, name); + + if (!parsed) + return normalizeSync.call(this, name, parentName, isPlugin); + + // if this is a plugin, normalize the plugin name and the argument + var argumentName = loader.normalizeSync(parsed.argument, parentName, true); + var pluginName = loader.normalizeSync(parsed.plugin, parentName, true); + return combinePluginParts(loader, argumentName, pluginName, checkDefaultExtension(loader, parsed.argument)); + }; + } + + hook('decanonicalize', createNormalizeSync); + hook('normalizeSync', createNormalizeSync); + + hook('normalize', function(normalize) { + return function(name, parentName, isPlugin) { + var loader = this; + + parentName = getParentName(this, parentName); + + var parsed = parsePlugin(loader, name); + + if (!parsed) + return normalize.call(loader, name, parentName, isPlugin); + + return Promise.all([ + loader.normalize(parsed.argument, parentName, true), + loader.normalize(parsed.plugin, parentName, true) + ]) + .then(function(normalized) { + return combinePluginParts(loader, normalized[0], normalized[1], checkDefaultExtension(loader, parsed.argument)); + }); + } + }); + + hook('locate', function(locate) { + return function(load) { + var loader = this; + + var name = load.name; + + // plugin syntax + var pluginSyntaxIndex; + if (loader.pluginFirst) { + if ((pluginSyntaxIndex = name.indexOf('!')) != -1) { + load.metadata.loader = name.substr(0, pluginSyntaxIndex); + load.name = name.substr(pluginSyntaxIndex + 1); + } + } + else { + if ((pluginSyntaxIndex = name.lastIndexOf('!')) != -1) { + load.metadata.loader = name.substr(pluginSyntaxIndex + 1); + load.name = name.substr(0, pluginSyntaxIndex); + } + } + + return locate.call(loader, load) + .then(function(address) { + var plugin = load.metadata.loader; + + if (!plugin) + return address; + + // only fetch the plugin itself if this name isn't defined + if (loader.defined && loader.defined[name]) + return address; + + var pluginLoader = loader.pluginLoader || loader; + + // load the plugin module and run standard locate + return pluginLoader['import'](plugin) + .then(function(loaderModule) { + // store the plugin module itself on the metadata + load.metadata.loaderModule = loaderModule; + + load.address = address; + if (loaderModule.locate) + return loaderModule.locate.call(loader, load); + + return address; + }); + }); + }; + }); + + hook('fetch', function(fetch) { + return function(load) { + var loader = this; + if (load.metadata.loaderModule && load.metadata.loaderModule.fetch && load.metadata.format != 'defined') { + load.metadata.scriptLoad = false; + return load.metadata.loaderModule.fetch.call(loader, load, function(load) { + return fetch.call(loader, load); + }); + } + else { + return fetch.call(loader, load); + } + }; + }); + + hook('translate', function(translate) { + return function(load) { + + /* + * Source map sanitization for load.metadata.sourceMap + * Used to set browser and build-level source maps for + * translated sources in a general way. + * + * This isn't plugin-specific, but can't go anywhere else for now + * As it is post-translate + */ + var sourceMap = load.metadata.sourceMap; + + // if an object not a JSON string do sanitizing + if (sourceMap && typeof sourceMap == 'object') { + var originalName = load.name.split('!')[0]; + + // force set the filename of the original file + sourceMap.file = originalName + '!transpiled'; + + // force set the sources list if only one source + if (!sourceMap.sources || sourceMap.sources.length == 1) + sourceMap.sources = [originalName]; + load.metadata.sourceMap = JSON.stringify(sourceMap); + } + + var loader = this; + if (load.metadata.loaderModule && load.metadata.loaderModule.translate && load.metadata.format != 'defined') { + return Promise.resolve(load.metadata.loaderModule.translate.call(loader, load)).then(function(result) { + // NB we should probably enforce a string output + if (typeof result == 'string') + load.source = result; + return translate.call(loader, load); + }); + } + else { + return translate.call(loader, load); + } + }; + }); + + hook('instantiate', function(instantiate) { + return function(load) { + var loader = this; + + if (load.metadata.loaderModule && load.metadata.loaderModule.instantiate && !loader.builder && load.metadata.format != 'defined') + return Promise.resolve(load.metadata.loaderModule.instantiate.call(loader, load)).then(function(result) { + load.metadata.entry = createEntry(); + load.metadata.entry.execute = function() { + return result; + } + load.metadata.entry.deps = load.metadata.deps; + load.metadata.format = 'defined'; + return instantiate.call(loader, load); + }); + else + return instantiate.call(loader, load); + }; + }); + +})();/* + * Conditions Extension + * + * Allows a condition module to alter the resolution of an import via syntax: + * + * import $ from 'jquery/#{browser}'; + * + * Will first load the module 'browser' via `SystemJS.import('browser')` and + * take the default export of that module. + * If the default export is not a string, an error is thrown. + * + * We then substitute the string into the require to get the conditional resolution + * enabling environment-specific variations like: + * + * import $ from 'jquery/ie' + * import $ from 'jquery/firefox' + * import $ from 'jquery/chrome' + * import $ from 'jquery/safari' + * + * It can be useful for a condition module to define multiple conditions. + * This can be done via the `|` modifier to specify an export member expression: + * + * import 'jquery/#{./browser.js|grade.version}' + * + * Where the `grade` export `version` member in the `browser.js` module is substituted. + * + * + * Boolean Conditionals + * + * For polyfill modules, that are used as imports but have no module value, + * a binary conditional allows a module not to be loaded at all if not needed: + * + * import 'es5-shim#?./conditions.js|needs-es5shim' + * + * These conditions can also be negated via: + * + * import 'es5-shim#?~./conditions.js|es6' + * + */ + + function parseCondition(condition) { + var conditionExport, conditionModule, negation; + + var negation = condition[0] == '~'; + var conditionExportIndex = condition.lastIndexOf('|'); + if (conditionExportIndex != -1) { + conditionExport = condition.substr(conditionExportIndex + 1); + conditionModule = condition.substr(negation, conditionExportIndex - negation) || '@system-env'; + } + else { + conditionExport = null; + conditionModule = condition.substr(negation); + } + + return { + module: conditionModule, + prop: conditionExport, + negate: negation + }; + } + + function serializeCondition(conditionObj) { + return (conditionObj.negate ? '~' : '') + conditionObj.module + (conditionObj.prop ? '|' + conditionObj.prop : ''); + } + + function resolveCondition(conditionObj, parentName, bool) { + return this['import'](conditionObj.module, parentName) + .then(function(m) { + if (conditionObj.prop) + m = readMemberExpression(conditionObj.prop, m); + else if (typeof m == 'object' && m + '' == 'Module') + m = m['default']; + + return conditionObj.negate ? !m : m; + }); + } + + var interpolationRegEx = /#\{[^\}]+\}/; + function interpolateConditional(name, parentName) { + // first we normalize the conditional + var conditionalMatch = name.match(interpolationRegEx); + + if (!conditionalMatch) + return Promise.resolve(name); + + var conditionObj = parseCondition(conditionalMatch[0].substr(2, conditionalMatch[0].length - 3)); + + // in builds, return normalized conditional + if (this.builder) + return this['normalize'](conditionObj.module, parentName) + .then(function(conditionModule) { + conditionObj.module = conditionModule; + return name.replace(interpolationRegEx, '#{' + serializeCondition(conditionObj) + '}'); + }); + + return resolveCondition.call(this, conditionObj, parentName, false) + .then(function(conditionValue) { + if (typeof conditionValue !== 'string') + throw new TypeError('The condition value for ' + name + ' doesn\'t resolve to a string.'); + + if (conditionValue.indexOf('/') != -1) + throw new TypeError('Unabled to interpolate conditional ' + name + (parentName ? ' in ' + parentName : '') + '\n\tThe condition value ' + conditionValue + ' cannot contain a "/" separator.'); + + return name.replace(interpolationRegEx, conditionValue); + }); + } + + function booleanConditional(name, parentName) { + // first we normalize the conditional + var booleanIndex = name.lastIndexOf('#?'); + + if (booleanIndex == -1) + return Promise.resolve(name); + + var conditionObj = parseCondition(name.substr(booleanIndex + 2)); + + // in builds, return normalized conditional + if (this.builder) + return this['normalize'](conditionObj.module, parentName) + .then(function(conditionModule) { + conditionObj.module = conditionModule; + return name.substr(0, booleanIndex) + '#?' + serializeCondition(conditionObj); + }); + + return resolveCondition.call(this, conditionObj, parentName, true) + .then(function(conditionValue) { + return conditionValue ? name.substr(0, booleanIndex) : '@empty'; + }); + } + + // normalizeSync does not parse conditionals at all although it could + hook('normalize', function(normalize) { + return function(name, parentName, parentAddress) { + var loader = this; + return booleanConditional.call(loader, name, parentName) + .then(function(name) { + return normalize.call(loader, name, parentName, parentAddress); + }) + .then(function(normalized) { + return interpolateConditional.call(loader, normalized, parentName); + }); + }; + }); +/* + * Alias Extension + * + * Allows a module to be a plain copy of another module by module name + * + * SystemJS.meta['mybootstrapalias'] = { alias: 'bootstrap' }; + * + */ +(function() { + // aliases + hook('fetch', function(fetch) { + return function(load) { + var alias = load.metadata.alias; + var aliasDeps = load.metadata.deps || []; + if (alias) { + load.metadata.format = 'defined'; + var entry = createEntry(); + this.defined[load.name] = entry; + entry.declarative = true; + entry.deps = aliasDeps.concat([alias]); + entry.declare = function(_export) { + return { + setters: [function(module) { + for (var p in module) + _export(p, module[p]); + if (module.__useDefault) + entry.module.exports.__useDefault = true; + }], + execute: function() {} + }; + }; + return ''; + } + + return fetch.call(this, load); + }; + }); +})();/* + * Meta Extension + * + * Sets default metadata on a load record (load.metadata) from + * loader.metadata via SystemJS.meta function. + * + * + * Also provides an inline meta syntax for module meta in source. + * + * Eg: + * + * loader.meta({ + * 'my/module': { deps: ['jquery'] } + * 'my/*': { format: 'amd' } + * }); + * + * Which in turn populates loader.metadata. + * + * load.metadata.deps and load.metadata.format will then be set + * for 'my/module' + * + * The same meta could be set with a my/module.js file containing: + * + * my/module.js + * "format amd"; + * "deps[] jquery"; + * "globals.some value" + * console.log('this is my/module'); + * + * Configuration meta always takes preference to inline meta. + * + * Multiple matches in wildcards are supported and ammend the meta. + * + * + * The benefits of the function form is that paths are URL-normalized + * supporting say + * + * loader.meta({ './app': { format: 'cjs' } }); + * + * Instead of needing to set against the absolute URL (https://site.com/app.js) + * + */ + +(function() { + + hookConstructor(function(constructor) { + return function() { + this.meta = {}; + constructor.call(this); + }; + }); + + hook('locate', function(locate) { + return function(load) { + var meta = this.meta; + var name = load.name; + + // NB for perf, maybe introduce a fast-path wildcard lookup cache here + // which is checked first + + // apply wildcard metas + var bestDepth = 0; + var wildcardIndex; + for (var module in meta) { + wildcardIndex = module.indexOf('*'); + if (wildcardIndex === -1) + continue; + if (module.substr(0, wildcardIndex) === name.substr(0, wildcardIndex) + && module.substr(wildcardIndex + 1) === name.substr(name.length - module.length + wildcardIndex + 1)) { + var depth = module.split('/').length; + if (depth > bestDepth) + bestDepth = depth; + extendMeta(load.metadata, meta[module], bestDepth != depth); + } + } + + // apply exact meta + if (meta[name]) + extendMeta(load.metadata, meta[name]); + + return locate.call(this, load); + }; + }); + + // detect any meta header syntax + // only set if not already set + var metaRegEx = /^(\s*\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\s*\/\/[^\n]*|\s*"[^"]+"\s*;?|\s*'[^']+'\s*;?)+/; + var metaPartRegEx = /\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\/\/[^\n]*|"[^"]+"\s*;?|'[^']+'\s*;?/g; + + function setMetaProperty(target, p, value) { + var pParts = p.split('.'); + var curPart; + while (pParts.length > 1) { + curPart = pParts.shift(); + target = target[curPart] = target[curPart] || {}; + } + curPart = pParts.shift(); + if (!(curPart in target)) + target[curPart] = value; + } + + hook('translate', function(translate) { + return function(load) { + // NB meta will be post-translate pending transpiler conversion to plugins + var meta = load.source.match(metaRegEx); + if (meta) { + var metaParts = meta[0].match(metaPartRegEx); + + for (var i = 0; i < metaParts.length; i++) { + var curPart = metaParts[i]; + var len = curPart.length; + + var firstChar = curPart.substr(0, 1); + if (curPart.substr(len - 1, 1) == ';') + len--; + + if (firstChar != '"' && firstChar != "'") + continue; + + var metaString = curPart.substr(1, curPart.length - 3); + var metaName = metaString.substr(0, metaString.indexOf(' ')); + + if (metaName) { + var metaValue = metaString.substr(metaName.length + 1, metaString.length - metaName.length - 1); + + if (metaName.substr(metaName.length - 2, 2) == '[]') { + metaName = metaName.substr(0, metaName.length - 2); + load.metadata[metaName] = load.metadata[metaName] || []; + load.metadata[metaName].push(metaValue); + } + else if (load.metadata[metaName] instanceof Array) { + // temporary backwards compat for previous "deps" syntax + warn.call(this, 'Module ' + load.name + ' contains deprecated "deps ' + metaValue + '" meta syntax.\nThis should be updated to "deps[] ' + metaValue + '" for pushing to array meta.'); + load.metadata[metaName].push(metaValue); + } + else { + setMetaProperty(load.metadata, metaName, metaValue); + } + } + else { + load.metadata[metaString] = true; + } + } + } + + return translate.call(this, load); + }; + }); +})(); +/* + System bundles + + Allows a bundle module to be specified which will be dynamically + loaded before trying to load a given module. + + For example: + SystemJS.bundles['mybundle'] = ['jquery', 'bootstrap/js/bootstrap'] + + Will result in a load to "mybundle" whenever a load to "jquery" + or "bootstrap/js/bootstrap" is made. + + In this way, the bundle becomes the request that provides the module +*/ + +(function() { + // bundles support (just like RequireJS) + // bundle name is module name of bundle itself + // bundle is array of modules defined by the bundle + // when a module in the bundle is requested, the bundle is loaded instead + // of the form SystemJS.bundles['mybundle'] = ['jquery', 'bootstrap/js/bootstrap'] + hookConstructor(function(constructor) { + return function() { + constructor.call(this); + this.bundles = {}; + this._loader.loadedBundles = {}; + }; + }); + + // assign bundle metadata for bundle loads + hook('locate', function(locate) { + return function(load) { + var loader = this; + var matched = false; + + if (!(load.name in loader.defined)) + for (var b in loader.bundles) { + for (var i = 0; i < loader.bundles[b].length; i++) { + var curModule = loader.bundles[b][i]; + + if (curModule == load.name) { + matched = true; + break; + } + + // wildcard in bundles does not include / boundaries + if (curModule.indexOf('*') != -1) { + var parts = curModule.split('*'); + if (parts.length != 2) { + loader.bundles[b].splice(i--, 1); + continue; + } + + if (load.name.substring(0, parts[0].length) == parts[0] && + load.name.substr(load.name.length - parts[1].length, parts[1].length) == parts[1] && + load.name.substr(parts[0].length, load.name.length - parts[1].length - parts[0].length).indexOf('/') == -1) { + matched = true; + break; + } + } + } + + if (matched) + return loader['import'](b) + .then(function() { + return locate.call(loader, load); + }); + } + + return locate.call(loader, load); + }; + }); +})(); +/* + * Dependency Tree Cache + * + * Allows a build to pre-populate a dependency trace tree on the loader of + * the expected dependency tree, to be loaded upfront when requesting the + * module, avoinding the n round trips latency of module loading, where + * n is the dependency tree depth. + * + * eg: + * SystemJS.depCache = { + * 'app': ['normalized', 'deps'], + * 'normalized': ['another'], + * 'deps': ['tree'] + * }; + * + * SystemJS.import('app') + * // simultaneously starts loading all of: + * // 'normalized', 'deps', 'another', 'tree' + * // before "app" source is even loaded + * + */ + +(function() { + hookConstructor(function(constructor) { + return function() { + constructor.call(this); + this.depCache = {}; + } + }); + + hook('locate', function(locate) { + return function(load) { + var loader = this; + // load direct deps, in turn will pick up their trace trees + var deps = loader.depCache[load.name]; + if (deps) + for (var i = 0; i < deps.length; i++) + loader['import'](deps[i], load.name); + + return locate.call(loader, load); + }; + }); +})(); + +/* + * Script-only addition used for production loader + * + */ +hookConstructor(function(constructor) { + return function() { + constructor.apply(this, arguments); + + // prepare amd define + if (this.has('@@amd-helpers')) + this.get('@@amd-helpers').createDefine(); + }; +}); + +hook('fetch', function(fetch) { + return function(load) { + load.metadata.scriptLoad = true; + return fetch.call(this, load); + }; +});System = new SystemJSLoader(); + +__global.SystemJS = System; +System.version = '0.19.17 CSP'; + // -- exporting -- + + if (typeof exports === 'object') + module.exports = Loader; + + __global.Reflect = __global.Reflect || {}; + __global.Reflect.Loader = __global.Reflect.Loader || Loader; + __global.Reflect.global = __global.Reflect.global || __global; + __global.LoaderPolyfill = Loader; + + if (!System) { + System = new SystemLoader(); + System.constructor = SystemLoader; + } + + if (typeof exports === 'object') + module.exports = System; + + __global.System = System; + +})(typeof self != 'undefined' ? self : global);} + +// auto-load Promise and URL polyfills if needed in the browser +try { + var hasURL = typeof URLPolyfill != 'undefined' || new URL('test:///').protocol == 'test:'; +} +catch(e) {} + +if (typeof Promise === 'undefined' || !hasURL) { + // document.write + if (typeof document !== 'undefined') { + var scripts = document.getElementsByTagName('script'); + $__curScript = scripts[scripts.length - 1]; + var curPath = $__curScript.src; + var basePath = curPath.substr(0, curPath.lastIndexOf('/') + 1); + window.systemJSBootstrap = bootstrap; + document.write( + '<' + 'script type="text/javascript" src="' + basePath + 'system-polyfills.js">' + '<' + '/script>' + ); + } + // importScripts + else if (typeof importScripts !== 'undefined') { + var basePath = ''; + try { + throw new Error('_'); + } catch (e) { + e.stack.replace(/(?:at|@).*(http.+):[\d]+:[\d]+/, function(m, url) { + basePath = url.replace(/\/[^\/]*$/, '/'); + }); + } + importScripts(basePath + 'system-polyfills.js'); + bootstrap(); + } + else { + bootstrap(); + } +} +else { + bootstrap(); +} + + +})(); +\ No newline at end of file diff --git a/extension/lib/vendor/system.src.js b/extension/lib/vendor/system.src.js @@ -1,4843 +0,0 @@ -/* - * SystemJS v0.19.13 - */ -(function() { -function bootstrap() {(function(__global) { - - var isWorker = typeof window == 'undefined' && typeof self != 'undefined' && typeof importScripts != 'undefined'; - var isBrowser = typeof window != 'undefined' && typeof document != 'undefined'; - var isWindows = typeof process != 'undefined' && typeof process.platform != 'undefined' && !!process.platform.match(/^win/); - - if (!__global.console) - __global.console = { assert: function() {} }; - - // IE8 support - var indexOf = Array.prototype.indexOf || function(item) { - for (var i = 0, thisLen = this.length; i < thisLen; i++) { - if (this[i] === item) { - return i; - } - } - return -1; - }; - - var defineProperty; - (function () { - try { - if (!!Object.defineProperty({}, 'a', {})) - defineProperty = Object.defineProperty; - } - catch (e) { - defineProperty = function(obj, prop, opt) { - try { - obj[prop] = opt.value || opt.get.call(obj); - } - catch(e) {} - } - } - })(); - - function addToError(err, msg) { - var newErr; - if (err instanceof Error) { - newErr = new Error(err.message, err.fileName, err.lineNumber); - if (isBrowser) { - newErr.message = err.message + '\n\t' + msg; - newErr.stack = err.stack; - } - else { - // node errors only look correct with the stack modified - newErr.message = err.message; - newErr.stack = err.stack + '\n\t' + msg; - } - } - else { - newErr = err + '\n\t' + msg; - } - - return newErr; - } - - function __eval(source, debugName, context) { - try { - new Function(source).call(context); - } - catch(e) { - throw addToError(e, 'Evaluating ' + debugName); - } - } - - var baseURI; - // environent baseURI detection - if (typeof document != 'undefined' && document.getElementsByTagName) { - baseURI = document.baseURI; - - if (!baseURI) { - var bases = document.getElementsByTagName('base'); - baseURI = bases[0] && bases[0].href || window.location.href; - } - - // sanitize out the hash and querystring - baseURI = baseURI.split('#')[0].split('?')[0]; - baseURI = baseURI.substr(0, baseURI.lastIndexOf('/') + 1); - } - else if (typeof process != 'undefined' && process.cwd) { - baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd() + '/'; - if (isWindows) - baseURI = baseURI.replace(/\\/g, '/'); - } - else if (typeof location != 'undefined') { - baseURI = __global.location.href; - } - else { - throw new TypeError('No environment baseURI'); - } - - var URL = __global.URLPolyfill || __global.URL; -/* -********************************************************************************************* - - Dynamic Module Loader Polyfill - - - Implemented exactly to the former 2014-08-24 ES6 Specification Draft Rev 27, Section 15 - http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts#august_24_2014_draft_rev_27 - - - Functions are commented with their spec numbers, with spec differences commented. - - - Spec bugs are commented in this code with links. - - - Abstract functions have been combined where possible, and their associated functions - commented. - - - Realm implementation is entirely omitted. - -********************************************************************************************* -*/ - -function Module() {} -// http://www.ecma-international.org/ecma-262/6.0/#sec-@@tostringtag -defineProperty(Module.prototype, 'toString', { - value: function() { - return 'Module'; - } -}); -function Loader(options) { - this._loader = { - loaderObj: this, - loads: [], - modules: {}, - importPromises: {}, - moduleRecords: {} - }; - - // 26.3.3.6 - defineProperty(this, 'global', { - get: function() { - return __global; - } - }); - - // 26.3.3.13 realm not implemented -} - -(function() { - -// Some Helpers - -// logs a linkset snapshot for debugging -/* function snapshot(loader) { - console.log('---Snapshot---'); - for (var i = 0; i < loader.loads.length; i++) { - var load = loader.loads[i]; - var linkSetLog = ' ' + load.name + ' (' + load.status + '): '; - - for (var j = 0; j < load.linkSets.length; j++) { - linkSetLog += '{' + logloads(load.linkSets[j].loads) + '} '; - } - console.log(linkSetLog); - } - console.log(''); -} -function logloads(loads) { - var log = ''; - for (var k = 0; k < loads.length; k++) - log += loads[k].name + (k != loads.length - 1 ? ' ' : ''); - return log; -} */ - - -/* function checkInvariants() { - // see https://bugs.ecmascript.org/show_bug.cgi?id=2603#c1 - - var loads = System._loader.loads; - var linkSets = []; - - for (var i = 0; i < loads.length; i++) { - var load = loads[i]; - console.assert(load.status == 'loading' || load.status == 'loaded', 'Each load is loading or loaded'); - - for (var j = 0; j < load.linkSets.length; j++) { - var linkSet = load.linkSets[j]; - - for (var k = 0; k < linkSet.loads.length; k++) - console.assert(loads.indexOf(linkSet.loads[k]) != -1, 'linkSet loads are a subset of loader loads'); - - if (linkSets.indexOf(linkSet) == -1) - linkSets.push(linkSet); - } - } - - for (var i = 0; i < loads.length; i++) { - var load = loads[i]; - for (var j = 0; j < linkSets.length; j++) { - var linkSet = linkSets[j]; - - if (linkSet.loads.indexOf(load) != -1) - console.assert(load.linkSets.indexOf(linkSet) != -1, 'linkSet contains load -> load contains linkSet'); - - if (load.linkSets.indexOf(linkSet) != -1) - console.assert(linkSet.loads.indexOf(load) != -1, 'load contains linkSet -> linkSet contains load'); - } - } - - for (var i = 0; i < linkSets.length; i++) { - var linkSet = linkSets[i]; - for (var j = 0; j < linkSet.loads.length; j++) { - var load = linkSet.loads[j]; - - for (var k = 0; k < load.dependencies.length; k++) { - var depName = load.dependencies[k].value; - var depLoad; - for (var l = 0; l < loads.length; l++) { - if (loads[l].name != depName) - continue; - depLoad = loads[l]; - break; - } - - // loading records are allowed not to have their dependencies yet - // if (load.status != 'loading') - // console.assert(depLoad, 'depLoad found'); - - // console.assert(linkSet.loads.indexOf(depLoad) != -1, 'linkset contains all dependencies'); - } - } - } -} */ - - // 15.2.3 - Runtime Semantics: Loader State - - // 15.2.3.11 - function createLoaderLoad(object) { - return { - // modules is an object for ES5 implementation - modules: {}, - loads: [], - loaderObj: object - }; - } - - // 15.2.3.2 Load Records and LoadRequest Objects - - // 15.2.3.2.1 - function createLoad(name) { - return { - status: 'loading', - name: name, - linkSets: [], - dependencies: [], - metadata: {} - }; - } - - // 15.2.3.2.2 createLoadRequestObject, absorbed into calling functions - - // 15.2.4 - - // 15.2.4.1 - function loadModule(loader, name, options) { - return new Promise(asyncStartLoadPartwayThrough({ - step: options.address ? 'fetch' : 'locate', - loader: loader, - moduleName: name, - // allow metadata for import https://bugs.ecmascript.org/show_bug.cgi?id=3091 - moduleMetadata: options && options.metadata || {}, - moduleSource: options.source, - moduleAddress: options.address - })); - } - - // 15.2.4.2 - function requestLoad(loader, request, refererName, refererAddress) { - // 15.2.4.2.1 CallNormalize - return new Promise(function(resolve, reject) { - resolve(loader.loaderObj.normalize(request, refererName, refererAddress)); - }) - // 15.2.4.2.2 GetOrCreateLoad - .then(function(name) { - var load; - if (loader.modules[name]) { - load = createLoad(name); - load.status = 'linked'; - // https://bugs.ecmascript.org/show_bug.cgi?id=2795 - load.module = loader.modules[name]; - return load; - } - - for (var i = 0, l = loader.loads.length; i < l; i++) { - load = loader.loads[i]; - if (load.name != name) - continue; - console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded'); - return load; - } - - load = createLoad(name); - loader.loads.push(load); - - proceedToLocate(loader, load); - - return load; - }); - } - - // 15.2.4.3 - function proceedToLocate(loader, load) { - proceedToFetch(loader, load, - Promise.resolve() - // 15.2.4.3.1 CallLocate - .then(function() { - return loader.loaderObj.locate({ name: load.name, metadata: load.metadata }); - }) - ); - } - - // 15.2.4.4 - function proceedToFetch(loader, load, p) { - proceedToTranslate(loader, load, - p - // 15.2.4.4.1 CallFetch - .then(function(address) { - // adjusted, see https://bugs.ecmascript.org/show_bug.cgi?id=2602 - if (load.status != 'loading') - return; - load.address = address; - - return loader.loaderObj.fetch({ name: load.name, metadata: load.metadata, address: address }); - }) - ); - } - - var anonCnt = 0; - - // 15.2.4.5 - function proceedToTranslate(loader, load, p) { - p - // 15.2.4.5.1 CallTranslate - .then(function(source) { - if (load.status != 'loading') - return; - - return Promise.resolve(loader.loaderObj.translate({ name: load.name, metadata: load.metadata, address: load.address, source: source })) - - // 15.2.4.5.2 CallInstantiate - .then(function(source) { - load.source = source; - return loader.loaderObj.instantiate({ name: load.name, metadata: load.metadata, address: load.address, source: source }); - }) - - // 15.2.4.5.3 InstantiateSucceeded - .then(function(instantiateResult) { - if (instantiateResult === undefined) { - load.address = load.address || '<Anonymous Module ' + ++anonCnt + '>'; - - // instead of load.kind, use load.isDeclarative - load.isDeclarative = true; - return transpile.call(loader.loaderObj, load) - .then(function(transpiled) { - // Hijack System.register to set declare function - var curSystem = __global.System; - var curRegister = curSystem.register; - curSystem.register = function(name, deps, declare) { - if (typeof name != 'string') { - declare = deps; - deps = name; - } - // store the registered declaration as load.declare - // store the deps as load.deps - load.declare = declare; - load.depsList = deps; - } - // empty {} context is closest to undefined 'this' we can get - __eval(transpiled, load.address, {}); - curSystem.register = curRegister; - }); - } - else if (typeof instantiateResult == 'object') { - load.depsList = instantiateResult.deps || []; - load.execute = instantiateResult.execute; - load.isDeclarative = false; - } - else - throw TypeError('Invalid instantiate return value'); - }) - // 15.2.4.6 ProcessLoadDependencies - .then(function() { - load.dependencies = []; - var depsList = load.depsList; - - var loadPromises = []; - for (var i = 0, l = depsList.length; i < l; i++) (function(request, index) { - loadPromises.push( - requestLoad(loader, request, load.name, load.address) - - // 15.2.4.6.1 AddDependencyLoad (load is parentLoad) - .then(function(depLoad) { - - // adjusted from spec to maintain dependency order - // this is due to the System.register internal implementation needs - load.dependencies[index] = { - key: request, - value: depLoad.name - }; - - if (depLoad.status != 'linked') { - var linkSets = load.linkSets.concat([]); - for (var i = 0, l = linkSets.length; i < l; i++) - addLoadToLinkSet(linkSets[i], depLoad); - } - - // console.log('AddDependencyLoad ' + depLoad.name + ' for ' + load.name); - // snapshot(loader); - }) - ); - })(depsList[i], i); - - return Promise.all(loadPromises); - }) - - // 15.2.4.6.2 LoadSucceeded - .then(function() { - // console.log('LoadSucceeded ' + load.name); - // snapshot(loader); - - console.assert(load.status == 'loading', 'is loading'); - - load.status = 'loaded'; - - var linkSets = load.linkSets.concat([]); - for (var i = 0, l = linkSets.length; i < l; i++) - updateLinkSetOnLoad(linkSets[i], load); - }); - }) - // 15.2.4.5.4 LoadFailed - ['catch'](function(exc) { - load.status = 'failed'; - load.exception = exc; - - var linkSets = load.linkSets.concat([]); - for (var i = 0, l = linkSets.length; i < l; i++) { - linkSetFailed(linkSets[i], load, exc); - } - - console.assert(load.linkSets.length == 0, 'linkSets not removed'); - }); - } - - // 15.2.4.7 PromiseOfStartLoadPartwayThrough absorbed into calling functions - - // 15.2.4.7.1 - function asyncStartLoadPartwayThrough(stepState) { - return function(resolve, reject) { - var loader = stepState.loader; - var name = stepState.moduleName; - var step = stepState.step; - - if (loader.modules[name]) - throw new TypeError('"' + name + '" already exists in the module table'); - - // adjusted to pick up existing loads - var existingLoad; - for (var i = 0, l = loader.loads.length; i < l; i++) { - if (loader.loads[i].name == name) { - existingLoad = loader.loads[i]; - - if (step == 'translate' && !existingLoad.source) { - existingLoad.address = stepState.moduleAddress; - proceedToTranslate(loader, existingLoad, Promise.resolve(stepState.moduleSource)); - } - - // a primary load -> use that existing linkset if it is for the direct load here - // otherwise create a new linkset unit - if (existingLoad.linkSets.length && existingLoad.linkSets[0].loads[0].name == existingLoad.name) - return existingLoad.linkSets[0].done.then(function() { - resolve(existingLoad); - }); - } - } - - var load = existingLoad || createLoad(name); - - load.metadata = stepState.moduleMetadata; - - var linkSet = createLinkSet(loader, load); - - loader.loads.push(load); - - resolve(linkSet.done); - - if (step == 'locate') - proceedToLocate(loader, load); - - else if (step == 'fetch') - proceedToFetch(loader, load, Promise.resolve(stepState.moduleAddress)); - - else { - console.assert(step == 'translate', 'translate step'); - load.address = stepState.moduleAddress; - proceedToTranslate(loader, load, Promise.resolve(stepState.moduleSource)); - } - } - } - - // Declarative linking functions run through alternative implementation: - // 15.2.5.1.1 CreateModuleLinkageRecord not implemented - // 15.2.5.1.2 LookupExport not implemented - // 15.2.5.1.3 LookupModuleDependency not implemented - - // 15.2.5.2.1 - function createLinkSet(loader, startingLoad) { - var linkSet = { - loader: loader, - loads: [], - startingLoad: startingLoad, // added see spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995 - loadingCount: 0 - }; - linkSet.done = new Promise(function(resolve, reject) { - linkSet.resolve = resolve; - linkSet.reject = reject; - }); - addLoadToLinkSet(linkSet, startingLoad); - return linkSet; - } - // 15.2.5.2.2 - function addLoadToLinkSet(linkSet, load) { - if (load.status == 'failed') - return; - - console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded on link set'); - - for (var i = 0, l = linkSet.loads.length; i < l; i++) - if (linkSet.loads[i] == load) - return; - - linkSet.loads.push(load); - load.linkSets.push(linkSet); - - // adjustment, see https://bugs.ecmascript.org/show_bug.cgi?id=2603 - if (load.status != 'loaded') { - linkSet.loadingCount++; - } - - var loader = linkSet.loader; - - for (var i = 0, l = load.dependencies.length; i < l; i++) { - if (!load.dependencies[i]) - continue; - - var name = load.dependencies[i].value; - - if (loader.modules[name]) - continue; - - for (var j = 0, d = loader.loads.length; j < d; j++) { - if (loader.loads[j].name != name) - continue; - - addLoadToLinkSet(linkSet, loader.loads[j]); - break; - } - } - // console.log('add to linkset ' + load.name); - // snapshot(linkSet.loader); - } - - // linking errors can be generic or load-specific - // this is necessary for debugging info - function doLink(linkSet) { - var error = false; - try { - link(linkSet, function(load, exc) { - linkSetFailed(linkSet, load, exc); - error = true; - }); - } - catch(e) { - linkSetFailed(linkSet, null, e); - error = true; - } - return error; - } - - // 15.2.5.2.3 - function updateLinkSetOnLoad(linkSet, load) { - // console.log('update linkset on load ' + load.name); - // snapshot(linkSet.loader); - - console.assert(load.status == 'loaded' || load.status == 'linked', 'loaded or linked'); - - linkSet.loadingCount--; - - if (linkSet.loadingCount > 0) - return; - - // adjusted for spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995 - var startingLoad = linkSet.startingLoad; - - // non-executing link variation for loader tracing - // on the server. Not in spec. - /***/ - if (linkSet.loader.loaderObj.execute === false) { - var loads = [].concat(linkSet.loads); - for (var i = 0, l = loads.length; i < l; i++) { - var load = loads[i]; - load.module = !load.isDeclarative ? { - module: _newModule({}) - } : { - name: load.name, - module: _newModule({}), - evaluated: true - }; - load.status = 'linked'; - finishLoad(linkSet.loader, load); - } - return linkSet.resolve(startingLoad); - } - /***/ - - var abrupt = doLink(linkSet); - - if (abrupt) - return; - - console.assert(linkSet.loads.length == 0, 'loads cleared'); - - linkSet.resolve(startingLoad); - } - - // 15.2.5.2.4 - function linkSetFailed(linkSet, load, exc) { - var loader = linkSet.loader; - var requests; - - checkError: - if (load) { - if (linkSet.loads[0].name == load.name) { - exc = addToError(exc, 'Error loading ' + load.name); - } - else { - for (var i = 0; i < linkSet.loads.length; i++) { - var pLoad = linkSet.loads[i]; - for (var j = 0; j < pLoad.dependencies.length; j++) { - var dep = pLoad.dependencies[j]; - if (dep.value == load.name) { - exc = addToError(exc, 'Error loading ' + load.name + ' as "' + dep.key + '" from ' + pLoad.name); - break checkError; - } - } - } - exc = addToError(exc, 'Error loading ' + load.name + ' from ' + linkSet.loads[0].name); - } - } - else { - exc = addToError(exc, 'Error linking ' + linkSet.loads[0].name); - } - - - var loads = linkSet.loads.concat([]); - for (var i = 0, l = loads.length; i < l; i++) { - var load = loads[i]; - - // store all failed load records - loader.loaderObj.failed = loader.loaderObj.failed || []; - if (indexOf.call(loader.loaderObj.failed, load) == -1) - loader.loaderObj.failed.push(load); - - var linkIndex = indexOf.call(load.linkSets, linkSet); - console.assert(linkIndex != -1, 'link not present'); - load.linkSets.splice(linkIndex, 1); - if (load.linkSets.length == 0) { - var globalLoadsIndex = indexOf.call(linkSet.loader.loads, load); - if (globalLoadsIndex != -1) - linkSet.loader.loads.splice(globalLoadsIndex, 1); - } - } - linkSet.reject(exc); - } - - // 15.2.5.2.5 - function finishLoad(loader, load) { - // add to global trace if tracing - if (loader.loaderObj.trace) { - if (!loader.loaderObj.loads) - loader.loaderObj.loads = {}; - var depMap = {}; - load.dependencies.forEach(function(dep) { - depMap[dep.key] = dep.value; - }); - loader.loaderObj.loads[load.name] = { - name: load.name, - deps: load.dependencies.map(function(dep){ return dep.key }), - depMap: depMap, - address: load.address, - metadata: load.metadata, - source: load.source, - kind: load.isDeclarative ? 'declarative' : 'dynamic' - }; - } - // if not anonymous, add to the module table - if (load.name) { - console.assert(!loader.modules[load.name], 'load not in module table'); - loader.modules[load.name] = load.module; - } - var loadIndex = indexOf.call(loader.loads, load); - if (loadIndex != -1) - loader.loads.splice(loadIndex, 1); - for (var i = 0, l = load.linkSets.length; i < l; i++) { - loadIndex = indexOf.call(load.linkSets[i].loads, load); - if (loadIndex != -1) - load.linkSets[i].loads.splice(loadIndex, 1); - } - load.linkSets.splice(0, load.linkSets.length); - } - - function doDynamicExecute(linkSet, load, linkError) { - try { - var module = load.execute(); - } - catch(e) { - linkError(load, e); - return; - } - if (!module || !(module instanceof Module)) - linkError(load, new TypeError('Execution must define a Module instance')); - else - return module; - } - - // 26.3 Loader - - // 26.3.1.1 - // defined at top - - // importPromises adds ability to import a module twice without error - https://bugs.ecmascript.org/show_bug.cgi?id=2601 - function createImportPromise(loader, name, promise) { - var importPromises = loader._loader.importPromises; - return importPromises[name] = promise.then(function(m) { - importPromises[name] = undefined; - return m; - }, function(e) { - importPromises[name] = undefined; - throw e; - }); - } - - Loader.prototype = { - // 26.3.3.1 - constructor: Loader, - // 26.3.3.2 - define: function(name, source, options) { - // check if already defined - if (this._loader.importPromises[name]) - throw new TypeError('Module is already loading.'); - return createImportPromise(this, name, new Promise(asyncStartLoadPartwayThrough({ - step: 'translate', - loader: this._loader, - moduleName: name, - moduleMetadata: options && options.metadata || {}, - moduleSource: source, - moduleAddress: options && options.address - }))); - }, - // 26.3.3.3 - 'delete': function(name) { - var loader = this._loader; - delete loader.importPromises[name]; - delete loader.moduleRecords[name]; - return loader.modules[name] ? delete loader.modules[name] : false; - }, - // 26.3.3.4 entries not implemented - // 26.3.3.5 - get: function(key) { - if (!this._loader.modules[key]) - return; - doEnsureEvaluated(this._loader.modules[key], [], this); - return this._loader.modules[key].module; - }, - // 26.3.3.7 - has: function(name) { - return !!this._loader.modules[name]; - }, - // 26.3.3.8 - 'import': function(name, parentName, parentAddress) { - if (typeof parentName == 'object') - parentName = parentName.name; - - // run normalize first - var loaderObj = this; - - // added, see https://bugs.ecmascript.org/show_bug.cgi?id=2659 - return Promise.resolve(loaderObj.normalize(name, parentName)) - .then(function(name) { - var loader = loaderObj._loader; - - if (loader.modules[name]) { - doEnsureEvaluated(loader.modules[name], [], loader._loader); - return loader.modules[name].module; - } - - return loader.importPromises[name] || createImportPromise(loaderObj, name, - loadModule(loader, name, {}) - .then(function(load) { - delete loader.importPromises[name]; - return evaluateLoadedModule(loader, load); - })); - }); - }, - // 26.3.3.9 keys not implemented - // 26.3.3.10 - load: function(name) { - var loader = this._loader; - if (loader.modules[name]) - return Promise.resolve(); - return loader.importPromises[name] || createImportPromise(this, name, new Promise(asyncStartLoadPartwayThrough({ - step: 'locate', - loader: loader, - moduleName: name, - moduleMetadata: {}, - moduleSource: undefined, - moduleAddress: undefined - })) - .then(function() { - delete loader.importPromises[name]; - })); - }, - // 26.3.3.11 - module: function(source, options) { - var load = createLoad(); - load.address = options && options.address; - var linkSet = createLinkSet(this._loader, load); - var sourcePromise = Promise.resolve(source); - var loader = this._loader; - var p = linkSet.done.then(function() { - return evaluateLoadedModule(loader, load); - }); - proceedToTranslate(loader, load, sourcePromise); - return p; - }, - // 26.3.3.12 - newModule: function (obj) { - if (typeof obj != 'object') - throw new TypeError('Expected object'); - - var m = new Module(); - - var pNames = []; - if (Object.getOwnPropertyNames && obj != null) - pNames = Object.getOwnPropertyNames(obj); - else - for (var key in obj) - pNames.push(key); - - for (var i = 0; i < pNames.length; i++) (function(key) { - defineProperty(m, key, { - configurable: false, - enumerable: true, - get: function () { - return obj[key]; - } - }); - })(pNames[i]); - - return m; - }, - // 26.3.3.14 - set: function(name, module) { - if (!(module instanceof Module)) - throw new TypeError('Loader.set(' + name + ', module) must be a module'); - this._loader.modules[name] = { - module: module - }; - }, - // 26.3.3.15 values not implemented - // 26.3.3.16 @@iterator not implemented - // 26.3.3.17 @@toStringTag not implemented - - // 26.3.3.18.1 - normalize: function(name, referrerName, referrerAddress) { - return name; - }, - // 26.3.3.18.2 - locate: function(load) { - return load.name; - }, - // 26.3.3.18.3 - fetch: function(load) { - }, - // 26.3.3.18.4 - translate: function(load) { - return load.source; - }, - // 26.3.3.18.5 - instantiate: function(load) { - } - }; - - var _newModule = Loader.prototype.newModule; -/* - * ES6 Module Declarative Linking Code - Dev Build Only - */ - function link(linkSet, linkError) { - - var loader = linkSet.loader; - - if (!linkSet.loads.length) - return; - - var loads = linkSet.loads.concat([]); - - for (var i = 0; i < loads.length; i++) { - var load = loads[i]; - - var module = doDynamicExecute(linkSet, load, linkError); - if (!module) - return; - load.module = { - name: load.name, - module: module - }; - load.status = 'linked'; - - finishLoad(loader, load); - } - } - - function evaluateLoadedModule(loader, load) { - console.assert(load.status == 'linked', 'is linked ' + load.name); - return load.module.module; - } - - function doEnsureEvaluated() {} - - function transpile() { - throw new TypeError('ES6 transpilation is only provided in the dev module loader build.'); - } -})();/* -********************************************************************************************* - - System Loader Implementation - - - Implemented to https://github.com/jorendorff/js-loaders/blob/master/browser-loader.js - - - <script type="module"> supported - -********************************************************************************************* -*/ - -var System; - -function SystemLoader() { - Loader.call(this); - this.paths = {}; -} - -// NB no specification provided for System.paths, used ideas discussed in https://github.com/jorendorff/js-loaders/issues/25 -function applyPaths(paths, name) { - // most specific (most number of slashes in path) match wins - var pathMatch = '', wildcard, maxWildcardPrefixLen = 0; - - // check to see if we have a paths entry - for (var p in paths) { - var pathParts = p.split('*'); - if (pathParts.length > 2) - throw new TypeError('Only one wildcard in a path is permitted'); - - // exact path match - if (pathParts.length == 1) { - if (name == p) { - pathMatch = p; - break; - } - } - // wildcard path match - else { - var wildcardPrefixLen = pathParts[0].length; - if (wildcardPrefixLen >= maxWildcardPrefixLen && - name.substr(0, pathParts[0].length) == pathParts[0] && - name.substr(name.length - pathParts[1].length) == pathParts[1]) { - maxWildcardPrefixLen = wildcardPrefixLen; - pathMatch = p; - wildcard = name.substr(pathParts[0].length, name.length - pathParts[1].length - pathParts[0].length); - } - } - } - - var outPath = paths[pathMatch]; - if (typeof wildcard == 'string') - outPath = outPath.replace('*', wildcard); - - return outPath; -} - -// inline Object.create-style class extension -function LoaderProto() {} -LoaderProto.prototype = Loader.prototype; -SystemLoader.prototype = new LoaderProto(); - var fetchTextFromURL; - if (typeof XMLHttpRequest != 'undefined') { - fetchTextFromURL = function(url, authorization, fulfill, reject) { - var xhr = new XMLHttpRequest(); - var sameDomain = true; - var doTimeout = false; - if (!('withCredentials' in xhr)) { - // check if same domain - var domainCheck = /^(\w+:)?\/\/([^\/]+)/.exec(url); - if (domainCheck) { - sameDomain = domainCheck[2] === window.location.host; - if (domainCheck[1]) - sameDomain &= domainCheck[1] === window.location.protocol; - } - } - if (!sameDomain && typeof XDomainRequest != 'undefined') { - xhr = new XDomainRequest(); - xhr.onload = load; - xhr.onerror = error; - xhr.ontimeout = error; - xhr.onprogress = function() {}; - xhr.timeout = 0; - doTimeout = true; - } - function load() { - fulfill(xhr.responseText); - } - function error() { - reject(new Error('XHR error' + (xhr.status ? ' (' + xhr.status + (xhr.statusText ? ' ' + xhr.statusText : '') + ')' : '') + ' loading ' + url)); - } - - xhr.onreadystatechange = function () { - if (xhr.readyState === 4) { - // in Chrome on file:/// URLs, status is 0 - if (xhr.status == 0) { - if (xhr.responseText) { - load(); - } - else { - // when responseText is empty, wait for load or error event - // to inform if it is a 404 or empty file - xhr.addEventListener('error', error); - xhr.addEventListener('load', load); - } - } - else if (xhr.status === 200) { - load(); - } - else { - error(); - } - } - }; - xhr.open("GET", url, true); - - if (xhr.setRequestHeader) { - xhr.setRequestHeader('Accept', 'application/x-es-module, */*'); - // can set "authorization: true" to enable withCredentials only - if (authorization) { - if (typeof authorization == 'string') - xhr.setRequestHeader('Authorization', authorization); - xhr.withCredentials = true; - } - } - - if (doTimeout) { - setTimeout(function() { - xhr.send(); - }, 0); - } else { - xhr.send(null); - } - }; - } - else if (typeof require != 'undefined' && typeof process != 'undefined') { - var fs; - fetchTextFromURL = function(url, authorization, fulfill, reject) { - if (url.substr(0, 8) != 'file:///') - throw new Error('Unable to fetch "' + url + '". Only file URLs of the form file:/// allowed running in Node.'); - fs = fs || require('fs'); - if (isWindows) - url = url.replace(/\//g, '\\').substr(8); - else - url = url.substr(7); - return fs.readFile(url, function(err, data) { - if (err) { - return reject(err); - } - else { - // Strip Byte Order Mark out if it's the leading char - var dataString = data + ''; - if (dataString[0] === '\ufeff') - dataString = dataString.substr(1); - - fulfill(dataString); - } - }); - }; - } - else if (typeof self != 'undefined' && typeof self.fetch != 'undefined') { - fetchTextFromURL = function(url, authorization, fulfill, reject) { - var opts = { - headers: {'Accept': 'application/x-es-module, */*'} - }; - - if (authorization) { - if (typeof authorization == 'string') - opts.headers['Authorization'] = authorization; - opts.credentials = 'include'; - } - - fetch(url, opts) - .then(function (r) { - if (r.ok) { - return r.text(); - } else { - throw new Error('Fetch error: ' + r.status + ' ' + r.statusText); - } - }) - .then(fulfill, reject); - } - } - else { - throw new TypeError('No environment fetch API available.'); - } - - SystemLoader.prototype.fetch = function(load) { - return new Promise(function(resolve, reject) { - fetchTextFromURL(load.address, undefined, resolve, reject); - }); - }; -/* - * Traceur, Babel and TypeScript transpile hook for Loader - */ -var transpile = (function() { - - // use Traceur by default - Loader.prototype.transpiler = 'traceur'; - - function transpile(load) { - var self = this; - - return Promise.resolve(__global[self.transpiler == 'typescript' ? 'ts' : self.transpiler] - || (self.pluginLoader || self)['import'](self.transpiler)) - .then(function(transpiler) { - if (transpiler.__useDefault) - transpiler = transpiler['default']; - - var transpileFunction; - if (transpiler.Compiler) - transpileFunction = traceurTranspile; - else if (transpiler.createLanguageService) - transpileFunction = typescriptTranspile; - else - transpileFunction = babelTranspile; - - // note __moduleName will be part of the transformer meta in future when we have the spec for this - return '(function(__moduleName){' + transpileFunction.call(self, load, transpiler) + '\n})("' + load.name + '");\n//# sourceURL=' + load.address + '!transpiled'; - }); - }; - - function traceurTranspile(load, traceur) { - var options = this.traceurOptions || {}; - options.modules = 'instantiate'; - options.script = false; - if (options.sourceMaps === undefined) - options.sourceMaps = 'inline'; - options.filename = load.address; - options.inputSourceMap = load.metadata.sourceMap; - options.moduleName = false; - - var compiler = new traceur.Compiler(options); - - return doTraceurCompile(load.source, compiler, options.filename); - } - function doTraceurCompile(source, compiler, filename) { - try { - return compiler.compile(source, filename); - } - catch(e) { - // on older versions of traceur (<0.9.3), an array of errors is thrown - // rather than a single error. - if (e.length) { - throw e[0]; - } - throw e; - } - } - - function babelTranspile(load, babel) { - var options = this.babelOptions || {}; - options.modules = 'system'; - if (options.sourceMap === undefined) - options.sourceMap = 'inline'; - options.inputSourceMap = load.metadata.sourceMap; - options.filename = load.address; - options.code = true; - options.ast = false; - - return babel.transform(load.source, options).code; - } - - function typescriptTranspile(load, ts) { - var options = this.typescriptOptions || {}; - options.target = options.target || ts.ScriptTarget.ES5; - if (options.sourceMap === undefined) - options.sourceMap = true; - if (options.sourceMap && options.inlineSourceMap !== false) - options.inlineSourceMap = true; - - options.module = ts.ModuleKind.System; - - return ts.transpile(load.source, options, load.address); - } - - return transpile; -})(); -// SystemJS Loader Class and Extension helpers - -function SystemJSLoader() { - SystemLoader.call(this); - - systemJSConstructor.call(this); -} - -// inline Object.create-style class extension -function SystemProto() {}; -SystemProto.prototype = SystemLoader.prototype; -SystemJSLoader.prototype = new SystemProto(); -SystemJSLoader.prototype.constructor = SystemJSLoader; - -// remove ESML instantiate -SystemJSLoader.prototype.instantiate = function() {}; - -var systemJSConstructor; - -function hook(name, hook) { - SystemJSLoader.prototype[name] = hook(SystemJSLoader.prototype[name] || function() {}); -} -function hookConstructor(hook) { - systemJSConstructor = hook(systemJSConstructor || function() {}); -} - -function dedupe(deps) { - var newDeps = []; - for (var i = 0, l = deps.length; i < l; i++) - if (indexOf.call(newDeps, deps[i]) == -1) - newDeps.push(deps[i]) - return newDeps; -} - -function group(deps) { - var names = []; - var indices = []; - for (var i = 0, l = deps.length; i < l; i++) { - var index = indexOf.call(names, deps[i]); - if (index === -1) { - names.push(deps[i]); - indices.push([i]); - } - else { - indices[index].push(i); - } - } - return { names: names, indices: indices }; -} - -var getOwnPropertyDescriptor = true; -try { - Object.getOwnPropertyDescriptor({ a: 0 }, 'a'); -} -catch(e) { - getOwnPropertyDescriptor = false; -} - -// converts any module.exports object into an object ready for SystemJS.newModule -function getESModule(exports) { - var esModule = {}; - // don't trigger getters/setters in environments that support them - if (typeof exports == 'object' || typeof exports == 'function') { - if (getOwnPropertyDescriptor) { - var d; - for (var p in exports) - if (d = Object.getOwnPropertyDescriptor(exports, p)) - defineProperty(esModule, p, d); - } - else { - var hasOwnProperty = exports && exports.hasOwnProperty; - for (var p in exports) { - if (!hasOwnProperty || exports.hasOwnProperty(p)) - esModule[p] = exports[p]; - } - } - } - esModule['default'] = exports; - defineProperty(esModule, '__useDefault', { - value: true - }); - return esModule; -} - -function extend(a, b, prepend) { - for (var p in b) { - if (!prepend || !(p in a)) - a[p] = b[p]; - } - return a; -} - -// package configuration options -var packageProperties = ['main', 'format', 'defaultExtension', 'meta', 'map', 'basePath', 'depCache']; - -// meta first-level extends where: -// array + array appends -// object + object extends -// other properties replace -function extendMeta(a, b, prepend) { - for (var p in b) { - var val = b[p]; - if (!(p in a)) - a[p] = val; - else if (val instanceof Array && a[p] instanceof Array) - a[p] = [].concat(prepend ? val : a[p]).concat(prepend ? a[p] : val); - else if (typeof val == 'object' && val !== null && typeof a[p] == 'object') - a[p] = extend(extend({}, a[p]), val, prepend); - else if (!prepend) - a[p] = val; - } -} - -function warn(msg) { - if (this.warnings && typeof console != 'undefined' && console.warn) - console.warn(msg); -}// we define a __exec for globally-scoped execution -// used by module format implementations -var __exec; - -(function() { - - // System clobbering protection (mostly for Traceur) - var curSystem; - var callCounter = 0; - var curLoad; - function preExec(loader, load) { - if (callCounter++ == 0) - curSystem = __global.System; - __global.System = loader; - curLoad = load; - } - function postExec() { - if (--callCounter == 0) - __global.System = curSystem; - curLoad = undefined; - } - - // System.register, System.registerDynamic, AMD define pipeline - // if currently evalling code here, immediately reduce the registered entry against the load record - hook('pushRegister_', function() { - return function(register) { - if (!curLoad) - return false; - - this.reduceRegister_(curLoad, register); - return true; - }; - }); - - var hasBtoa = typeof btoa != 'undefined'; - - // used to support leading #!/usr/bin/env in scripts as supported in Node - var hashBangRegEx = /^\#\!.*/; - - function getSource(load) { - var lastLineIndex = load.source.lastIndexOf('\n'); - - // wrap ES formats with a System closure for System global encapsulation - var wrap = load.metadata.format == 'esm' || load.metadata.format == 'register' || load.metadata.bundle; - - return (wrap ? '(function(System) {' : '') + (load.metadata.format == 'cjs' ? load.source.replace(hashBangRegEx, '') : load.source) + (wrap ? '\n})(System);' : '') - // adds the sourceURL comment if not already present - + (load.source.substr(lastLineIndex, 15) != '\n//# sourceURL=' - ? '\n//# sourceURL=' + load.address + (load.metadata.sourceMap ? '!transpiled' : '') : '') - // add sourceMappingURL if load.metadata.sourceMap is set - + (load.metadata.sourceMap && hasBtoa && - '\n//# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(load.metadata.sourceMap))) || '') - } - - function evalExec(load) { - if (load.metadata.integrity) - throw new TypeError('Subresource integrity checking is not supported in Web Workers or Chrome Extensions.'); - try { - preExec(this, load); - new Function(getSource(load)).call(__global); - postExec(); - } - catch(e) { - postExec(); - throw addToError(e, 'Evaluating ' + load.address); - } - } - - // use script injection eval to get identical global script behaviour - if (typeof document != 'undefined' && document.getElementsByTagName) { - var head; - - var scripts = document.getElementsByTagName('script'); - $__curScript = scripts[scripts.length - 1]; - __exec = function(load) { - if (!this.globalEvaluationScope) - return evalExec.call(this, load); - - if (!head) - head = document.head || document.body || document.documentElement; - - var script = document.createElement('script'); - script.text = getSource(load); - var onerror = window.onerror; - var e; - window.onerror = function(_e) { - e = addToError(_e, 'Evaluating ' + load.address); - } - preExec(this, load); - - if (load.metadata.integrity) - script.setAttribute('integrity', load.metadata.integrity); - if (load.metadata.nonce) - script.setAttribute('nonce', load.metadata.nonce); - - head.appendChild(script); - head.removeChild(script); - postExec(); - window.onerror = onerror; - if (e) - throw e; - }; - } - - // global scoped eval for node - else if (typeof require != 'undefined') { - var vmModule = 'vm'; - var vm = require(vmModule); - __exec = function vmExec(load) { - if (!this.globalEvaluationScope) - return evalExec.call(this, load); - - if (load.metadata.integrity) - throw new TypeError('Subresource integrity checking is unavailable in Node.'); - try { - preExec(this, load); - vm.runInThisContext(getSource(load)); - postExec(); - } - catch(e) { - postExec(); - throw addToError(e.toString(), 'Evaluating ' + load.address); - } - }; - } - else { - __exec = evalExec; - } - -})();var absURLRegEx = /^[^\/]+:\/\//; - -function readMemberExpression(p, value) { - var pParts = p.split('.'); - while (pParts.length) - value = value[pParts.shift()]; - return value; -} - -var baseURLCache = {}; -function getBaseURLObj() { - if (baseURLCache[this.baseURL]) - return baseURLCache[this.baseURL]; - - // normalize baseURL if not already - if (this.baseURL[this.baseURL.length - 1] != '/') - this.baseURL += '/'; - - var baseURL = new URL(this.baseURL, baseURI); - - this.baseURL = baseURL.href; - - return (baseURLCache[this.baseURL] = baseURL); -} - -function getMapMatch(map, name) { - var bestMatch, bestMatchLength = 0; - - for (var p in map) { - if (name.substr(0, p.length) == p && (name.length == p.length || name[p.length] == '/')) { - var curMatchLength = p.split('/').length; - if (curMatchLength <= bestMatchLength) - continue; - bestMatch = p; - bestMatchLength = curMatchLength; - } - } - - return bestMatch; -} - -function setConditional(mode) { - this.set('@system-env', this.newModule({ - browser: isBrowser, - node: !!this._nodeRequire, - env: mode, - production: mode == 'production', - development: mode == 'development' - })); -} - -var baseURIObj = new URL(baseURI); - -hookConstructor(function(constructor) { - return function() { - constructor.call(this); - - // support baseURL - this.baseURL = baseURI.substr(0, baseURI.lastIndexOf('/') + 1); - - // support map - this.map = {}; - - // global behaviour flags - this.warnings = false; - this.defaultJSExtensions = false; - this.globalEvaluationScope = true; - this.pluginFirst = false; - - // by default load ".json" files as json - // leading * meta doesn't need normalization - // NB add this in next breaking release - // this.meta['*.json'] = { format: 'json' }; - - // Default settings for globalEvaluationScope: - // Disabled for WebWorker, Chrome Extensions and jsdom - if (isWorker - || isBrowser && window.chrome && window.chrome.extension - || isBrowser && navigator.userAgent.match(/^Node\.js/)) - this.globalEvaluationScope = false; - - // support the empty module, as a concept - this.set('@empty', this.newModule({})); - - setConditional.call(this, 'development'); - }; -}); - -// include the node require since we're overriding it -if (typeof require != 'undefined' && typeof process != 'undefined' && !process.browser) - SystemJSLoader.prototype._nodeRequire = require; - -var nodeCoreModules = ['assert', 'buffer', 'child_process', 'cluster', 'console', 'constants', - 'crypto', 'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'https', 'module', 'net', 'os', 'path', - 'process', 'punycode', 'querystring', 'readline', 'repl', 'stream', 'string_decoder', 'sys', 'timers', - 'tls', 'tty', 'url', 'util', 'vm', 'zlib']; - -/* - Core SystemJS Normalization - - If a name is relative, we apply URL normalization to the page - If a name is an absolute URL, we leave it as-is - - Plain names (neither of the above) run through the map and paths - normalization phases. - - The paths normalization phase applies last (paths extension), which - defines the `decanonicalize` function and normalizes everything into - a URL. - */ -hook('normalize', function(normalize) { - return function(name, parentName) { - // first run map config - if (name[0] != '.' && name[0] != '/' && !name.match(absURLRegEx)) { - var mapMatch = getMapMatch(this.map, name); - if (mapMatch) - name = this.map[mapMatch] + name.substr(mapMatch.length); - } - - // dynamically load node-core modules when requiring `@node/fs` for example - if (name.substr(0, 6) == '@node/' && nodeCoreModules.indexOf(name.substr(6)) != -1) { - if (!this._nodeRequire) - throw new TypeError('Error loading ' + name + '. Can only load node core modules in Node.'); - this.set(name, this.newModule(getESModule(this._nodeRequire(name.substr(6))))); - } - - // relative URL-normalization - if (name[0] == '.' || name[0] == '/') { - if (parentName) - name = new URL(name, parentName.replace(/#/g, '%05')).href.replace(/%05/g, '#'); - else - name = new URL(name, baseURIObj).href; - } - - // if the module is in the registry already, use that - if (this.has(name)) - return name; - - if (name.match(absURLRegEx)) { - // defaultJSExtensions backwards compatibility - if (this.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js') - name += '.js'; - return name; - } - - // applyPaths implementation provided from ModuleLoader system.js source - name = applyPaths(this.paths, name) || name; - - // defaultJSExtensions backwards compatibility - if (this.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js') - name += '.js'; - - // ./x, /x -> page-relative - if (name[0] == '.' || name[0] == '/') - return new URL(name, baseURIObj).href; - // x -> baseURL-relative - else - return new URL(name, getBaseURLObj.call(this)).href; - }; -}); - -// percent encode just '#' in urls if using HTTP requests -var httpRequest = typeof XMLHttpRequest != 'undefined'; -hook('locate', function(locate) { - return function(load) { - return Promise.resolve(locate.call(this, load)) - .then(function(address) { - if (httpRequest) - return address.replace(/#/g, '%23'); - return address; - }); - }; -}); - -/* - * Fetch with authorization - */ -hook('fetch', function() { - return function(load) { - return new Promise(function(resolve, reject) { - fetchTextFromURL(load.address, load.metadata.authorization, resolve, reject); - }); - }; -}); - -/* - __useDefault - - When a module object looks like: - newModule( - __useDefault: true, - default: 'some-module' - }) - - Then importing that module provides the 'some-module' - result directly instead of the full module. - - Useful for eg module.exports = function() {} -*/ -hook('import', function(systemImport) { - return function(name, parentName, parentAddress) { - if (parentName && parentName.name) - warn.call(this, 'SystemJS.import(name, { name: parentName }) is deprecated for SystemJS.import(name, parentName), while importing ' + name + ' from ' + parentName.name); - return systemImport.call(this, name, parentName, parentAddress).then(function(module) { - return module.__useDefault ? module['default'] : module; - }); - }; -}); - -/* - * Allow format: 'detect' meta to enable format detection - */ -hook('translate', function(systemTranslate) { - return function(load) { - if (load.metadata.format == 'detect') - load.metadata.format = undefined; - return systemTranslate.call(this, load); - }; -}); - - -/* - * JSON format support - * - * Supports loading JSON files as a module format itself - * - * Usage: - * - * SystemJS.config({ - * meta: { - * '*.json': { format: 'json' } - * } - * }); - * - * Module is returned as if written: - * - * export default {JSON} - * - * No named exports are provided - * - * Files ending in ".json" are treated as json automatically by SystemJS - */ -hook('instantiate', function(instantiate) { - return function(load) { - if (load.metadata.format == 'json' && !this.builder) { - var entry = load.metadata.entry = createEntry(); - entry.deps = []; - entry.execute = function() { - try { - return JSON.parse(load.source); - } - catch(e) { - throw new Error("Invalid JSON file " + load.name); - } - }; - } - }; -}) - -/* - Extend config merging one deep only - - loader.config({ - some: 'random', - config: 'here', - deep: { - config: { too: 'too' } - } - }); - - <=> - - loader.some = 'random'; - loader.config = 'here' - loader.deep = loader.deep || {}; - loader.deep.config = { too: 'too' }; - - - Normalizes meta and package configs allowing for: - - SystemJS.config({ - meta: { - './index.js': {} - } - }); - - To become - - SystemJS.meta['https://thissite.com/index.js'] = {}; - - For easy normalization canonicalization with latest URL support. - -*/ -SystemJSLoader.prototype.env = 'development'; - -SystemJSLoader.prototype.config = function(cfg) { - var loader = this; - - if ('warnings' in cfg) - loader.warnings = cfg.warnings; - - // always configure baseURL first - if (cfg.baseURL) { - var hasConfig = false; - function checkHasConfig(obj) { - for (var p in obj) - return true; - } - if (checkHasConfig(loader.packages) || checkHasConfig(loader.meta) || checkHasConfig(loader.depCache) || checkHasConfig(loader.bundles) || checkHasConfig(loader.packageConfigPaths)) - throw new TypeError('Incorrect configuration order. The baseURL must be configured with the first SystemJS.config call.'); - - loader.baseURL = cfg.baseURL; - - // sanitize baseURL - getBaseURLObj.call(loader); - } - - if (cfg.defaultJSExtensions) { - loader.defaultJSExtensions = cfg.defaultJSExtensions; - warn.call(loader, 'The defaultJSExtensions configuration option is deprecated, use packages configuration instead.'); - } - - if (cfg.pluginFirst) - loader.pluginFirst = cfg.pluginFirst; - - if (cfg.env) { - if (cfg.env != 'production' && cfg.env != 'development') - throw new TypeError('The config environment must be set to "production" or "development".'); - setConditional.call(loader, cfg.env); - } - - if (cfg.paths) { - for (var p in cfg.paths) - loader.paths[p] = cfg.paths[p]; - } - - function noJSDecanonicalize(name) { - var normalized = loader.decanonicalize(name); - if (loader.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js' && normalized.substr(normalized.length - 3, 3) == '.js') - return normalized.substr(0, normalized.length - 3); - return normalized; - } - - if (cfg.map) { - var objMaps = ''; - for (var p in cfg.map) { - var v = cfg.map[p]; - - // object map backwards-compat into packages configuration - if (typeof v !== 'string') { - objMaps += (objMaps.length ? ', ' : '') + '"' + p + '"'; - - var normalized = noJSDecanonicalize(p); - - // if a package main, revert it - var pkgMatch = ''; - for (var pkg in loader.packages) { - if (normalized.substr(0, pkg.length) == pkg - && (!normalized[pkg.length] || normalized[pkg.length] == '/') - && pkgMatch.split('/').length < pkg.split('/').length) - pkgMatch = pkg; - } - if (pkgMatch && loader.packages[pkgMatch].main) - normalized = normalized.substr(0, normalized.length - loader.packages[pkgMatch].main.length - 1); - - var pkg = loader.packages[normalized] = loader.packages[normalized] || {}; - pkg.map = v; - } - else { - loader.map[p] = v; - } - } - if (objMaps) - warn.call(loader, 'The map configuration for ' + objMaps + ' uses object submaps, which is deprecated in global map.\nUpdate this to use package contextual map with configs like SystemJS.config({ packages: { "' + p + '": { map: {...} } } }).'); - } - - if (cfg.packageConfigPaths) { - var packageConfigPaths = []; - for (var i = 0; i < cfg.packageConfigPaths.length; i++) { - var path = cfg.packageConfigPaths[i]; - var packageLength = Math.max(path.lastIndexOf('*') + 1, path.lastIndexOf('/')); - var normalized = noJSDecanonicalize(path.substr(0, packageLength) + '/'); - normalized = normalized.substr(0, normalized.length - 1) + path.substr(packageLength); - packageConfigPaths[i] = normalized; - } - loader.packageConfigPaths = packageConfigPaths; - } - - if (cfg.bundles) { - for (var p in cfg.bundles) { - var bundle = []; - for (var i = 0; i < cfg.bundles[p].length; i++) - bundle.push(noJSDecanonicalize(cfg.bundles[p][i])); - loader.bundles[p] = bundle; - } - } - - if (cfg.packages) { - for (var p in cfg.packages) { - if (p.match(/^([^\/]+:)?\/\/$/)) - throw new TypeError('"' + p + '" is not a valid package name.'); - - // trailing slash allows paths matches here - var prop = noJSDecanonicalize(p + (p[p.length - 1] != '/' ? '/' : '')); - - // allow trailing '/' in package config - if (prop[prop.length - 1] == '/') - prop = prop.substr(0, prop.length - 1); - - loader.packages[prop] = loader.packages[prop] || {}; - - // meta backwards compatibility - if (cfg.packages[p].modules) { - warn.call(loader, 'Package ' + p + ' is configured with "modules", which is deprecated as it has been renamed to "meta".'); - cfg.packages[p].meta = cfg.packages[p].modules; - delete cfg.packages[p].modules; - } - - for (var q in cfg.packages[p]) - if (indexOf.call(packageProperties, q) == -1) - warn.call(loader, '"' + q + '" is not a valid package configuration option in package ' + p); - - extendMeta(loader.packages[prop], cfg.packages[p]); - } - } - - for (var c in cfg) { - var v = cfg[c]; - var normalizeProp = false; - - if (c == 'baseURL' || c == 'map' || c == 'packages' || c == 'bundles' || c == 'paths' || c == 'warnings' || c == 'packageConfigPaths') - continue; - - if (typeof v != 'object' || v instanceof Array) { - loader[c] = v; - } - else { - loader[c] = loader[c] || {}; - - if (c == 'meta' || c == 'depCache') - normalizeProp = true; - - for (var p in v) { - // base-level wildcard meta does not normalize to retain catch-all quality - if (c == 'meta' && p[0] == '*') - loader[c][p] = v[p]; - else if (normalizeProp) - loader[c][noJSDecanonicalize(p)] = v[p]; - else - loader[c][p] = v[p]; - } - } - } -};/* - * Package Configuration Extension - * - * Example: - * - * SystemJS.packages = { - * jquery: { - * basePath: 'lib', // optionally only use a subdirectory within the package - * main: 'index.js', // when not set, package name is requested directly - * format: 'amd', - * defaultExtension: 'ts', // defaults to 'js', can be set to false - * modules: { - * '*.ts': { - * loader: 'typescript' - * }, - * 'vendor/sizzle.js': { - * format: 'global' - * } - * }, - * map: { - * // map internal require('sizzle') to local require('./vendor/sizzle') - * sizzle: './vendor/sizzle.js', - * // map any internal or external require of 'jquery/vendor/another' to 'another/index.js' - * './vendor/another.js': './another/index.js', - * // test.js / test -> lib/test.js - * './test.js': './lib/test.js', - * - * // environment-specific map configurations - * './index.js': { - * '~browser': './index-node.js' - * } - * }, - * // allows for setting package-prefixed depCache - * // keys are normalized module names relative to the package itself - * depCache: { - * // import 'package/index.js' loads in parallel package/lib/test.js,package/vendor/sizzle.js - * './index.js': ['./test'], - * './test.js': ['external-dep'], - * 'external-dep/path.js': ['./another.js'] - * } - * } - * }; - * - * Then: - * import 'jquery' -> jquery/index.js - * import 'jquery/submodule' -> jquery/submodule.js - * import 'jquery/submodule.ts' -> jquery/submodule.ts loaded as typescript - * import 'jquery/vendor/another' -> another/index.js - * - * Detailed Behaviours - * - main can have a leading "./" can be added optionally - * - map and defaultExtension are applied to the main - * - defaultExtension adds the extension only if the exact extension is not present - * - defaultJSExtensions applies after map when defaultExtension is not set - * - if a meta value is available for a module, map and defaultExtension are skipped - * - like global map, package map also applies to subpaths (sizzle/x, ./vendor/another/sub) - * - condition module map is '@env' module in package or '@system-env' globally - * - map targets support conditional interpolation ('./x': './x.#{|env}.js') - * - internal package map targets cannot use boolean conditionals - * - * In addition, the following modules properties will be allowed to be package - * -relative as well in the package module config: - * - * - loader - * - alias - * - * - * Package Configuration Loading - * - * Not all packages may already have their configuration present in the System config - * For these cases, a list of packageConfigPaths can be provided, which when matched against - * a request, will first request a ".json" file by the package name to derive the package - * configuration from. This allows dynamic loading of non-predetermined code, a key use - * case in SystemJS. - * - * Example: - * - * SystemJS.packageConfigPaths = ['packages/test/package.json', 'packages/*.json']; - * - * // will first request 'packages/new-package/package.json' for the package config - * // before completing the package request to 'packages/new-package/path' - * SystemJS.import('packages/new-package/path'); - * - * // will first request 'packages/test/package.json' before the main - * SystemJS.import('packages/test'); - * - * When a package matches packageConfigPaths, it will always send a config request for - * the package configuration. - * The package name itself is taken to be the match up to and including the last wildcard - * or trailing slash. - * The most specific package config path will be used. - * Any existing package configurations for the package will deeply merge with the - * package config, with the existing package configurations taking preference. - * To opt-out of the package configuration request for a package that matches - * packageConfigPaths, use the { configured: true } package config option. - * - */ -(function() { - - hookConstructor(function(constructor) { - return function() { - constructor.call(this); - this.packages = {}; - this.packageConfigPaths = {}; - }; - }); - - function getPackage(loader, normalized) { - // use most specific package - var curPkg, curPkgLen = 0, pkgLen; - for (var p in loader.packages) { - if (normalized.substr(0, p.length) === p && (normalized.length === p.length || normalized[p.length] === '/')) { - pkgLen = p.split('/').length; - if (pkgLen > curPkgLen) { - curPkg = p; - curPkgLen = pkgLen; - } - } - } - return curPkg; - } - - function getBasePath(pkg) { - // sanitize basePath - var basePath = pkg.basePath && pkg.basePath != '.' ? pkg.basePath : ''; - if (basePath) { - if (basePath.substr(0, 2) == './') - basePath = basePath.substr(2); - if (basePath[basePath.length - 1] != '/') - basePath += '/'; - } - return basePath; - } - - function addDefaultExtension(loader, pkg, pkgName, basePath, subPath, skipExtensions) { - // don't apply extensions to folders or if defaultExtension = false - if (!subPath || subPath[subPath.length - 1] == '/' || skipExtensions || pkg.defaultExtension === false) - return subPath; - - // NB are you sure about this? - // skip if we have interpolation conditional syntax in subPath? - if (subPath.match(interpolationRegEx)) - return subPath; - - var metaMatch = false; - - // exact meta or meta with any content after the last wildcard skips extension - if (pkg.meta) - getMetaMatches(pkg.meta, subPath, function(metaPattern, matchMeta, matchDepth) { - if (matchDepth == 0 || metaPattern.lastIndexOf('*') != metaPattern.length - 1) - return metaMatch = true; - }); - - // exact global meta or meta with any content after the last wildcard skips extension - if (!metaMatch && loader.meta) - getMetaMatches(loader.meta, pkgName + '/' + basePath + subPath, function(metaPattern, matchMeta, matchDepth) { - if (matchDepth == 0 || metaPattern.lastIndexOf('*') != metaPattern.length - 1) - return metaMatch = true; - }); - - if (metaMatch) - return subPath; - - // work out what the defaultExtension is and add if not there already - // NB reconsider if default should really be ".js"? - var defaultExtension = '.' + (pkg.defaultExtension || 'js'); - if (subPath.substr(subPath.length - defaultExtension.length) != defaultExtension) - return subPath + defaultExtension; - else - return subPath; - } - - function applyPackageConfigSync(loader, pkg, pkgName, subPath, skipExtensions) { - // main - if (!subPath) { - if (pkg.main) - subPath = pkg.main.substr(0, 2) == './' ? pkg.main.substr(2) : pkg.main; - // also no submap if name is package itself (import 'pkg' -> 'path/to/pkg.js') - else - // NB can add a default package main convention here when defaultJSExtensions is deprecated - // if it becomes internal to the package then it would no longer be an exit path - return pkgName + (loader.defaultJSExtensions ? '.js' : ''); - } - - var basePath = getBasePath(pkg); - - // map config checking without then with extensions - if (pkg.map) { - var mapPath = './' + subPath; - - var mapMatch = getMapMatch(pkg.map, mapPath); - - // we then check map with the default extension adding - if (!mapMatch) { - mapPath = './' + addDefaultExtension(loader, pkg, pkgName, basePath, subPath, skipExtensions); - if (mapPath != './' + subPath) - mapMatch = getMapMatch(pkg.map, mapPath); - } - if (mapMatch) - return doMapSync(loader, pkg, pkgName, basePath, mapMatch, mapPath, skipExtensions); - } - - // normal package resolution - return pkgName + '/' + basePath + addDefaultExtension(loader, pkg, pkgName, basePath, subPath, skipExtensions); - } - - function doMapSync(loader, pkg, pkgName, basePath, mapMatch, path, skipExtensions) { - var mapped = pkg.map[mapMatch]; - - // ignore conditionals in sync - if (typeof mapped != 'string') - mapped = mapMatch = path; - - // package map to main / base-level - if (mapped == '.') - mapped = pkgName; - - // internal package map - else if (mapped.substr(0, 2) == './') - return pkgName + '/' + basePath + addDefaultExtension(loader, pkg, pkgName, basePath, mapped.substr(2) + path.substr(mapMatch.length), skipExtensions); - - // external map reference - return loader.normalizeSync(mapped + path.substr(mapMatch.length), pkgName + '/'); - } - - function applyPackageConfig(loader, pkg, pkgName, subPath, skipExtensions) { - // main - if (!subPath) { - if (pkg.main) - subPath = pkg.main.substr(0, 2) == './' ? pkg.main.substr(2) : pkg.main; - // also no submap if name is package itself (import 'pkg' -> 'path/to/pkg.js') - else - // NB can add a default package main convention here when defaultJSExtensions is deprecated - // if it becomes internal to the package then it would no longer be an exit path - return Promise.resolve(pkgName + (loader.defaultJSExtensions ? '.js' : '')); - } - - var basePath = getBasePath(pkg); - - // map config checking without then with extensions - var mapPath, mapMatch; - - if (pkg.map) { - mapPath = './' + subPath; - mapMatch = getMapMatch(pkg.map, mapPath); - - // we then check map with the default extension adding - if (!mapMatch) { - mapPath = './' + addDefaultExtension(loader, pkg, pkgName, basePath, subPath, skipExtensions); - if (mapPath != './' + subPath) - mapMatch = getMapMatch(pkg.map, mapPath); - } - } - - return (mapMatch ? doMap(loader, pkg, pkgName, basePath, mapMatch, mapPath, skipExtensions) : Promise.resolve()) - .then(function(mapped) { - if (mapped) - return Promise.resolve(mapped); - - // normal package resolution / fallback resolution for no conditional match - return Promise.resolve(pkgName + '/' + basePath + addDefaultExtension(loader, pkg, pkgName, basePath, subPath, skipExtensions)); - }); - } - - function doStringMap(loader, pkg, pkgName, basePath, mapMatch, mapped, path, skipExtensions) { - // NB the interpolation cases should strictly skip subsequent interpolation - - // package map to main / base-level - if (mapped == '.') - mapped = pkgName; - - // internal package map - else if (mapped.substr(0, 2) == './') - return Promise.resolve(pkgName + '/' + basePath + addDefaultExtension(loader, pkg, pkgName, basePath, mapped.substr(2) + path.substr(mapMatch.length), skipExtensions)) - .then(function(name) { - return interpolateConditional.call(loader, name, pkgName + '/'); - }); - - // external map reference - // NB deprecate the use of the second argument here -> should be fully global reference - return loader.normalize(mapped + path.substr(mapMatch.length), pkgName + '/'); - } - - function doMap(loader, pkg, pkgName, basePath, mapMatch, path, skipExtensions) { - var mapped = pkg.map[mapMatch]; - - if (typeof mapped == 'string') - return doStringMap(loader, pkg, pkgName, basePath, mapMatch, mapped, path, skipExtensions); - - // we use a special conditional syntax to allow the builder to handle conditional branch points further - if (loader.builder) - return Promise.resolve(pkgName + '/#:' + path); - - // map object -> conditional map - return loader['import'](pkg.map['@env'] || '@system-env', pkgName) - .then(function(env) { - // first map condition to match is used - for (var e in mapped) { - var negate = e[0] == '~'; - - var value = readMemberExpression(negate ? e.substr(1) : e, env); - - if (!negate && value || negate && !value) - return mapped[e]; - } - }) - .then(function(mapped) { - if (mapped) - return doStringMap(loader, pkg, pkgName, basePath, mapMatch, mapped, path, skipExtensions); - - // no environment match -> fallback to original subPath by returning undefined - }); - } - - // normalizeSync = decanonicalize + package resolution - SystemJSLoader.prototype.normalizeSync = SystemJSLoader.prototype.decanonicalize = SystemJSLoader.prototype.normalize; - - // decanonicalize must JUST handle package defaultExtension: false case when defaultJSExtensions is set - // to be deprecated! - hook('decanonicalize', function(decanonicalize) { - return function(name, parentName) { - var decanonicalized = decanonicalize.call(this, name, parentName); - - if (!this.defaultJSExtensions) - return decanonicalized; - - var pkgName = getPackage(this, decanonicalized); - - var defaultExtension = pkgName && this.packages[pkgName].defaultExtension; - - if (defaultExtension && (defaultExtension === false || defaultExtension != '.js') && name.substr(name.length - 3, 3) != '.js' && decanonicalized.substr(decanonicalized.length - 3, 3) == '.js') - decanonicalized = decanonicalized.substr(0, decanonicalized.length - 3); - - return decanonicalized; - }; - }); - - hook('normalizeSync', function(normalizeSync) { - return function(name, parentName, isPlugin) { - warn.call(this, 'SystemJS.normalizeSync has been deprecated for SystemJS.decanonicalize.'); - - var loader = this; - isPlugin = isPlugin === true; - - // apply contextual package map first - // (we assume the parent package config has already been loaded) - if (parentName) - var parentPackageName = getPackage(loader, parentName) || - loader.defaultJSExtensions && parentName.substr(parentName.length - 3, 3) == '.js' && - getPackage(loader, parentName.substr(0, parentName.length - 3)); - - var parentPackage = parentPackageName && loader.packages[parentPackageName]; - - // remove any parent basePath from parentName - if (parentPackage) { - var parentBasePath = getBasePath(parentPackage); - if (parentBasePath && parentName.substr(parentPackageName.length + 1, parentBasePath.length) == parentBasePath) - parentName = parentPackageName + parentName.substr(parentPackageName.length + parentBasePath.length); - } - - // ignore . since internal maps handled by standard package resolution - if (parentPackage && name[0] != '.') { - var parentMap = parentPackage.map; - var parentMapMatch = parentMap && getMapMatch(parentMap, name); - - if (parentMapMatch && typeof parentMap[parentMapMatch] == 'string') - return doMapSync(loader, parentPackage, parentPackageName, getBasePath(parentPackage), parentMapMatch, name, isPlugin); - } - - var defaultJSExtension = loader.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js'; - - // apply map, core, paths, contextual package map - var normalized = normalizeSync.call(loader, name, parentName); - - // undo defaultJSExtension - if (defaultJSExtension && normalized.substr(normalized.length - 3, 3) != '.js') - defaultJSExtension = false; - if (defaultJSExtension) - normalized = normalized.substr(0, normalized.length - 3); - - var pkgConfigMatch = getPackageConfigMatch(loader, normalized); - var pkgName = pkgConfigMatch && pkgConfigMatch.packageName || getPackage(loader, normalized); - - if (!pkgName) - return normalized + (defaultJSExtension ? '.js' : ''); - - var subPath = normalized.substr(pkgName.length + 1); - - // allow for direct package name normalization with trailling "/" (no main) - // that is normalize('pkg/') does not apply main, while normalize('./', 'pkg/') does - if (!subPath && normalized.length == pkgName.length + 1 && name[0] != '.') - return pkgName + subPath; - - return applyPackageConfigSync(loader, loader.packages[pkgName] || {}, pkgName, subPath, isPlugin); - }; - }); - - hook('normalize', function(normalize) { - return function(name, parentName, isPlugin) { - var loader = this; - isPlugin = isPlugin === true; - - return Promise.resolve() - .then(function() { - // apply contextual package map first - // (we assume the parent package config has already been loaded) - if (parentName) - var parentPackageName = getPackage(loader, parentName) || - loader.defaultJSExtensions && parentName.substr(parentName.length - 3, 3) == '.js' && - getPackage(loader, parentName.substr(0, parentName.length - 3)); - - var parentPackage = parentPackageName && loader.packages[parentPackageName]; - - // remove any parent basePath from parentName - if (parentPackage) { - var parentBasePath = getBasePath(parentPackage); - if (parentBasePath && parentName.substr(parentPackageName.length + 1, parentBasePath.length) == parentBasePath) - parentName = parentPackageName + parentName.substr(parentPackageName.length + parentBasePath.length); - } - - // ignore . since internal maps handled by standard package resolution - if (parentPackage && name.substr(0, 2) != './') { - var parentMap = parentPackage.map; - var parentMapMatch = parentMap && getMapMatch(parentMap, name); - - if (parentMapMatch) - return doMap(loader, parentPackage, parentPackageName, parentBasePath, parentMapMatch, name, isPlugin); - } - - return Promise.resolve(); - }) - .then(function(mapped) { - if (mapped) - return mapped; - - var defaultJSExtension = loader.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js'; - - // apply map, core, paths, contextual package map - var normalized = normalize.call(loader, name, parentName); - - // undo defaultJSExtension - if (defaultJSExtension && normalized.substr(normalized.length - 3, 3) != '.js') - defaultJSExtension = false; - if (defaultJSExtension) - normalized = normalized.substr(0, normalized.length - 3); - - var pkgConfigMatch = getPackageConfigMatch(loader, normalized); - var pkgName = pkgConfigMatch && pkgConfigMatch.packageName || getPackage(loader, normalized); - - if (!pkgName) - return Promise.resolve(normalized + (defaultJSExtension ? '.js' : '')); - - var pkg = loader.packages[pkgName]; - - // if package is already configured or not a dynamic config package, use existing package config - var isConfigured = pkg && (pkg.configured || !pkgConfigMatch); - return (isConfigured ? Promise.resolve(pkg) : loadPackageConfigPath(loader, pkgName, pkgConfigMatch.configPath)) - .then(function(pkg) { - var subPath = normalized.substr(pkgName.length + 1); - - // allow for direct package name normalization with trailling "/" (no main) - // that is normalize('pkg/') does not apply main, while normalize('./', 'pkg/') does - if (!subPath && normalized.length == pkgName.length + 1 && name[0] != '.') - return Promise.resolve(pkgName + subPath); - - return applyPackageConfig(loader, pkg, pkgName, subPath, isPlugin); - }); - }); - }; - }); - - // check if the given normalized name matches a packageConfigPath - // if so, loads the config - var packageConfigPaths = {}; - - // data object for quick checks against package paths - function createPkgConfigPathObj(path) { - var lastWildcard = path.lastIndexOf('*'); - var length = Math.max(lastWildcard + 1, path.lastIndexOf('/')); - return { - length: length, - // NB handle regex control character escapes or simply create a test function here - regEx: new RegExp('^(' + path.substr(0, length).replace(/\*/g, '[^\\/]+') + ')(\\/|$)'), - wildcard: lastWildcard != -1 - }; - } - - // most specific match wins - function getPackageConfigMatch(loader, normalized) { - var pkgName, exactMatch = false, configPath; - for (var i = 0; i < loader.packageConfigPaths.length; i++) { - var packageConfigPath = loader.packageConfigPaths[i]; - var p = packageConfigPaths[packageConfigPath] || (packageConfigPaths[packageConfigPath] = createPkgConfigPathObj(packageConfigPath)); - if (normalized.length < p.length) - continue; - var match = normalized.match(p.regEx); - if (match && (!pkgName || (!(exactMatch && p.wildcard) && pkgName.length < match[1].length))) { - pkgName = match[1]; - exactMatch = !p.wildcard; - configPath = pkgName + packageConfigPath.substr(p.length); - } - } - - if (!pkgName) - return; - - return { - packageName: pkgName, - configPath: configPath - }; - } - - function loadPackageConfigPath(loader, pkgName, pkgConfigPath) { - var configLoader = loader.pluginLoader || loader; - - // NB remove this when json is default - (configLoader.meta[pkgConfigPath] = configLoader.meta[pkgConfigPath] || {}).format = 'json'; - - return configLoader.load(pkgConfigPath) - .then(function() { - pkgConfig = configLoader.get(pkgConfigPath); - - var cfg = pkgConfig['default']; - - // support "systemjs" prefixing - if (cfg.systemjs) - cfg = cfg.systemjs; - - // modules backwards compatibility - if (cfg.modules) { - cfg.meta = cfg.modules; - warn.call(loader, 'Package config file ' + pkgConfigPath + ' is configured with "modules", which is deprecated as it has been renamed to "meta".'); - } - - // remove any non-system properties if generic config file (eg package.json) - for (var p in cfg) { - if (indexOf.call(packageProperties, p) == -1) - delete cfg[p]; - } - - // deeply-merge (to first level) config with any existing package config - var pkg = loader.packages[pkgName] = loader.packages[pkgName] || {}; - extendMeta(pkg, cfg, true); - - // support external depCache - var basePath = getBasePath(pkg); - if (cfg.depCache) { - for (var d in cfg.depCache) { - var dNormalized; - - if (d.substr(0, 2) == './') - dNormalized = pkgName + '/' + basePath + d.substr(2); - else - dNormalized = coreResolve.call(loader, d); - loader.depCache[dNormalized] = (loader.depCache[dNormalized] || []).concat(cfg.depCache[d]); - } - delete cfg.depCache; - } - - return pkg; - }); - } - - function getMetaMatches(pkgMeta, subPath, matchFn) { - // wildcard meta - var meta = {}; - var wildcardIndex; - for (var module in pkgMeta) { - // allow meta to start with ./ for flexibility - var dotRel = module.substr(0, 2) == './' ? './' : ''; - if (dotRel) - module = module.substr(2); - - wildcardIndex = module.indexOf('*'); - if (wildcardIndex === -1) - continue; - - if (module.substr(0, wildcardIndex) == subPath.substr(0, wildcardIndex) - && module.substr(wildcardIndex + 1) == subPath.substr(subPath.length - module.length + wildcardIndex + 1)) { - // alow match function to return true for an exit path - if (matchFn(module, pkgMeta[dotRel + module], module.split('/').length)) - return; - } - } - // exact meta - var exactMeta = pkgMeta[subPath] || pkgMeta['./' + subPath]; - if (exactMeta) - matchFn(exactMeta, exactMeta, 0); - } - - hook('locate', function(locate) { - return function(load) { - var loader = this; - return Promise.resolve(locate.call(this, load)) - .then(function(address) { - var pkgName = getPackage(loader, load.name); - if (pkgName) { - var pkg = loader.packages[pkgName]; - var basePath = getBasePath(pkg); - var subPath = load.name.substr(pkgName.length + basePath.length + 1); - - // format - if (pkg.format) - load.metadata.format = load.metadata.format || pkg.format; - - var meta = {}; - if (pkg.meta) { - var bestDepth = 0; - - // NB support a main shorthand in meta here? - getMetaMatches(pkg.meta, subPath, function(metaPattern, matchMeta, matchDepth) { - if (matchDepth > bestDepth) - bestDepth = matchDepth; - extendMeta(meta, matchMeta, matchDepth && bestDepth > matchDepth); - }); - - // allow alias and loader to be package-relative - if (meta.alias && meta.alias.substr(0, 2) == './') - meta.alias = pkgName + meta.alias.substr(1); - if (meta.loader && meta.loader.substr(0, 2) == './') - meta.loader = pkgName + meta.loader.substr(1); - extendMeta(load.metadata, meta); - } - } - - return address; - }); - }; - }); - -})(); -/* - * Script tag fetch - * - * When load.metadata.scriptLoad is true, we load via script tag injection. - */ -(function() { - - if (typeof document != 'undefined') - var head = document.getElementsByTagName('head')[0]; - - var curSystem; - - // if doing worker executing, this is set to the load record being executed - var workerLoad = null; - - // interactive mode handling method courtesy RequireJS - var ieEvents = head && (function() { - var s = document.createElement('script'); - var isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]'; - return s.attachEvent && !(s.attachEvent.toString && s.attachEvent.toString().indexOf('[native code') < 0) && !isOpera; - })(); - - // IE interactive-only part - // we store loading scripts array as { script: <script>, load: {...} } - var interactiveLoadingScripts = []; - var interactiveScript; - function getInteractiveScriptLoad() { - if (interactiveScript && interactiveScript.script.readyState === 'interactive') - return interactiveScript.load; - - for (var i = 0; i < interactiveLoadingScripts.length; i++) - if (interactiveLoadingScripts[i].script.readyState == 'interactive') { - interactiveScript = interactiveLoadingScripts[i]; - return interactiveScript.load; - } - } - - // System.register, System.registerDynamic, AMD define pipeline - // this is called by the above methods when they execute - // we then run the reduceRegister_ collection function either immediately - // if we are in IE and know the currently executing script (interactive) - // or later if we need to wait for the synchronous load callback to know the script - var loadingCnt = 0; - var registerQueue = []; - hook('pushRegister_', function(pushRegister) { - return function(register) { - // if using eval-execution then skip - if (pushRegister.call(this, register)) - return false; - - // if using worker execution, then we're done - if (workerLoad) - this.reduceRegister_(workerLoad, register); - - // detect if we know the currently executing load (IE) - // if so, immediately call reduceRegister - else if (ieEvents) - this.reduceRegister_(getInteractiveScriptLoad(), register); - - // otherwise, add to our execution queue - // to call reduceRegister on sync script load event - else if (loadingCnt) - registerQueue.push(register); - - // if we're not currently loading anything though - // then do the reduction against a null load - // (out of band named define or named register) - // note even in non-script environments, this catch is used - else - this.reduceRegister_(null, register); - - return true; - }; - }); - - function webWorkerImport(loader, load) { - return new Promise(function(resolve, reject) { - if (load.metadata.integrity) - reject(new Error('Subresource integrity checking is not supported in web workers.')); - - workerLoad = load; - try { - importScripts(load.address); - } - catch(e) { - workerLoad = null; - reject(e); - } - workerLoad = null; - - // if nothing registered, then something went wrong - if (!load.metadata.entry) - reject(new Error(load.address + ' did not call System.register or AMD define')); - - resolve(''); - }); - } - - // override fetch to use script injection - hook('fetch', function(fetch) { - return function(load) { - var loader = this; - - if (!load.metadata.scriptLoad || (!isBrowser && !isWorker)) - return fetch.call(this, load); - - if (isWorker) - return webWorkerImport(loader, load); - - return new Promise(function(resolve, reject) { - var s = document.createElement('script'); - - s.async = true; - - if (load.metadata.integrity) - s.setAttribute('integrity', load.metadata.integrity); - - if (ieEvents) { - s.attachEvent('onreadystatechange', complete); - interactiveLoadingScripts.push({ - script: s, - load: load - }); - } - else { - s.addEventListener('load', complete, false); - s.addEventListener('error', error, false); - } - - loadingCnt++; - - curSystem = __global.System; - - s.src = load.address; - head.appendChild(s); - - function complete(evt) { - if (s.readyState && s.readyState != 'loaded' && s.readyState != 'complete') - return; - - loadingCnt--; - - // complete call is sync on execution finish - // (in ie already done reductions) - if (!load.metadata.entry && !registerQueue.length) { - loader.reduceRegister_(load); - } - else if (!ieEvents) { - for (var i = 0; i < registerQueue.length; i++) - loader.reduceRegister_(load, registerQueue[i]); - registerQueue = []; - } - - cleanup(); - - // if nothing registered, then something went wrong - if (!load.metadata.entry && !load.metadata.bundle) - reject(new Error(load.name + ' did not call System.register or AMD define. If loading a global module configure the global name via the meta exports property for script injection support.')); - - resolve(''); - } - - function error(evt) { - cleanup(); - reject(new Error('Unable to load script ' + load.address)); - } - - function cleanup() { - __global.System = curSystem; - - if (s.detachEvent) { - s.detachEvent('onreadystatechange', complete); - for (var i = 0; i < interactiveLoadingScripts.length; i++) - if (interactiveLoadingScripts[i].script == s) { - if (interactiveScript && interactiveScript.script == s) - interactiveScript = null; - interactiveLoadingScripts.splice(i, 1); - } - } - else { - s.removeEventListener('load', complete, false); - s.removeEventListener('error', error, false); - } - - head.removeChild(s); - } - }); - }; - }); -})(); -/* - * Instantiate registry extension - * - * Supports Traceur System.register 'instantiate' output for loading ES6 as ES5. - * - * - Creates the loader.register function - * - Also supports metadata.format = 'register' in instantiate for anonymous register modules - * - Also supports metadata.deps, metadata.execute and metadata.executingRequire - * for handling dynamic modules alongside register-transformed ES6 modules - * - * - * The code here replicates the ES6 linking groups algorithm to ensure that - * circular ES6 compiled into System.register can work alongside circular AMD - * and CommonJS, identically to the actual ES6 loader. - * - */ - - -/* - * Registry side table entries in loader.defined - * Registry Entry Contains: - * - name - * - deps - * - declare for declarative modules - * - execute for dynamic modules, different to declarative execute on module - * - executingRequire indicates require drives execution for circularity of dynamic modules - * - declarative optional boolean indicating which of the above - * - * Can preload modules directly on SystemJS.defined['my/module'] = { deps, execute, executingRequire } - * - * Then the entry gets populated with derived information during processing: - * - normalizedDeps derived from deps, created in instantiate - * - groupIndex used by group linking algorithm - * - evaluated indicating whether evaluation has happend - * - module the module record object, containing: - * - exports actual module exports - * - * For dynamic we track the es module with: - * - esModule actual es module value - * - esmExports whether to extend the esModule with named exports - * - * Then for declarative only we track dynamic bindings with the 'module' records: - * - name - * - exports - * - setters declarative setter functions - * - dependencies, module records of dependencies - * - importers, module records of dependents - * - * After linked and evaluated, entries are removed, declarative module records remain in separate - * module binding table - * - */ - -var leadingCommentAndMetaRegEx = /^\s*(\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\s*\/\/[^\n]*|\s*"[^"]+"\s*;?|\s*'[^']+'\s*;?)*\s*/; -function detectRegisterFormat(source) { - var leadingCommentAndMeta = source.match(leadingCommentAndMetaRegEx); - return leadingCommentAndMeta && source.substr(leadingCommentAndMeta[0].length, 15) == 'System.register'; -} - -function createEntry() { - return { - name: null, - deps: null, - originalIndices: null, - declare: null, - execute: null, - executingRequire: false, - declarative: false, - normalizedDeps: null, - groupIndex: null, - evaluated: false, - module: null, - esModule: null, - esmExports: false - }; -} - -(function() { - - /* - * There are two variations of System.register: - * 1. System.register for ES6 conversion (2-3 params) - System.register([name, ]deps, declare) - * see https://github.com/ModuleLoader/es6-module-loader/wiki/System.register-Explained - * - * 2. System.registerDynamic for dynamic modules (3-4 params) - System.registerDynamic([name, ]deps, executingRequire, execute) - * the true or false statement - * - * this extension implements the linking algorithm for the two variations identical to the spec - * allowing compiled ES6 circular references to work alongside AMD and CJS circular references. - * - */ - SystemJSLoader.prototype.register = function(name, deps, declare) { - if (typeof name != 'string') { - declare = deps; - deps = name; - name = null; - } - - // dynamic backwards-compatibility - // can be deprecated eventually - if (typeof declare == 'boolean') - return this.registerDynamic.apply(this, arguments); - - var entry = createEntry(); - // ideally wouldn't apply map config to bundle names but - // dependencies go through map regardless so we can't restrict - // could reconsider in shift to new spec - entry.name = name && (this.decanonicalize || this.normalize).call(this, name); - entry.declarative = true; - entry.deps = deps; - entry.declare = declare; - - this.pushRegister_({ - amd: false, - entry: entry - }); - }; - SystemJSLoader.prototype.registerDynamic = function(name, deps, declare, execute) { - if (typeof name != 'string') { - execute = declare; - declare = deps; - deps = name; - name = null; - } - - // dynamic - var entry = createEntry(); - entry.name = name && (this.decanonicalize || this.normalize).call(this, name); - entry.deps = deps; - entry.execute = execute; - entry.executingRequire = declare; - - this.pushRegister_({ - amd: false, - entry: entry - }); - }; - hook('reduceRegister_', function() { - return function(load, register) { - if (!register) - return; - - var entry = register.entry; - var curMeta = load && load.metadata; - - // named register - if (entry.name) { - if (!(entry.name in this.defined)) - this.defined[entry.name] = entry; - - if (curMeta) - curMeta.bundle = true; - } - // anonymous register - if (!entry.name || load && entry.name == load.name) { - if (!curMeta) - throw new TypeError('Unexpected anonymous System.register call.'); - if (curMeta.entry) { - if (curMeta.format == 'register') - throw new Error('Multiple anonymous System.register calls in module ' + load.name + '. If loading a bundle, ensure all the System.register calls are named.'); - else - throw new Error('Module ' + load.name + ' interpreted as ' + curMeta.format + ' module format, but called System.register.'); - } - if (!curMeta.format) - curMeta.format = 'register'; - curMeta.entry = entry; - } - }; - }); - - hookConstructor(function(constructor) { - return function() { - constructor.call(this); - - this.defined = {}; - this._loader.moduleRecords = {}; - }; - }); - - function buildGroups(entry, loader, groups) { - groups[entry.groupIndex] = groups[entry.groupIndex] || []; - - if (indexOf.call(groups[entry.groupIndex], entry) != -1) - return; - - groups[entry.groupIndex].push(entry); - - for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { - var depName = entry.normalizedDeps[i]; - var depEntry = loader.defined[depName]; - - // not in the registry means already linked / ES6 - if (!depEntry || depEntry.evaluated) - continue; - - // now we know the entry is in our unlinked linkage group - var depGroupIndex = entry.groupIndex + (depEntry.declarative != entry.declarative); - - // the group index of an entry is always the maximum - if (depEntry.groupIndex === null || depEntry.groupIndex < depGroupIndex) { - - // if already in a group, remove from the old group - if (depEntry.groupIndex !== null) { - groups[depEntry.groupIndex].splice(indexOf.call(groups[depEntry.groupIndex], depEntry), 1); - - // if the old group is empty, then we have a mixed depndency cycle - if (groups[depEntry.groupIndex].length == 0) - throw new Error("Mixed dependency cycle detected"); - } - - depEntry.groupIndex = depGroupIndex; - } - - buildGroups(depEntry, loader, groups); - } - } - - function link(name, loader) { - var startEntry = loader.defined[name]; - - // skip if already linked - if (startEntry.module) - return; - - startEntry.groupIndex = 0; - - var groups = []; - - buildGroups(startEntry, loader, groups); - - var curGroupDeclarative = !!startEntry.declarative == groups.length % 2; - for (var i = groups.length - 1; i >= 0; i--) { - var group = groups[i]; - for (var j = 0; j < group.length; j++) { - var entry = group[j]; - - // link each group - if (curGroupDeclarative) - linkDeclarativeModule(entry, loader); - else - linkDynamicModule(entry, loader); - } - curGroupDeclarative = !curGroupDeclarative; - } - } - - // module binding records - function Module() {} - defineProperty(Module, 'toString', { - value: function() { - return 'Module'; - } - }); - - function getOrCreateModuleRecord(name, moduleRecords) { - return moduleRecords[name] || (moduleRecords[name] = { - name: name, - dependencies: [], - exports: new Module(), // start from an empty module and extend - importers: [] - }); - } - - function linkDeclarativeModule(entry, loader) { - // only link if already not already started linking (stops at circular) - if (entry.module) - return; - - var moduleRecords = loader._loader.moduleRecords; - var module = entry.module = getOrCreateModuleRecord(entry.name, moduleRecords); - var exports = entry.module.exports; - - var declaration = entry.declare.call(__global, function(name, value) { - module.locked = true; - - if (typeof name == 'object') { - for (var p in name) - exports[p] = name[p]; - } - else { - exports[name] = value; - } - - for (var i = 0, l = module.importers.length; i < l; i++) { - var importerModule = module.importers[i]; - if (!importerModule.locked) { - var importerIndex = indexOf.call(importerModule.dependencies, module); - importerModule.setters[importerIndex](exports); - } - } - - module.locked = false; - return value; - }, entry.name); - - module.setters = declaration.setters; - module.execute = declaration.execute; - - if (!module.setters || !module.execute) { - throw new TypeError('Invalid System.register form for ' + entry.name); - } - - // now link all the module dependencies - for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { - var depName = entry.normalizedDeps[i]; - var depEntry = loader.defined[depName]; - var depModule = moduleRecords[depName]; - - // work out how to set depExports based on scenarios... - var depExports; - - if (depModule) { - depExports = depModule.exports; - } - // dynamic, already linked in our registry - else if (depEntry && !depEntry.declarative) { - depExports = depEntry.esModule; - } - // in the loader registry - else if (!depEntry) { - depExports = loader.get(depName); - } - // we have an entry -> link - else { - linkDeclarativeModule(depEntry, loader); - depModule = depEntry.module; - depExports = depModule.exports; - } - - // only declarative modules have dynamic bindings - if (depModule && depModule.importers) { - depModule.importers.push(module); - module.dependencies.push(depModule); - } - else { - module.dependencies.push(null); - } - - // run setters for all entries with the matching dependency name - var originalIndices = entry.originalIndices[i]; - for (var j = 0, len = originalIndices.length; j < len; ++j) { - var index = originalIndices[j]; - if (module.setters[index]) { - module.setters[index](depExports); - } - } - } - } - - // An analog to loader.get covering execution of all three layers (real declarative, simulated declarative, simulated dynamic) - function getModule(name, loader) { - var exports; - var entry = loader.defined[name]; - - if (!entry) { - exports = loader.get(name); - if (!exports) - throw new Error('Unable to load dependency ' + name + '.'); - } - - else { - if (entry.declarative) - ensureEvaluated(name, [], loader); - - else if (!entry.evaluated) - linkDynamicModule(entry, loader); - - exports = entry.module.exports; - } - - if ((!entry || entry.declarative) && exports && exports.__useDefault) - return exports['default']; - - return exports; - } - - function linkDynamicModule(entry, loader) { - if (entry.module) - return; - - var exports = {}; - - var module = entry.module = { exports: exports, id: entry.name }; - - // AMD requires execute the tree first - if (!entry.executingRequire) { - for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { - var depName = entry.normalizedDeps[i]; - // we know we only need to link dynamic due to linking algorithm - var depEntry = loader.defined[depName]; - if (depEntry) - linkDynamicModule(depEntry, loader); - } - } - - // now execute - entry.evaluated = true; - var output = entry.execute.call(__global, function(name) { - for (var i = 0, l = entry.deps.length; i < l; i++) { - if (entry.deps[i] != name) - continue; - return getModule(entry.normalizedDeps[i], loader); - } - throw new Error('Module ' + name + ' not declared as a dependency.'); - }, exports, module); - - if (output) - module.exports = output; - - // create the esModule object, which allows ES6 named imports of dynamics - exports = module.exports; - - // __esModule flag treats as already-named - if (exports && exports.__esModule) - entry.esModule = exports; - // set module as 'default' export, then fake named exports by iterating properties - else if (entry.esmExports && exports !== __global) - entry.esModule = getESModule(exports); - // just use the 'default' export - else - entry.esModule = { 'default': exports }; - } - - /* - * Given a module, and the list of modules for this current branch, - * ensure that each of the dependencies of this module is evaluated - * (unless one is a circular dependency already in the list of seen - * modules, in which case we execute it) - * - * Then we evaluate the module itself depth-first left to right - * execution to match ES6 modules - */ - function ensureEvaluated(moduleName, seen, loader) { - var entry = loader.defined[moduleName]; - - // if already seen, that means it's an already-evaluated non circular dependency - if (!entry || entry.evaluated || !entry.declarative) - return; - - // this only applies to declarative modules which late-execute - - seen.push(moduleName); - - for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { - var depName = entry.normalizedDeps[i]; - if (indexOf.call(seen, depName) == -1) { - if (!loader.defined[depName]) - loader.get(depName); - else - ensureEvaluated(depName, seen, loader); - } - } - - if (entry.evaluated) - return; - - entry.evaluated = true; - entry.module.execute.call(__global); - } - - // override the delete method to also clear the register caches - hook('delete', function(del) { - return function(name) { - delete this._loader.moduleRecords[name]; - delete this.defined[name]; - return del.call(this, name); - }; - }); - - hook('fetch', function(fetch) { - return function(load) { - if (this.defined[load.name]) { - load.metadata.format = 'defined'; - return ''; - } - - if (load.metadata.format == 'register' && !load.metadata.authorization && load.metadata.scriptLoad !== false) - load.metadata.scriptLoad = true; - - load.metadata.deps = load.metadata.deps || []; - - return fetch.call(this, load); - }; - }); - - hook('translate', function(translate) { - // we run the meta detection here (register is after meta) - return function(load) { - load.metadata.deps = load.metadata.deps || []; - return Promise.resolve(translate.call(this, load)).then(function(source) { - // run detection for register format - if (load.metadata.format == 'register' || !load.metadata.format && detectRegisterFormat(load.source)) - load.metadata.format = 'register'; - return source; - }); - }; - }); - - hook('instantiate', function(instantiate) { - return function(load) { - if (load.metadata.format == 'detect') - load.metadata.format = undefined; - - // assumes previous instantiate is sync - // (core json support) - instantiate.call(this, load); - - var loader = this; - - var entry; - - // first we check if this module has already been defined in the registry - if (loader.defined[load.name]) { - entry = loader.defined[load.name]; - // don't support deps for ES modules - if (!entry.declarative) - entry.deps = entry.deps.concat(load.metadata.deps); - } - - // picked up already by an anonymous System.register script injection - // or via the dynamic formats - else if (load.metadata.entry) { - entry = load.metadata.entry; - entry.deps = entry.deps.concat(load.metadata.deps); - } - - // Contains System.register calls - // (dont run bundles in the builder) - else if (!(loader.builder && load.metadata.bundle) - && (load.metadata.format == 'register' || load.metadata.format == 'esm' || load.metadata.format == 'es6')) { - - if (typeof __exec != 'undefined') - __exec.call(loader, load); - - if (!load.metadata.entry && !load.metadata.bundle) - throw new Error(load.name + ' detected as ' + load.metadata.format + ' but didn\'t execute.'); - - entry = load.metadata.entry; - - // support metadata deps for System.register - if (entry && load.metadata.deps) - entry.deps = entry.deps.concat(load.metadata.deps); - } - - // named bundles are just an empty module - if (!entry) { - entry = createEntry(); - entry.deps = load.metadata.deps; - entry.execute = function() {}; - } - - // place this module onto defined for circular references - loader.defined[load.name] = entry; - - var grouped = group(entry.deps); - - entry.deps = grouped.names; - entry.originalIndices = grouped.indices; - entry.name = load.name; - entry.esmExports = load.metadata.esmExports !== false; - - // first, normalize all dependencies - var normalizePromises = []; - for (var i = 0, l = entry.deps.length; i < l; i++) - normalizePromises.push(Promise.resolve(loader.normalize(entry.deps[i], load.name))); - - return Promise.all(normalizePromises).then(function(normalizedDeps) { - - entry.normalizedDeps = normalizedDeps; - - return { - deps: entry.deps, - execute: function() { - // recursively ensure that the module and all its - // dependencies are linked (with dependency group handling) - link(load.name, loader); - - // now handle dependency execution in correct order - ensureEvaluated(load.name, [], loader); - - // remove from the registry - loader.defined[load.name] = undefined; - - // return the defined module object - return loader.newModule(entry.declarative ? entry.module.exports : entry.esModule); - } - }; - }); - }; - }); -})(); -/* - * Extension to detect ES6 and auto-load Traceur or Babel for processing - */ -(function() { - // good enough ES6 module detection regex - format detections not designed to be accurate, but to handle the 99% use case - var esmRegEx = /(^\s*|[}\);\n]\s*)(import\s+(['"]|(\*\s+as\s+)?[^"'\(\)\n;]+\s+from\s+['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/; - - var traceurRuntimeRegEx = /\$traceurRuntime\s*\./; - var babelHelpersRegEx = /babelHelpers\s*\./; - - hook('translate', function(translate) { - return function(load) { - var loader = this; - return translate.call(loader, load) - .then(function(source) { - // detect & transpile ES6 - if (load.metadata.format == 'esm' || load.metadata.format == 'es6' || !load.metadata.format && loader.transpiler !== false && source.match(esmRegEx)) { - if (load.metadata.format == 'es6') - warn.call(loader, 'Module ' + load.name + ' has metadata setting its format to "es6", which is deprecated.\nThis should be updated to "esm".'); - - load.metadata.format = 'esm'; - - if (loader.transpiler === false) { - // we accept translation to esm for builds though to enable eg rollup optimizations - if (loader.builder) - return source; - throw new TypeError('Unable to dynamically transpile ES module as SystemJS.transpiler set to false.'); - } - - // setting _loader.loadedTranspiler = false tells the next block to - // do checks for setting transpiler metadata - loader._loader.loadedTranspiler = loader._loader.loadedTranspiler || false; - if (loader.pluginLoader) - loader.pluginLoader._loader.loadedTranspiler = loader._loader.loadedTranspiler || false; - - // do transpilation - return (loader._loader.transpilerPromise || ( - loader._loader.transpilerPromise = Promise.resolve( - __global[loader.transpiler == 'typescript' ? 'ts' : loader.transpiler] || (loader.pluginLoader || loader)['import'](loader.transpiler) - ))).then(function(transpiler) { - loader._loader.loadedTranspilerRuntime = true; - - // translate hooks means this is a transpiler plugin instead of a raw implementation - if (transpiler.translate) { - // if transpiler is the same as the plugin loader, then don't run twice - if (transpiler == load.metadata.loaderModule) - return load.source; - - return Promise.resolve(transpiler.translate.call(loader, load)) - .then(function(source) { - if (load.metadata.format == 'esm' && !loader.builder && detectRegisterFormat(source)) - load.metadata.format = 'register'; - return source; - }); - } - - // legacy builder support - if (loader.builder) - load.metadata.originalSource = load.source; - - // defined in es6-module-loader/src/transpile.js - return transpile.call(loader, load) - .then(function(source) { - // clear sourceMap as transpiler embeds it - load.metadata.sourceMap = undefined; - return source; - }); - }); - } - - // skip transpiler and transpiler runtime loading when transpiler is disabled - if (loader.transpiler === false) - return source; - - // load the transpiler correctly - if (loader._loader.loadedTranspiler === false && (loader.transpiler == 'traceur' || loader.transpiler == 'typescript' || loader.transpiler == 'babel') - && load.name == loader.normalizeSync(loader.transpiler)) { - - // always load transpiler as a global - if (source.length > 100 && !load.metadata.format) { - load.metadata.format = 'global'; - - if (loader.transpiler === 'traceur') - load.metadata.exports = 'traceur'; - if (loader.transpiler === 'typescript') - load.metadata.exports = 'ts'; - } - - loader._loader.loadedTranspiler = true; - } - - // load the transpiler runtime correctly - if (loader._loader.loadedTranspilerRuntime === false) { - if (load.name == loader.normalizeSync('traceur-runtime') - || load.name == loader.normalizeSync('babel/external-helpers*')) { - if (source.length > 100) - load.metadata.format = load.metadata.format || 'global'; - - loader._loader.loadedTranspilerRuntime = true; - } - } - - // detect transpiler runtime usage to load runtimes - if ((load.metadata.format == 'register' || load.metadata.bundle) && loader._loader.loadedTranspilerRuntime !== true) { - if (!__global.$traceurRuntime && load.source.match(traceurRuntimeRegEx)) { - loader._loader.loadedTranspilerRuntime = loader._loader.loadedTranspilerRuntime || false; - return loader['import']('traceur-runtime').then(function() { - return source; - }); - } - if (!__global.babelHelpers && load.source.match(babelHelpersRegEx)) { - loader._loader.loadedTranspilerRuntime = loader._loader.loadedTranspilerRuntime || false; - return loader['import']('babel/external-helpers').then(function() { - return source; - }); - } - } - - return source; - }); - }; - }); - -})(); -/* - SystemJS Global Format - - Supports - metadata.deps - metadata.globals - metadata.exports - - Without metadata.exports, detects writes to the global object. -*/ -var __globalName = typeof self != 'undefined' ? 'self' : 'global'; - -hook('fetch', function(fetch) { - return function(load) { - if (load.metadata.exports && !load.metadata.format) - load.metadata.format = 'global'; - - // A global with exports, no globals and no deps - // can be loaded via a script tag - if (load.metadata.format == 'global' && !load.metadata.authorization - && load.metadata.exports && !load.metadata.globals - && (!load.metadata.deps || load.metadata.deps.length == 0) - && load.metadata.scriptLoad !== false) - load.metadata.scriptLoad = true; - - return fetch.call(this, load); - }; -}); - -// ideally we could support script loading for globals, but the issue with that is that -// we can't do it with AMD support side-by-side since AMD support means defining the -// global define, and global support means not definining it, yet we don't have any hook -// into the "pre-execution" phase of a script tag being loaded to handle both cases -hook('instantiate', function(instantiate) { - return function(load) { - var loader = this; - - if (!load.metadata.format) - load.metadata.format = 'global'; - - // global is a fallback module format - if (load.metadata.format == 'global' && !load.metadata.registered) { - - var entry = createEntry(); - - load.metadata.entry = entry; - - entry.deps = []; - - for (var g in load.metadata.globals) - entry.deps.push(load.metadata.globals[g]); - - entry.execute = function(require, exports, module) { - - var globals; - if (load.metadata.globals) { - globals = {}; - for (var g in load.metadata.globals) - if (load.metadata.globals[g]) - globals[g] = require(load.metadata.globals[g]); - } - - var exportName = load.metadata.exports; - - if (exportName) - load.source += '\n' + __globalName + '["' + exportName + '"] = ' + exportName + ';'; - - var retrieveGlobal = loader.get('@@global-helpers').prepareGlobal(module.id, exportName, globals); - - __exec.call(loader, load); - - return retrieveGlobal(); - } - } - return instantiate.call(this, load); - }; -}); -hook('reduceRegister_', function(reduceRegister) { - return function(load, register) { - if (register || !load.metadata.exports) - return reduceRegister.call(this, load, register); - - load.metadata.format = 'global'; - var entry = load.metadata.entry = createEntry(); - entry.deps = load.metadata.deps; - var globalValue = readMemberExpression(load.metadata.exports, __global); - entry.execute = function() { - return globalValue; - }; - }; -}); - -hookConstructor(function(constructor) { - return function() { - var loader = this; - constructor.call(loader); - - var hasOwnProperty = Object.prototype.hasOwnProperty; - - // bare minimum ignores for IE8 - var ignoredGlobalProps = ['_g', 'sessionStorage', 'localStorage', 'clipboardData', 'frames', 'frameElement', 'external', 'mozAnimationStartTime', 'webkitStorageInfo', 'webkitIndexedDB']; - - var globalSnapshot; - - function forEachGlobal(callback) { - if (Object.keys) - Object.keys(__global).forEach(callback); - else - for (var g in __global) { - if (!hasOwnProperty.call(__global, g)) - continue; - callback(g); - } - } - - function forEachGlobalValue(callback) { - forEachGlobal(function(globalName) { - if (indexOf.call(ignoredGlobalProps, globalName) != -1) - return; - try { - var value = __global[globalName]; - } - catch (e) { - ignoredGlobalProps.push(globalName); - } - callback(globalName, value); - }); - } - - loader.set('@@global-helpers', loader.newModule({ - prepareGlobal: function(moduleName, exportName, globals) { - // disable module detection - var curDefine = __global.define; - - __global.define = undefined; - __global.exports = undefined; - if (__global.module && __global.module.exports) - __global.module = undefined; - - // set globals - var oldGlobals; - if (globals) { - oldGlobals = {}; - for (var g in globals) { - oldGlobals[g] = __global[g]; - __global[g] = globals[g]; - } - } - - // store a complete copy of the global object in order to detect changes - if (!exportName) { - globalSnapshot = {}; - - forEachGlobalValue(function(name, value) { - globalSnapshot[name] = value; - }); - } - - // return function to retrieve global - return function() { - var globalValue; - - if (exportName) { - globalValue = readMemberExpression(exportName, __global); - } - else { - var singleGlobal; - var multipleExports; - var exports = {}; - - forEachGlobalValue(function(name, value) { - if (globalSnapshot[name] === value) - return; - if (typeof value == 'undefined') - return; - exports[name] = value; - - if (typeof singleGlobal != 'undefined') { - if (!multipleExports && singleGlobal !== value) - multipleExports = true; - } - else { - singleGlobal = value; - } - }); - globalValue = multipleExports ? exports : singleGlobal; - } - - // revert globals - if (oldGlobals) { - for (var g in oldGlobals) - __global[g] = oldGlobals[g]; - } - __global.define = curDefine; - - return globalValue; - }; - } - })); - }; -}); -/* - SystemJS CommonJS Format -*/ -(function() { - // CJS Module Format - // require('...') || exports[''] = ... || exports.asd = ... || module.exports = ... - var cjsExportsRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF.])(exports\s*(\[['"]|\.)|module(\.exports|\['exports'\]|\["exports"\])\s*(\[['"]|[=,\.]))/; - // RegEx adjusted from https://github.com/jbrantly/yabble/blob/master/lib/yabble.js#L339 - var cjsRequireRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF."'])require\s*\(\s*("[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*')\s*\)/g; - var commentRegEx = /(^|[^\\])(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg; - - var stringRegEx = /("[^"\\\n\r]*(\\.[^"\\\n\r]*)*"|'[^'\\\n\r]*(\\.[^'\\\n\r]*)*')/g; - - function getCJSDeps(source) { - cjsRequireRegEx.lastIndex = commentRegEx.lastIndex = stringRegEx.lastIndex = 0; - - var deps = []; - - var match; - - // track string and comment locations for unminified source - var stringLocations = [], commentLocations = []; - - function inLocation(locations, match) { - for (var i = 0; i < locations.length; i++) - if (locations[i][0] < match.index && locations[i][1] > match.index) - return true; - return false; - } - - if (source.length / source.split('\n').length < 200) { - while (match = stringRegEx.exec(source)) - stringLocations.push([match.index, match.index + match[0].length]); - - while (match = commentRegEx.exec(source)) { - // only track comments not starting in strings - if (!inLocation(stringLocations, match)) - commentLocations.push([match.index, match.index + match[0].length]); - } - } - - while (match = cjsRequireRegEx.exec(source)) { - // ensure we're not within a string or comment location - if (!inLocation(stringLocations, match) && !inLocation(commentLocations, match)) { - var dep = match[1].substr(1, match[1].length - 2); - // skip cases like require('" + file + "') - if (dep.match(/"|'/)) - continue; - // trailing slash requires are removed as they don't map mains in SystemJS - if (dep[dep.length - 1] == '/') - dep = dep.substr(0, dep.length - 1); - deps.push(dep); - } - } - - return deps; - } - - hook('instantiate', function(instantiate) { - return function(load) { - var loader = this; - if (!load.metadata.format) { - cjsExportsRegEx.lastIndex = 0; - cjsRequireRegEx.lastIndex = 0; - if (cjsRequireRegEx.exec(load.source) || cjsExportsRegEx.exec(load.source)) - load.metadata.format = 'cjs'; - } - - if (load.metadata.format == 'cjs') { - var metaDeps = load.metadata.deps; - var deps = load.metadata.cjsRequireDetection === false ? [] : getCJSDeps(load.source); - - for (var g in load.metadata.globals) - if (load.metadata.globals[g]) - deps.push(load.metadata.globals[g]); - - var entry = createEntry(); - - load.metadata.entry = entry; - - entry.deps = deps; - entry.executingRequire = true; - entry.execute = function(_require, exports, module) { - function require(name) { - if (name[name.length - 1] == '/') - name = name.substr(0, name.length - 1); - return _require.apply(this, arguments); - } - - // ensure meta deps execute first - for (var i = 0; i < metaDeps.length; i++) - require(metaDeps[i]); - - // disable AMD detection - var define = __global.define; - __global.define = undefined; - - var pathVars = loader.get('@@cjs-helpers').getPathVars(module.id); - - __global.__cjsWrapper = { - exports: exports, - args: [require, exports, module, pathVars.filename, pathVars.dirname, __global, __global] - }; - - var globals = ''; - if (load.metadata.globals) { - for (var g in load.metadata.globals) - globals += 'var ' + g + ' = require("' + load.metadata.globals[g] + '");'; - } - - load.source = "(function(require, exports, module, __filename, __dirname, global, GLOBAL) {" + globals - + load.source + "\n}).apply(__cjsWrapper.exports, __cjsWrapper.args);"; - - __exec.call(loader, load); - - __global.__cjsWrapper = undefined; - __global.define = define; - }; - } - - return instantiate.call(loader, load); - }; - }); -})(); -hookConstructor(function(constructor) { - return function() { - var loader = this; - constructor.call(loader); - - if (typeof window != 'undefined' && typeof document != 'undefined' && window.location) - var windowOrigin = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : ''); - - loader.set('@@cjs-helpers', loader.newModule({ - getPathVars: function(moduleId) { - // remove any plugin syntax - var pluginIndex = moduleId.lastIndexOf('!'); - var filename; - if (pluginIndex != -1) - filename = moduleId.substr(0, pluginIndex); - else - filename = moduleId; - - var dirname = filename.split('/'); - dirname.pop(); - dirname = dirname.join('/'); - - if (filename.substr(0, 8) == 'file:///') { - filename = filename.substr(7); - dirname = dirname.substr(7); - - // on windows remove leading '/' - if (isWindows) { - filename = filename.substr(1); - dirname = dirname.substr(1); - } - } - else if (windowOrigin && filename.substr(0, windowOrigin.length) === windowOrigin) { - filename = filename.substr(windowOrigin.length); - dirname = dirname.substr(windowOrigin.length); - } - - return { - filename: filename, - dirname: dirname - }; - } - })) - }; -});/* - * AMD Helper function module - * Separated into its own file as this is the part needed for full AMD support in SFX builds - * NB since implementations have now diverged this can be merged back with amd.js - */ -hookConstructor(function(constructor) { - return function() { - var loader = this; - constructor.call(this); - - var commentRegEx = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg; - var cjsRequirePre = "(?:^|[^$_a-zA-Z\\xA0-\\uFFFF.])"; - var cjsRequirePost = "\\s*\\(\\s*(\"([^\"]+)\"|'([^']+)')\\s*\\)"; - var fnBracketRegEx = /\(([^\)]*)\)/; - var wsRegEx = /^\s+|\s+$/g; - - var requireRegExs = {}; - - function getCJSDeps(source, requireIndex) { - - // remove comments - source = source.replace(commentRegEx, ''); - - // determine the require alias - var params = source.match(fnBracketRegEx); - var requireAlias = (params[1].split(',')[requireIndex] || 'require').replace(wsRegEx, ''); - - // find or generate the regex for this requireAlias - var requireRegEx = requireRegExs[requireAlias] || (requireRegExs[requireAlias] = new RegExp(cjsRequirePre + requireAlias + cjsRequirePost, 'g')); - - requireRegEx.lastIndex = 0; - - var deps = []; - - var match; - while (match = requireRegEx.exec(source)) - deps.push(match[2] || match[3]); - - return deps; - } - - /* - AMD-compatible require - To copy RequireJS, set window.require = window.requirejs = loader.amdRequire - */ - function require(names, callback, errback, referer) { - // in amd, first arg can be a config object... we just ignore - if (typeof names == 'object' && !(names instanceof Array)) - return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1)); - - // amd require - if (typeof names == 'string' && typeof callback == 'function') - names = [names]; - if (names instanceof Array) { - var dynamicRequires = []; - for (var i = 0; i < names.length; i++) - dynamicRequires.push(loader['import'](names[i], referer)); - Promise.all(dynamicRequires).then(function(modules) { - if (callback) - callback.apply(null, modules); - }, errback); - } - - // commonjs require - else if (typeof names == 'string') { - var module = loader.get(loader.decanonicalize(names, referer)); - if (!module) - throw new Error('Module not already loaded loading "' + names + '" from "' + referer + '".'); - return module.__useDefault ? module['default'] : module; - } - - else - throw new TypeError('Invalid require'); - } - - function define(name, deps, factory) { - if (typeof name != 'string') { - factory = deps; - deps = name; - name = null; - } - if (!(deps instanceof Array)) { - factory = deps; - deps = ['require', 'exports', 'module'].splice(0, factory.length); - } - - if (typeof factory != 'function') - factory = (function(factory) { - return function() { return factory; } - })(factory); - - // in IE8, a trailing comma becomes a trailing undefined entry - if (deps[deps.length - 1] === undefined) - deps.pop(); - - // remove system dependencies - var requireIndex, exportsIndex, moduleIndex; - - if ((requireIndex = indexOf.call(deps, 'require')) != -1) { - - deps.splice(requireIndex, 1); - - // only trace cjs requires for non-named - // named defines assume the trace has already been done - if (!name) - deps = deps.concat(getCJSDeps(factory.toString(), requireIndex)); - } - - if ((exportsIndex = indexOf.call(deps, 'exports')) != -1) - deps.splice(exportsIndex, 1); - - if ((moduleIndex = indexOf.call(deps, 'module')) != -1) - deps.splice(moduleIndex, 1); - - function execute(req, exports, module) { - var depValues = []; - for (var i = 0; i < deps.length; i++) - depValues.push(req(deps[i])); - - module.uri = module.id; - - module.config = function() {}; - - // add back in system dependencies - if (moduleIndex != -1) - depValues.splice(moduleIndex, 0, module); - - if (exportsIndex != -1) - depValues.splice(exportsIndex, 0, exports); - - if (requireIndex != -1) { - function contextualRequire(names, callback, errback) { - if (typeof names == 'string' && typeof callback != 'function') - return req(names); - return require.call(loader, names, callback, errback, module.id); - } - contextualRequire.toUrl = function(name) { - // normalize without defaultJSExtensions - var defaultJSExtension = loader.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js'; - var url = loader.decanonicalize(name, module.id); - if (defaultJSExtension && url.substr(url.length - 3, 3) == '.js') - url = url.substr(0, url.length - 3); - return url; - }; - depValues.splice(requireIndex, 0, contextualRequire); - } - - // set global require to AMD require - var curRequire = __global.require; - __global.require = require; - - var output = factory.apply(exportsIndex == -1 ? __global : exports, depValues); - - __global.require = curRequire; - - if (typeof output == 'undefined' && module) - output = module.exports; - - if (typeof output != 'undefined') - return output; - } - - var entry = createEntry(); - entry.name = name && (loader.decanonicalize || loader.normalize).call(loader, name); - entry.deps = deps; - entry.execute = execute; - - loader.pushRegister_({ - amd: true, - entry: entry - }); - } - define.amd = {}; - - // reduction function to attach defines to a load record - hook('reduceRegister_', function(reduceRegister) { - return function(load, register) { - // only handle AMD registers here - if (!register || !register.amd) - return reduceRegister.call(this, load, register); - - var curMeta = load && load.metadata; - var entry = register.entry; - - if (curMeta) - curMeta.format = 'amd'; - - // anonymous define - if (!entry.name) { - if (!curMeta) - throw new TypeError('Unexpected anonymous AMD define.'); - - // already defined anonymously -> throw - if (curMeta.entry) - throw new TypeError('Multiple defines for anonymous module ' + load.name); - - curMeta.entry = entry; - } - // named define - else { - // if we don't have any other defines, - // then let this be an anonymous define - // this is just to support single modules of the form: - // define('jquery') - // still loading anonymously - // because it is done widely enough to be useful - // as soon as there is more than one define, this gets removed though - if (curMeta) { - if (!curMeta.entry && !curMeta.bundle) - curMeta.entry = entry; - else - curMeta.entry = undefined; - - // note this is now a bundle - curMeta.bundle = true; - } - - // define the module through the register registry - if (!(entry.name in this.defined)) - this.defined[entry.name] = entry; - } - }; - }); - - // adds define as a global (potentially just temporarily) - function createDefine() { - // ensure no NodeJS environment detection - var oldModule = __global.module; - var oldExports = __global.exports; - var oldDefine = __global.define; - - __global.module = undefined; - __global.exports = undefined; - __global.define = define; - - return function() { - __global.define = oldDefine; - __global.module = oldModule; - __global.exports = oldExports; - }; - } - - loader.set('@@amd-helpers', loader.newModule({ - createDefine: createDefine, - require: require, - define: define - })); - loader.amdDefine = define; - loader.amdRequire = require; - }; -});/* - SystemJS AMD Format -*/ -(function() { - // AMD Module Format Detection RegEx - // define([.., .., ..], ...) - // define(varName); || define(function(require, exports) {}); || define({}) - var amdRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF.])define\s*\(\s*("[^"]+"\s*,\s*|'[^']+'\s*,\s*)?\s*(\[(\s*(("[^"]+"|'[^']+')\s*,|\/\/.*\r?\n|\/\*(.|\s)*?\*\/))*(\s*("[^"]+"|'[^']+')\s*,?)?(\s*(\/\/.*\r?\n|\/\*(.|\s)*?\*\/))*\s*\]|function\s*|{|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*\))/; - - hook('fetch', function(fetch) { - return function(load) { - if (load.metadata.format === 'amd' - && !load.metadata.authorization - && load.metadata.scriptLoad !== false) - load.metadata.scriptLoad = true; - // script load implies define global leak - if (load.metadata.scriptLoad && isBrowser) - this.get('@@amd-helpers').createDefine(); - return fetch.call(this, load); - }; - }); - - hook('instantiate', function(instantiate) { - return function(load) { - var loader = this; - - if (load.metadata.format == 'amd' || !load.metadata.format && load.source.match(amdRegEx)) { - load.metadata.format = 'amd'; - - if (!loader.builder && loader.execute !== false) { - var removeDefine = this.get('@@amd-helpers').createDefine(); - - try { - __exec.call(loader, load); - } - finally { - removeDefine(); - } - - if (!load.metadata.entry && !load.metadata.bundle) - throw new TypeError('AMD module ' + load.name + ' did not define'); - } - else { - load.metadata.execute = function() { - return load.metadata.builderExecute.apply(this, arguments); - }; - } - } - - return instantiate.call(loader, load); - }; - }); - -})(); -/* - SystemJS Loader Plugin Support - - Supports plugin loader syntax with "!", or via metadata.loader - - The plugin name is loaded as a module itself, and can override standard loader hooks - for the plugin resource. See the plugin section of the systemjs readme. -*/ - -(function() { - function getParentName(loader, parentName) { - // if parent is a plugin, normalize against the parent plugin argument only - if (parentName) { - var parentPluginIndex; - if (loader.pluginFirst) { - if ((parentPluginIndex = parentName.lastIndexOf('!')) != -1) - return parentName.substr(parentPluginIndex + 1); - } - else { - if ((parentPluginIndex = parentName.indexOf('!')) != -1) - return parentName.substr(0, parentPluginIndex); - } - - return parentName; - } - } - - function parsePlugin(loader, name) { - var argumentName; - var pluginName; - - var pluginIndex = name.lastIndexOf('!'); - - if (pluginIndex == -1) - return; - - if (loader.pluginFirst) { - argumentName = name.substr(pluginIndex + 1); - pluginName = name.substr(0, pluginIndex); - } - else { - argumentName = name.substr(0, pluginIndex); - pluginName = name.substr(pluginIndex + 1) || argumentName.substr(argumentName.lastIndexOf('.') + 1); - } - - return { - argument: argumentName, - plugin: pluginName - }; - } - - // put name back together after parts have been normalized - function combinePluginParts(loader, argumentName, pluginName, defaultExtension) { - if (defaultExtension && argumentName.substr(argumentName.length - 3, 3) == '.js') - argumentName = argumentName.substr(0, argumentName.length - 3); - - if (loader.pluginFirst) { - return pluginName + '!' + argumentName; - } - else { - return argumentName + '!' + pluginName; - } - } - - // note if normalize will add a default js extension - // if so, remove for backwards compat - // this is strange and sucks, but will be deprecated - function checkDefaultExtension(loader, arg) { - return loader.defaultJSExtensions && arg.substr(arg.length - 3, 3) != '.js'; - } - - function createNormalizeSync(normalizeSync) { - return function(name, parentName, isPlugin) { - var loader = this; - - parentName = getParentName(this, parentName); - var parsed = parsePlugin(loader, name); - - if (!parsed) - return normalizeSync.call(this, name, parentName, isPlugin); - - // if this is a plugin, normalize the plugin name and the argument - var argumentName = loader.normalizeSync(parsed.argument, parentName, true); - var pluginName = loader.normalizeSync(parsed.plugin, parentName, true); - return combinePluginParts(loader, argumentName, pluginName, checkDefaultExtension(loader, parsed.argument)); - }; - } - - hook('decanonicalize', createNormalizeSync); - hook('normalizeSync', createNormalizeSync); - - hook('normalize', function(normalize) { - return function(name, parentName, isPlugin) { - var loader = this; - - parentName = getParentName(this, parentName); - - var parsed = parsePlugin(loader, name); - - if (!parsed) - return normalize.call(loader, name, parentName, isPlugin); - - return Promise.all([ - loader.normalize(parsed.argument, parentName, true), - loader.normalize(parsed.plugin, parentName, true) - ]) - .then(function(normalized) { - return combinePluginParts(loader, normalized[0], normalized[1], checkDefaultExtension(loader, parsed.argument)); - }); - } - }); - - hook('locate', function(locate) { - return function(load) { - var loader = this; - - var name = load.name; - - // plugin syntax - var pluginSyntaxIndex; - if (loader.pluginFirst) { - if ((pluginSyntaxIndex = name.indexOf('!')) != -1) { - load.metadata.loader = name.substr(0, pluginSyntaxIndex); - load.name = name.substr(pluginSyntaxIndex + 1); - } - } - else { - if ((pluginSyntaxIndex = name.lastIndexOf('!')) != -1) { - load.metadata.loader = name.substr(pluginSyntaxIndex + 1); - load.name = name.substr(0, pluginSyntaxIndex); - } - } - - return locate.call(loader, load) - .then(function(address) { - var plugin = load.metadata.loader; - - if (!plugin) - return address; - - // only fetch the plugin itself if this name isn't defined - if (loader.defined && loader.defined[name]) - return address; - - var pluginLoader = loader.pluginLoader || loader; - - // load the plugin module and run standard locate - return pluginLoader['import'](plugin) - .then(function(loaderModule) { - // store the plugin module itself on the metadata - load.metadata.loaderModule = loaderModule; - - load.address = address; - if (loaderModule.locate) - return loaderModule.locate.call(loader, load); - - return address; - }); - }); - }; - }); - - hook('fetch', function(fetch) { - return function(load) { - var loader = this; - if (load.metadata.loaderModule && load.metadata.loaderModule.fetch && load.metadata.format != 'defined') { - load.metadata.scriptLoad = false; - return load.metadata.loaderModule.fetch.call(loader, load, function(load) { - return fetch.call(loader, load); - }); - } - else { - return fetch.call(loader, load); - } - }; - }); - - hook('translate', function(translate) { - return function(load) { - - /* - * Source map sanitization for load.metadata.sourceMap - * Used to set browser and build-level source maps for - * translated sources in a general way. - * - * This isn't plugin-specific, but can't go anywhere else for now - * As it is post-translate - */ - var sourceMap = load.metadata.sourceMap; - - // if an object not a JSON string do sanitizing - if (sourceMap && typeof sourceMap == 'object') { - var originalName = load.name.split('!')[0]; - - // force set the filename of the original file - sourceMap.file = originalName + '!transpiled'; - - // force set the sources list if only one source - if (!sourceMap.sources || sourceMap.sources.length == 1) - sourceMap.sources = [originalName]; - load.metadata.sourceMap = JSON.stringify(sourceMap); - } - - var loader = this; - if (load.metadata.loaderModule && load.metadata.loaderModule.translate && load.metadata.format != 'defined') { - return Promise.resolve(load.metadata.loaderModule.translate.call(loader, load)).then(function(result) { - // NB we should probably enforce a string output - if (typeof result == 'string') - load.source = result; - return translate.call(loader, load); - }); - } - else { - return translate.call(loader, load); - } - }; - }); - - hook('instantiate', function(instantiate) { - return function(load) { - var loader = this; - - if (load.metadata.loaderModule && load.metadata.loaderModule.instantiate && !loader.builder && load.metadata.format != 'defined') - return Promise.resolve(load.metadata.loaderModule.instantiate.call(loader, load)).then(function(result) { - load.metadata.entry = createEntry(); - load.metadata.entry.execute = function() { - return result; - } - load.metadata.entry.deps = load.metadata.deps; - load.metadata.format = 'defined'; - return instantiate.call(loader, load); - }); - else - return instantiate.call(loader, load); - }; - }); - -})();/* - * Conditions Extension - * - * Allows a condition module to alter the resolution of an import via syntax: - * - * import $ from 'jquery/#{browser}'; - * - * Will first load the module 'browser' via `SystemJS.import('browser')` and - * take the default export of that module. - * If the default export is not a string, an error is thrown. - * - * We then substitute the string into the require to get the conditional resolution - * enabling environment-specific variations like: - * - * import $ from 'jquery/ie' - * import $ from 'jquery/firefox' - * import $ from 'jquery/chrome' - * import $ from 'jquery/safari' - * - * It can be useful for a condition module to define multiple conditions. - * This can be done via the `|` modifier to specify an export member expression: - * - * import 'jquery/#{./browser.js|grade.version}' - * - * Where the `grade` export `version` member in the `browser.js` module is substituted. - * - * - * Boolean Conditionals - * - * For polyfill modules, that are used as imports but have no module value, - * a binary conditional allows a module not to be loaded at all if not needed: - * - * import 'es5-shim#?./conditions.js|needs-es5shim' - * - * These conditions can also be negated via: - * - * import 'es5-shim#?~./conditions.js|es6' - * - */ - - function parseCondition(condition) { - var conditionExport, conditionModule, negation; - - var negation = condition[0] == '~'; - var conditionExportIndex = condition.lastIndexOf('|'); - if (conditionExportIndex != -1) { - conditionExport = condition.substr(conditionExportIndex + 1); - conditionModule = condition.substr(negation, conditionExportIndex - negation) || '@system-env'; - } - else { - conditionExport = null; - conditionModule = condition.substr(negation); - } - - return { - module: conditionModule, - prop: conditionExport, - negate: negation - }; - } - - function serializeCondition(conditionObj) { - return (conditionObj.negate ? '~' : '') + conditionObj.module + (conditionObj.prop ? '|' + conditionObj.prop : ''); - } - - function resolveCondition(conditionObj, parentName, bool) { - return this['import'](conditionObj.module, parentName) - .then(function(m) { - if (conditionObj.prop) - m = readMemberExpression(conditionObj.prop, m); - else if (typeof m == 'object' && m + '' == 'Module') - m = m['default']; - - return conditionObj.negate ? !m : m; - }); - } - - var interpolationRegEx = /#\{[^\}]+\}/; - function interpolateConditional(name, parentName) { - // first we normalize the conditional - var conditionalMatch = name.match(interpolationRegEx); - - if (!conditionalMatch) - return Promise.resolve(name); - - var conditionObj = parseCondition(conditionalMatch[0].substr(2, conditionalMatch[0].length - 3)); - - // in builds, return normalized conditional - if (this.builder) - return this['normalize'](conditionObj.module, parentName) - .then(function(conditionModule) { - conditionObj.module = conditionModule; - return name.replace(interpolationRegEx, '#{' + serializeCondition(conditionObj) + '}'); - }); - - return resolveCondition.call(this, conditionObj, parentName, false) - .then(function(conditionValue) { - if (typeof conditionValue !== 'string') - throw new TypeError('The condition value for ' + name + ' doesn\'t resolve to a string.'); - - if (conditionValue.indexOf('/') != -1) - throw new TypeError('Unabled to interpolate conditional ' + name + (parentName ? ' in ' + parentName : '') + '\n\tThe condition value ' + conditionValue + ' cannot contain a "/" separator.'); - - return name.replace(interpolationRegEx, conditionValue); - }); - } - - function booleanConditional(name, parentName) { - // first we normalize the conditional - var booleanIndex = name.lastIndexOf('#?'); - - if (booleanIndex == -1) - return Promise.resolve(name); - - var conditionObj = parseCondition(name.substr(booleanIndex + 2)); - - // in builds, return normalized conditional - if (this.builder) - return this['normalize'](conditionObj.module, parentName) - .then(function(conditionModule) { - conditionObj.module = conditionModule; - return name.substr(0, booleanIndex) + '#?' + serializeCondition(conditionObj); - }); - - return resolveCondition.call(this, conditionObj, parentName, true) - .then(function(conditionValue) { - return conditionValue ? name.substr(0, booleanIndex) : '@empty'; - }); - } - - // normalizeSync does not parse conditionals at all although it could - hook('normalize', function(normalize) { - return function(name, parentName, parentAddress) { - var loader = this; - return booleanConditional.call(loader, name, parentName) - .then(function(name) { - return normalize.call(loader, name, parentName, parentAddress); - }) - .then(function(normalized) { - return interpolateConditional.call(loader, normalized, parentName); - }); - }; - }); -/* - * Alias Extension - * - * Allows a module to be a plain copy of another module by module name - * - * SystemJS.meta['mybootstrapalias'] = { alias: 'bootstrap' }; - * - */ -(function() { - // aliases - hook('fetch', function(fetch) { - return function(load) { - var alias = load.metadata.alias; - var aliasDeps = load.metadata.deps || []; - if (alias) { - load.metadata.format = 'defined'; - var entry = createEntry(); - this.defined[load.name] = entry; - entry.declarative = true; - entry.deps = aliasDeps.concat([alias]); - entry.declare = function(_export) { - return { - setters: [function(module) { - for (var p in module) - _export(p, module[p]); - if (module.__useDefault) - entry.module.exports.__useDefault = true; - }], - execute: function() {} - }; - }; - return ''; - } - - return fetch.call(this, load); - }; - }); -})();/* - * Meta Extension - * - * Sets default metadata on a load record (load.metadata) from - * loader.metadata via SystemJS.meta function. - * - * - * Also provides an inline meta syntax for module meta in source. - * - * Eg: - * - * loader.meta({ - * 'my/module': { deps: ['jquery'] } - * 'my/*': { format: 'amd' } - * }); - * - * Which in turn populates loader.metadata. - * - * load.metadata.deps and load.metadata.format will then be set - * for 'my/module' - * - * The same meta could be set with a my/module.js file containing: - * - * my/module.js - * "format amd"; - * "deps[] jquery"; - * "globals.some value" - * console.log('this is my/module'); - * - * Configuration meta always takes preference to inline meta. - * - * Multiple matches in wildcards are supported and ammend the meta. - * - * - * The benefits of the function form is that paths are URL-normalized - * supporting say - * - * loader.meta({ './app': { format: 'cjs' } }); - * - * Instead of needing to set against the absolute URL (https://site.com/app.js) - * - */ - -(function() { - - hookConstructor(function(constructor) { - return function() { - this.meta = {}; - constructor.call(this); - }; - }); - - hook('locate', function(locate) { - return function(load) { - var meta = this.meta; - var name = load.name; - - // NB for perf, maybe introduce a fast-path wildcard lookup cache here - // which is checked first - - // apply wildcard metas - var bestDepth = 0; - var wildcardIndex; - for (var module in meta) { - wildcardIndex = module.indexOf('*'); - if (wildcardIndex === -1) - continue; - if (module.substr(0, wildcardIndex) === name.substr(0, wildcardIndex) - && module.substr(wildcardIndex + 1) === name.substr(name.length - module.length + wildcardIndex + 1)) { - var depth = module.split('/').length; - if (depth > bestDepth) - bestDepth = depth; - extendMeta(load.metadata, meta[module], bestDepth != depth); - } - } - - // apply exact meta - if (meta[name]) - extendMeta(load.metadata, meta[name]); - - return locate.call(this, load); - }; - }); - - // detect any meta header syntax - // only set if not already set - var metaRegEx = /^(\s*\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\s*\/\/[^\n]*|\s*"[^"]+"\s*;?|\s*'[^']+'\s*;?)+/; - var metaPartRegEx = /\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\/\/[^\n]*|"[^"]+"\s*;?|'[^']+'\s*;?/g; - - function setMetaProperty(target, p, value) { - var pParts = p.split('.'); - var curPart; - while (pParts.length > 1) { - curPart = pParts.shift(); - target = target[curPart] = target[curPart] || {}; - } - curPart = pParts.shift(); - if (!(curPart in target)) - target[curPart] = value; - } - - hook('translate', function(translate) { - return function(load) { - // NB meta will be post-translate pending transpiler conversion to plugins - var meta = load.source.match(metaRegEx); - if (meta) { - var metaParts = meta[0].match(metaPartRegEx); - - for (var i = 0; i < metaParts.length; i++) { - var curPart = metaParts[i]; - var len = curPart.length; - - var firstChar = curPart.substr(0, 1); - if (curPart.substr(len - 1, 1) == ';') - len--; - - if (firstChar != '"' && firstChar != "'") - continue; - - var metaString = curPart.substr(1, curPart.length - 3); - var metaName = metaString.substr(0, metaString.indexOf(' ')); - - if (metaName) { - var metaValue = metaString.substr(metaName.length + 1, metaString.length - metaName.length - 1); - - if (metaName.substr(metaName.length - 2, 2) == '[]') { - metaName = metaName.substr(0, metaName.length - 2); - load.metadata[metaName] = load.metadata[metaName] || []; - load.metadata[metaName].push(metaValue); - } - else if (load.metadata[metaName] instanceof Array) { - // temporary backwards compat for previous "deps" syntax - warn.call(this, 'Module ' + load.name + ' contains deprecated "deps ' + metaValue + '" meta syntax.\nThis should be updated to "deps[] ' + metaValue + '" for pushing to array meta.'); - load.metadata[metaName].push(metaValue); - } - else { - setMetaProperty(load.metadata, metaName, metaValue); - } - } - else { - load.metadata[metaString] = true; - } - } - } - - return translate.call(this, load); - }; - }); -})(); -/* - System bundles - - Allows a bundle module to be specified which will be dynamically - loaded before trying to load a given module. - - For example: - SystemJS.bundles['mybundle'] = ['jquery', 'bootstrap/js/bootstrap'] - - Will result in a load to "mybundle" whenever a load to "jquery" - or "bootstrap/js/bootstrap" is made. - - In this way, the bundle becomes the request that provides the module -*/ - -(function() { - // bundles support (just like RequireJS) - // bundle name is module name of bundle itself - // bundle is array of modules defined by the bundle - // when a module in the bundle is requested, the bundle is loaded instead - // of the form SystemJS.bundles['mybundle'] = ['jquery', 'bootstrap/js/bootstrap'] - hookConstructor(function(constructor) { - return function() { - constructor.call(this); - this.bundles = {}; - this._loader.loadedBundles = {}; - }; - }); - - // assign bundle metadata for bundle loads - hook('locate', function(locate) { - return function(load) { - var loader = this; - - if (!(load.name in loader.defined)) - for (var b in loader.bundles) { - if (loader.bundles[b].indexOf(load.name) != -1) - return loader['import'](b) - .then(function() { - return locate.call(loader, load); - }); - } - - return locate.call(loader, load); - }; - }); -})(); -/* - * Dependency Tree Cache - * - * Allows a build to pre-populate a dependency trace tree on the loader of - * the expected dependency tree, to be loaded upfront when requesting the - * module, avoinding the n round trips latency of module loading, where - * n is the dependency tree depth. - * - * eg: - * SystemJS.depCache = { - * 'app': ['normalized', 'deps'], - * 'normalized': ['another'], - * 'deps': ['tree'] - * }; - * - * SystemJS.import('app') - * // simultaneously starts loading all of: - * // 'normalized', 'deps', 'another', 'tree' - * // before "app" source is even loaded - * - */ - -(function() { - hookConstructor(function(constructor) { - return function() { - constructor.call(this); - this.depCache = {}; - } - }); - - hook('locate', function(locate) { - return function(load) { - var loader = this; - // load direct deps, in turn will pick up their trace trees - var deps = loader.depCache[load.name]; - if (deps) - for (var i = 0; i < deps.length; i++) - loader['import'](deps[i], load.name); - - return locate.call(loader, load); - }; - }); -})(); - -System = new SystemJSLoader(); - -__global.SystemJS = System; -System.version = '0.19.13 Standard'; - // -- exporting -- - - if (typeof exports === 'object') - module.exports = Loader; - - __global.Reflect = __global.Reflect || {}; - __global.Reflect.Loader = __global.Reflect.Loader || Loader; - __global.Reflect.global = __global.Reflect.global || __global; - __global.LoaderPolyfill = Loader; - - if (!System) { - System = new SystemLoader(); - System.constructor = SystemLoader; - } - - if (typeof exports === 'object') - module.exports = System; - - __global.System = System; - -})(typeof self != 'undefined' ? self : global);} - -// auto-load Promise and URL polyfills if needed in the browser -try { - var hasURL = typeof URLPolyfill != 'undefined' || new URL('test:///').protocol == 'test:'; -} -catch(e) {} - -if (typeof Promise === 'undefined' || !hasURL) { - // document.write - if (typeof document !== 'undefined') { - var scripts = document.getElementsByTagName('script'); - $__curScript = scripts[scripts.length - 1]; - var curPath = $__curScript.src; - var basePath = curPath.substr(0, curPath.lastIndexOf('/') + 1); - window.systemJSBootstrap = bootstrap; - document.write( - '<' + 'script type="text/javascript" src="' + basePath + 'system-polyfills.js">' + '<' + '/script>' - ); - } - // importScripts - else if (typeof importScripts !== 'undefined') { - var basePath = ''; - try { - throw new Error('_'); - } catch (e) { - e.stack.replace(/(?:at|@).*(http.+):[\d]+:[\d]+/, function(m, url) { - basePath = url.replace(/\/[^\/]*$/, '/'); - }); - } - importScripts(basePath + 'system-polyfills.js'); - bootstrap(); - } - else { - bootstrap(); - } -} -else { - bootstrap(); -} - - -})(); -\ No newline at end of file diff --git a/extension/lib/wallet/wallet.ts b/extension/lib/wallet/wallet.ts @@ -89,7 +89,6 @@ class CoinPaySig { interface ConfirmPayRequest { - merchantPageUrl: string; offer: Offer; } @@ -107,8 +106,6 @@ interface Offer { contract: Contract; sig: string; H_contract: string; - pay_url: string; - exec_url: string; } interface Contract { @@ -140,7 +137,6 @@ interface CoinPaySig_interface { interface Transaction { contractHash: string; contract: any; - payUrl: string; payReq: any; } @@ -153,8 +149,8 @@ interface Reserve { interface PaymentResponse { - payUrl: string; payReq: any; + contract: Contract; } @@ -370,7 +366,6 @@ export class Wallet { executePay(offer: Offer, payCoinInfo: PayCoinInfo, - merchantBaseUrl: string, chosenMint: string): Promise<void> { let payReq = {}; payReq["H_wire"] = offer.contract.H_wire; @@ -380,15 +375,12 @@ export class Wallet { payReq["mint"] = URI(chosenMint).href(); payReq["coins"] = payCoinInfo.map((x) => x.sig); payReq["timestamp"] = offer.contract.timestamp; - let payUrl = URI(offer.pay_url).absoluteTo(merchantBaseUrl); let t: Transaction = { contractHash: offer.H_contract, contract: offer.contract, - payUrl: payUrl.href(), - payReq: payReq + payReq: payReq, }; - let historyEntry = { type: "pay", timestamp: (new Date).getTime(), @@ -406,7 +398,7 @@ export class Wallet { .finish(); } - confirmPay(offer: Offer, merchantPageUrl: string): Promise<any> { + confirmPay(offer: Offer): Promise<any> { return Promise.resolve().then(() => { return this.getPossibleMintCoins(offer.contract.amount, offer.contract.max_fee, @@ -417,7 +409,7 @@ export class Wallet { } let mintUrl = Object.keys(mcs)[0]; let ds = Wallet.signDeposit(offer, mcs[mintUrl]); - return this.executePay(offer, ds, merchantPageUrl, mintUrl); + return this.executePay(offer, ds, mintUrl); }); } @@ -430,15 +422,14 @@ export class Wallet { throw Error("contract not found"); } let resp: PaymentResponse = { - payUrl: t.payUrl, - payReq: t.payReq + payReq: t.payReq, + contract: t.contract, }; return resp; }); }); } - initReserve(reserveRecord) { this.updateMintFromUrl(reserveRecord.mint_base_url) .then((mint) => @@ -478,55 +469,55 @@ export class Wallet { } return this.http.postForm(req.post_url, form) - .then((hresp) => { - // TODO: look at response status code and handle errors appropriately - let json = JSON.parse(hresp.responseText); - if (!json) { - return { - success: false - }; - } - let resp: ConfirmReserveResponse = { - success: undefined, - backlink: json.redirect_url, - }; - let reserveRecord = { - reserve_pub: reservePub.toCrock(), - reserve_priv: reservePriv.toCrock(), - mint_base_url: mintBaseUrl, - created: now, - last_query: null, - current_amount: null, - // XXX: set to actual amount - requested_amount: null - }; - - if (hresp.status != 200) { - resp.success = false; - return resp; - } - - let historyEntry = { - type: "create-reserve", - timestamp: now, - detail: { - requestedAmount, - reservePub: reserveRecord.reserve_pub, - } - }; - - resp.success = true; - - return Query(this.db) - .put("reserves", reserveRecord) - .put("history", historyEntry) - .finish() - .then(() => { - // Do this in the background - this.initReserve(reserveRecord); - return resp; - }); - }); + .then((hresp) => { + // TODO: look at response status code and handle errors appropriately + let json = JSON.parse(hresp.responseText); + if (!json) { + return { + success: false + }; + } + let resp: ConfirmReserveResponse = { + success: undefined, + backlink: json.redirect_url, + }; + let reserveRecord = { + reserve_pub: reservePub.toCrock(), + reserve_priv: reservePriv.toCrock(), + mint_base_url: mintBaseUrl, + created: now, + last_query: null, + current_amount: null, + // XXX: set to actual amount + requested_amount: null + }; + + if (hresp.status != 200) { + resp.success = false; + return resp; + } + + let historyEntry = { + type: "create-reserve", + timestamp: now, + detail: { + requestedAmount, + reservePub: reserveRecord.reserve_pub, + } + }; + + resp.success = true; + + return Query(this.db) + .put("reserves", reserveRecord) + .put("history", historyEntry) + .finish() + .then(() => { + // Do this in the background + this.initReserve(reserveRecord); + return resp; + }); + }); } @@ -652,6 +643,7 @@ export class Wallet { }); } + withdraw(denom, reserve): Promise<void> { return this.withdrawPrepare(denom, reserve) .then((pc) => this.withdrawExecute(pc)) @@ -741,6 +733,7 @@ export class Wallet { }); } + /** * Update or add mint DB entry by fetching the /keys information. * Optionally link the reserve entry to the new or existing @@ -782,11 +775,13 @@ export class Wallet { .reduce(collectBalances, {}); } + getHistory() { function collect(x, acc) { acc.push(x); return acc; } + return Query(this.db) .iter("history", {indexName: "timestamp"}) .reduce(collect, []) diff --git a/extension/lib/wallet/wxmessaging.js b/extension/lib/wallet/wxmessaging.js @@ -81,8 +81,8 @@ System.register(["./wallet", "./db", "./http"], function(exports_1) { .then(function (r) { sendResponse({ success: true, - payUrl: r.payUrl, - payReq: r.payReq + payReq: r.payReq, + contract: r.contract, }); }) .catch(function (e) { @@ -105,6 +105,9 @@ System.register(["./wallet", "./db", "./http"], function(exports_1) { }); return true; }, + _a["error-fatal"] = function (db, detail, sendResponse) { + console.log("fatal error from page", detail.url); + }, _a ); var _a; diff --git a/extension/lib/wallet/wxmessaging.ts b/extension/lib/wallet/wxmessaging.ts @@ -98,8 +98,8 @@ function makeHandlers(wallet) { .then((r) => { sendResponse({ success: true, - payUrl: r.payUrl, - payReq: r.payReq + payReq: r.payReq, + contract: r.contract, }); }) .catch((e) => { @@ -113,14 +113,17 @@ function makeHandlers(wallet) { ["get-history"]: function(db, detail, sendResponse) { // TODO: limit history length wallet.getHistory() - .then((h) => { - sendResponse(h); - }) - .catch((e) => { - console.error("exception during 'get-history'"); - console.error(e.stack); - }); + .then((h) => { + sendResponse(h); + }) + .catch((e) => { + console.error("exception during 'get-history'"); + console.error(e.stack); + }); return true; + }, + ["error-fatal"]: function(db, detail, sendResponse) { + console.log("fatal error from page", detail.url); } }; } diff --git a/extension/lib/web-common.ts b/extension/lib/web-common.ts @@ -0,0 +1,21 @@ +/* + This file is part of TALER + (C) 2016 GNUnet e.V. + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, If not, see <http://www.gnu.org/licenses/> + */ + +export function substituteFulfillmentUrl(url: string, offer) { + url = url.replace("${H_contract}", offer.H_contract); + url = url.replace("${$}", "$"); + return url; +} +\ No newline at end of file diff --git a/extension/manifest.json b/extension/manifest.json @@ -26,8 +26,8 @@ { "matches": ["*://*/*"], "js": [ - "lib/vendor/system.src.js", "lib/vendor/URI.js", + "lib/vendor/system-csp-production.src.js", "content_scripts/notify.js" ], "run_at": "document_start" @@ -44,12 +44,10 @@ "lib/vendor/URI.js", "lib/vendor/handlebars-v4.0.5.js", "lib/emscripten/libwrapper.js", - "lib/vendor/system.src.js", + "lib/vendor/system-csp-production.src.js", "background/main.js" ] }, - - "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'", - + "minimum_chrome_version": "47.0.2526" } diff --git a/extension/pages/confirm-contract.html b/extension/pages/confirm-contract.html @@ -4,17 +4,14 @@ <head> <title>Taler Wallet: Confirm Reserve Creation</title> <script src="../lib/vendor/URI.js"></script> - <script src="../lib/vendor/handlebars-v4.0.5.js"></script> - <script src="../lib/commonHelpers.js"></script> - <script src="confirm-contract.js"></script> + <script src="../lib/vendor/mithril.js"></script> + <script src="../lib/i18n.js"></script> + <script src="../lib/vendor/lodash.core.min.js"></script> + <script src="../lib/vendor/system-csp-production.src.js"></script> + <script src="../lib/module-trampoline.js"></script> <link rel="stylesheet" type="text/css" href="../style/wallet.css"> <script id="contract-template" type="text/x-handlebars-template"> - Hello, this is the wallet. The merchant "{{merchant.name}}" - wants to enter a contract over {{prettyAmount amount}} - with you. - - <p /> Your contract includes these products: <ul> @@ -41,15 +38,7 @@ </aside> <section id="main"> - - <article id="contract"> - <div id="render-contract"></div> - <button id="confirm-pay">Confirm Payment</button> - <div id="confirm-warning"></div> - </article> - - <article id="status"></article> - + <article id="contract"></article> </section> </body> diff --git a/extension/pages/confirm-contract.js b/extension/pages/confirm-contract.js @@ -13,47 +13,55 @@ You should have received a copy of the GNU General Public License along with TALER; see the file COPYING. If not, If not, see <http://www.gnu.org/licenses/> */ -/// <reference path="../lib/decl/handlebars/handlebars.d.ts" /> -"use strict"; -var url = URI(document.location.href); -var query = URI.parseQuery(url.query()); -var $_ = function (x) { return document.getElementById(x); }; -function renderContract(contract) { - var showAmount = document.getElementById("show-amount"); - $_('merchant-name').innerText = contract.merchant.name; -} -function clone(obj) { - // This is faster than it looks ... - return JSON.parse(JSON.stringify(obj)); -} -Handlebars.registerHelper('prettyAmount', function (amount) { - var v = amount.value + amount.fraction / 10e6; - return v.toFixed(2) + " " + amount.currency; -}); -document.addEventListener("DOMContentLoaded", function (e) { - var offer = JSON.parse(query.offer); - console.dir(offer); - var source = $_("contract-template").innerHTML; - var template = Handlebars.compile(source); - $_("render-contract").innerHTML = template(offer.contract); - document.getElementById("confirm-pay").addEventListener("click", function (e) { - console.log("Query:", JSON.stringify(query)); - var d = { - offer: JSON.parse(query.offer), - merchantPageUrl: query.merchantPageUrl - }; - chrome.runtime.sendMessage({ type: 'confirm-pay', detail: d }, function (resp) { - if (!resp.success) { - var source_1 = $_("error-template").innerHTML; - var template_1 = Handlebars.compile(source_1); - $_("status").innerHTML = template_1(resp); - return; +System.register(["../lib/web-common"], function(exports_1) { + /// <reference path="../lib/decl/handlebars/handlebars.d.ts" /> + "use strict"; + var web_common_1; + function prettyAmount(amount) { + var v = amount.value + amount.fraction / 1e6; + return v.toFixed(2) + " " + amount.currency; + } + function main() { + var url = URI(document.location.href); + var query = URI.parseQuery(url.query()); + var offer = JSON.parse(query.offer); + console.dir(offer); + var contract = offer.contract; + var Contract = { + view: function (ctrl) { + return [ + m("p", (_a = ["Hello, this is the wallet. The merchant \"", "\"\n wants to enter a contract over ", "\n with you."], _a.raw = ["Hello, this is the wallet. The merchant \"", "\"\n wants to enter a contract over ", "\n with you."], i18n(_a, contract.merchant.name, prettyAmount(contract.amount)))), + m("p", (_b = ["The contract contains the following products:"], _b.raw = ["The contract contains the following products:"], i18n(_b))), + m('ul', _.map(contract.products, function (p) { return m("li", p.description + ": " + prettyAmount(p.price)); })), + m("button", { onclick: doPayment }, (_c = ["Confirm Payment"], _c.raw = ["Confirm Payment"], i18n(_c))) + ]; + var _a, _b, _c; } - document.location.href = URI(d.offer.exec_url) - .absoluteTo(query.merchantPageUrl) - .addQuery({ H_contract: d.offer.H_contract }) - .href(); - }); - }); + }; + m.mount(document.getElementById("contract"), Contract); + function doPayment() { + var d = { + offer: offer + }; + chrome.runtime.sendMessage({ type: 'confirm-pay', detail: d }, function (resp) { + if (!resp.success) { + console.log("confirm-pay error", JSON.stringify(resp)); + return; + } + var c = d.offer.contract; + console.log("contract", c); + document.location.href = web_common_1.substituteFulfillmentUrl(c.fulfillment_url, offer); + }); + } + } + exports_1("main", main); + return { + setters:[ + function (web_common_1_1) { + web_common_1 = web_common_1_1; + }], + execute: function() { + } + } }); //# sourceMappingURL=confirm-contract.js.map \ No newline at end of file diff --git a/extension/pages/confirm-contract.tsx b/extension/pages/confirm-contract.tsx @@ -17,55 +17,56 @@ /// <reference path="../lib/decl/handlebars/handlebars.d.ts" /> "use strict"; -let url = URI(document.location.href); -let query: any = URI.parseQuery(url.query()); +import {substituteFulfillmentUrl} from "../lib/web-common"; -let $_ = (x) => document.getElementById(x); +declare var m: any; -function renderContract(contract) { - let showAmount = document.getElementById("show-amount"); - $_('merchant-name').innerText = contract.merchant.name; +function prettyAmount(amount) { + let v = amount.value + amount.fraction / 1e6; + return `${v.toFixed(2)} ${amount.currency}`; } -function clone(obj) { - // This is faster than it looks ... - return JSON.parse(JSON.stringify(obj)); -} - - -Handlebars.registerHelper('prettyAmount', function(amount) { - let v = amount.value + amount.fraction / 10e6; - return v.toFixed(2) + " " + amount.currency; -}); - -document.addEventListener("DOMContentLoaded", (e) => { +export function main() { + let url = URI(document.location.href); + let query: any = URI.parseQuery(url.query()); let offer = JSON.parse(query.offer); console.dir(offer); - - let source = $_("contract-template").innerHTML; - let template = Handlebars.compile(source); - $_("render-contract").innerHTML = template(offer.contract); - - document.getElementById("confirm-pay").addEventListener("click", (e) => { - console.log("Query:", JSON.stringify(query)); + let contract = offer.contract; + + var Contract = { + view(ctrl) { + return [ + m("p", + i18n`Hello, this is the wallet. The merchant "${contract.merchant.name}" + wants to enter a contract over ${prettyAmount(contract.amount)} + with you.`), + m("p", + i18n`The contract contains the following products:`), + m('ul', + _.map(contract.products, + (p: any) => m("li", + `${p.description}: ${prettyAmount(p.price)}`))), + m("button", {onclick: doPayment}, i18n`Confirm Payment`) + ]; + } + }; + + m.mount(document.getElementById("contract"), Contract); + + + function doPayment() { let d = { - offer: JSON.parse(query.offer), - merchantPageUrl: query.merchantPageUrl + offer }; - chrome.runtime.sendMessage({type:'confirm-pay', detail: d}, (resp) => { + chrome.runtime.sendMessage({type: 'confirm-pay', detail: d}, (resp) => { if (!resp.success) { - let source = $_("error-template").innerHTML; - let template = Handlebars.compile(source); - $_("status").innerHTML = template(resp); + console.log("confirm-pay error", JSON.stringify(resp)); return; } - document.location.href = URI(d.offer.exec_url) - .absoluteTo(query.merchantPageUrl) - .addQuery({H_contract: d.offer.H_contract}) - .href(); + let c = d.offer.contract; + console.log("contract", c); + document.location.href = substituteFulfillmentUrl(c.fulfillment_url, offer); }); - }); -}); - - + } +} diff --git a/extension/pages/confirm-create-reserve.html b/extension/pages/confirm-create-reserve.html @@ -4,8 +4,8 @@ <head> <title>Taler Wallet: Select Taler Provider</title> <script src="../lib/vendor/URI.js"></script> - <script src="../lib/polyfill-react.js"></script> - <script src="confirm-create-reserve.js"></script> + <script src="../lib/vendor/system-csp-production.src.js"></script> + <script src="../lib/module-trampoline.js"></script> <link rel="stylesheet" type="text/css" href="../style/wallet.css"> </head> diff --git a/extension/pages/confirm-create-reserve.js b/extension/pages/confirm-create-reserve.js @@ -1,6 +1,6 @@ /* This file is part of TALER - (C) 2015 GNUnet e.V. + (C) 2015-2016 GNUnet e.V. TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -13,27 +13,26 @@ You should have received a copy of the GNU General Public License along with TALER; see the file COPYING. If not, If not, see <http://www.gnu.org/licenses/> */ -"use strict"; -var ConfirmCreateReserve; -(function (ConfirmCreateReserve) { - var url = URI(document.location.href); - var query = URI.parseQuery(url.query()); - function updateAmount() { - var showAmount = document.getElementById("show-amount"); - console.log("Query is " + JSON.stringify(query)); - var s = query.amount_str; - if (!s) { - document.body.innerHTML = "Oops, something went wrong."; - return; +System.register([], function(exports_1) { + "use strict"; + function main() { + function updateAmount() { + var showAmount = document.getElementById("show-amount"); + console.log("Query is " + JSON.stringify(query)); + var s = query.amount_str; + if (!s) { + document.body.innerHTML = "Oops, something went wrong."; + return; + } + showAmount.textContent = s; } - showAmount.textContent = s; - } - document.addEventListener("DOMContentLoaded", function (e) { + var url = URI(document.location.href); + var query = URI.parseQuery(url.query()); updateAmount(); document.getElementById("confirm").addEventListener("click", function (e) { var d = Object.assign({}, query); d.mint = document.getElementById('mint-url').value; - chrome.runtime.sendMessage({ type: 'confirm-reserve', detail: d }, function (resp) { + var cb = function (resp) { if (resp.success === true) { document.location.href = resp.backlink; } @@ -41,8 +40,15 @@ var ConfirmCreateReserve; document.body.innerHTML = "Oops, something went wrong. It looks like the bank could not\n transfer funds to the mint. Please go back to your bank's website\n to check what happened."; } - }); + }; + chrome.runtime.sendMessage({ type: 'confirm-reserve', detail: d }, cb); }); - }); -})(ConfirmCreateReserve || (ConfirmCreateReserve = {})); + } + exports_1("main", main); + return { + setters:[], + execute: function() { + } + } +}); //# sourceMappingURL=confirm-create-reserve.js.map \ No newline at end of file diff --git a/extension/pages/confirm-create-reserve.tsx b/extension/pages/confirm-create-reserve.tsx @@ -1,6 +1,6 @@ /* This file is part of TALER - (C) 2015 GNUnet e.V. + (C) 2015-2016 GNUnet e.V. TALER is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -16,11 +16,8 @@ "use strict"; -namespace ConfirmCreateReserve { - - let url = URI(document.location.href); - let query: any = URI.parseQuery(url.query()); +export function main() { function updateAmount() { let showAmount = document.getElementById("show-amount"); console.log("Query is " + JSON.stringify(query)); @@ -32,26 +29,25 @@ namespace ConfirmCreateReserve { showAmount.textContent = s; } + let url = URI(document.location.href); + let query: any = URI.parseQuery(url.query()); + + updateAmount(); - document.addEventListener("DOMContentLoaded", (e) => { - updateAmount(); + document.getElementById("confirm").addEventListener("click", (e) => { + let d = Object.assign({}, query); + d.mint = (document.getElementById('mint-url') as HTMLInputElement).value; - document.getElementById("confirm").addEventListener("click", (e) => { - let d = Object.assign({}, query); - d.mint = (document.getElementById('mint-url') as HTMLInputElement).value; - chrome.runtime.sendMessage({type:'confirm-reserve', detail: d}, - (resp) => { - if (resp.success === true) { - document.location.href = resp.backlink; - } else { - document.body.innerHTML = - `Oops, something went wrong. It looks like the bank could not + const cb = (resp) => { + if (resp.success === true) { + document.location.href = resp.backlink; + } else { + document.body.innerHTML = + `Oops, something went wrong. It looks like the bank could not transfer funds to the mint. Please go back to your bank's website to check what happened.`; - } - }); - - }); + } + }; + chrome.runtime.sendMessage({type: 'confirm-reserve', detail: d}, cb); }); - } \ No newline at end of file diff --git a/extension/popup/popup.html b/extension/popup/popup.html @@ -6,7 +6,8 @@ <script src="../lib/vendor/mithril.js"></script> <script src="../lib/i18n.js"></script> <script src="../lib/vendor/lodash.core.min.js"></script> - <script src="popup.js"></script> + <script src="../lib/vendor/system-csp-production.src.js"></script> + <script src="../lib/module-trampoline.js"></script> </head> <body> <div id="nav"></div> diff --git a/extension/popup/popup.tsx b/extension/popup/popup.tsx @@ -20,11 +20,12 @@ "use strict"; - declare var m: any; declare var i18n: any; -document.addEventListener("DOMContentLoaded", function(event) { + +export function main() { + console.log("popup main"); m.route.mode = "hash"; m.route(document.getElementById("content"), "/balance", { "/balance": WalletBalance, @@ -32,7 +33,9 @@ document.addEventListener("DOMContentLoaded", function(event) { "/debug": WalletDebug, }); m.mount(document.getElementById("nav"), WalletNavBar); -}); +} + +console.log("this is popup"); function makeTab(target, name) { @@ -84,7 +87,9 @@ var WalletBalance = { if (listing.length > 0) { return listing; } - let link = m("a[href=https://demo.taler.net]", {config: openInExtension}, i18n`free KUDOS`); + let link = m("a[href=https://demo.taler.net]", + {config: openInExtension}, + i18n`free KUDOS`); return i18n.parts`You have no balance to show. Want to get some ${link}?`; } }; @@ -102,7 +107,7 @@ function formatAmount(amount) { } function abbrevKey(s: string) { - return m("span.abbrev", {title: s}, (s.slice(0,5) + "..")) + return m("span.abbrev", {title: s}, (s.slice(0, 5) + "..")) } @@ -112,7 +117,8 @@ function formatHistoryItem(historyItem) { switch (historyItem.type) { case "create-reserve": return m("p", - i18n.parts`Created reserve (${abbrevKey(d.reservePub)}) of ${formatAmount(d.requestedAmount)} at ${formatTimestamp( + i18n.parts`Created reserve (${abbrevKey(d.reservePub)}) of ${formatAmount( + d.requestedAmount)} at ${formatTimestamp( t)}`); case "withdraw": return m("p", @@ -155,17 +161,20 @@ var WalletHistory = { }; +function reload() { + try { + chrome.runtime.reload(); + window.close(); + } catch (e) { + // Functionality missing in firefox, ignore! + } +} + function confirmReset() { if (confirm("Do you want to IRREVOCABLY DESTROY everything inside your" + " wallet and LOSE ALL YOUR COINS?")) { chrome.runtime.sendMessage({type: "reset"}); window.close(); - try { - chrome.runtime.reload(); - } catch (e) { - // Functionality missing in firefox, ignore! - } - } } @@ -173,15 +182,25 @@ function confirmReset() { var WalletDebug = { view() { return [ - m("button", {onclick: openWalletAsTab}, "wallet tab"), - m("button", {onclick: confirmReset}, "reset") + m("button", + {onclick: openExtensionPage("popup/popup.html")}, + "wallet tab"), + m("button", + {onclick: openExtensionPage("pages/show-db.html")}, + "show db"), + m("br"), + m("button", {onclick: confirmReset}, "reset"), + m("button", {onclick: reload}, "reload chrome extension"), ] } }; -function openWalletAsTab() { - chrome.tabs.create({ - "url": chrome.extension.getURL("popup/popup.html") - }); +function openExtensionPage(page) { + return function() { + chrome.tabs.create({ + "url": chrome.extension.getURL(page) + }); + } } + diff --git a/extension/tsconfig.json b/extension/tsconfig.json @@ -10,6 +10,7 @@ "files": [ "lib/i18n.ts", "lib/refs.ts", + "lib/web-common.ts", "lib/wallet/checkable.ts", "lib/wallet/db.ts", "lib/wallet/emscriptif.ts",