1 (function (global
, factory
) {
2 typeof exports
=== 'object' && typeof module
!== 'undefined' ? module
.exports
= factory() :
3 typeof define
=== 'function' && define
.amd
? define(factory
) :
4 (global
.BrowserESModuleLoader
= factory());
5 }(this, (function () { 'use strict';
10 var isBrowser
= typeof window
!== 'undefined' && typeof document
!== 'undefined';
11 var isNode
= typeof process
!== 'undefined' && process
.versions
&& process
.versions
.node
;
12 var isWindows
= typeof process
!== 'undefined' && typeof process
.platform
=== 'string' && process
.platform
.match(/^win/);
14 var envGlobal
= typeof self
!== 'undefined' ? self
: global
;
16 * Simple Symbol() shim
18 var hasSymbol
= typeof Symbol
!== 'undefined';
19 function createSymbol (name
) {
20 return hasSymbol
? Symbol() : '@@' + name
;
32 // environent baseURI detection
33 if (typeof document
!= 'undefined' && document
.getElementsByTagName
) {
34 baseURI
= document
.baseURI
;
37 var bases
= document
.getElementsByTagName('base');
38 baseURI
= bases
[0] && bases
[0].href
|| window
.location
.href
;
41 else if (typeof location
!= 'undefined') {
42 baseURI
= location
.href
;
45 // sanitize out the hash and querystring
47 baseURI
= baseURI
.split('#')[0].split('?')[0];
48 var slashIndex
= baseURI
.lastIndexOf('/');
49 if (slashIndex
!== -1)
50 baseURI
= baseURI
.substr(0, slashIndex
+ 1);
52 else if (typeof process
!== 'undefined' && process
.cwd
) {
53 baseURI
= 'file://' + (isWindows
? '/' : '') + process
.cwd();
55 baseURI
= baseURI
.replace(/\\/g, '/');
58 throw new TypeError('No environment baseURI
');
61 // ensure baseURI has trailing "/"
62 if (baseURI[baseURI.length - 1] !== '/')
66 * LoaderError with chaining for loader stacks
68 var errArgs = new Error(0, '_
').fileName == '_
';
69 function LoaderError__Check_error_message_for_loader_stack (childErr, newMessage) {
70 // Convert file:/// URLs to paths in Node
72 newMessage = newMessage.replace(isWindows ? /file:\/\/\//g : /file:\/\//g, '');
74 var message = (childErr.message || childErr) + '\n ' + newMessage;
77 if (errArgs && childErr.fileName)
78 err = new Error(message, childErr.fileName, childErr.lineNumber);
80 err = new Error(message);
83 var stack = childErr.originalErr ? childErr.originalErr.stack : childErr.stack;
86 // node doesn't show the message otherwise
87 err
.stack
= message
+ '\n ' + stack
;
91 err
.originalErr
= childErr
.originalErr
|| childErr
;
96 var resolvedPromise
= Promise
.resolve();
99 * Simple Array values shim
101 function arrayValues (arr
) {
105 if (typeof Symbol
=== 'undefined' || !Symbol
.iterator
)
106 throw new Error('Symbol.iterator not supported in this browser');
109 iterable
[Symbol
.iterator
] = function () {
110 var keys
= Object
.keys(arr
);
114 if (keyIndex
< keys
.length
)
116 value
: arr
[keys
[keyIndex
++]],
133 * We skip the entire native internal pipeline, just providing the bare API
137 this.registry
= new Registry();
140 Loader
.prototype.constructor = Loader
;
142 function ensureInstantiated (module
) {
143 if (!(module
instanceof ModuleNamespace
))
144 throw new TypeError('Module instantiation did not return a valid namespace object.');
149 Loader
.prototype.import = function (key
, parent
) {
150 if (typeof key
!== 'string')
151 throw new TypeError('Loader import method must be passed a module key string');
152 // custom resolveInstantiate combined hook for better perf
154 return resolvedPromise
156 return loader
[RESOLVE_INSTANTIATE
](key
, parent
);
158 .then(ensureInstantiated
)
159 //.then(Module.evaluate)
160 .catch(function (err
) {
161 throw LoaderError__Check_error_message_for_loader_stack(err
, 'Loading ' + key
+ (parent
? ' from ' + parent
: ''));
165 var RESOLVE
= Loader
.resolve
= createSymbol('resolve');
168 * Combined resolve / instantiate hook
170 * Not in current reduced spec, but necessary to separate RESOLVE from RESOLVE + INSTANTIATE as described
171 * in the spec notes of this repo to ensure that loader.resolve doesn't instantiate when not wanted.
173 * We implement RESOLVE_INSTANTIATE as a single hook instead of a separate INSTANTIATE in order to avoid
174 * the need for double registry lookups as a performance optimization.
176 var RESOLVE_INSTANTIATE
= Loader
.resolveInstantiate
= createSymbol('resolveInstantiate');
178 // default resolveInstantiate is just to call resolve and then get from the registry
179 // this provides compatibility for the resolveInstantiate optimization
180 Loader
.prototype[RESOLVE_INSTANTIATE
] = function (key
, parent
) {
182 return loader
.resolve(key
, parent
)
183 .then(function (resolved
) {
184 return loader
.registry
.get(resolved
);
188 function ensureResolution (resolvedKey
) {
189 if (resolvedKey
=== undefined)
190 throw new RangeError('No resolution found.');
194 Loader
.prototype.resolve = function (key
, parent
) {
196 return resolvedPromise
198 return loader
[RESOLVE
](key
, parent
);
200 .then(ensureResolution
)
201 .catch(function (err
) {
202 throw LoaderError__Check_error_message_for_loader_stack(err
, 'Resolving ' + key
+ (parent
? ' to ' + parent
: ''));
206 // 3.3.4 (import without evaluate)
207 // this is not documented because the use of deferred evaluation as in Module.evaluate is not
208 // documented, as it is not considered a stable feature to be encouraged
209 // Loader.prototype.load may well be deprecated if this stays disabled
210 /* Loader.prototype.load = function (key, parent) {
211 return Promise.resolve(this[RESOLVE_INSTANTIATE](key, parent || this.key))
212 .catch(function (err) {
213 throw addToError(err, 'Loading ' + key + (parent ? ' from ' + parent : ''));
220 * Instead of structuring through a Map, just use a dictionary object
221 * We throw for construction attempts so this doesn't affect the public API
223 * Registry has been adjusted to use Namespace objects over ModuleStatus objects
224 * as part of simplifying loader API implementation
226 var iteratorSupport
= typeof Symbol
!== 'undefined' && Symbol
.iterator
;
227 var REGISTRY
= createSymbol('registry');
228 function Registry() {
230 this._registry
= REGISTRY
;
233 if (iteratorSupport
) {
235 Registry
.prototype[Symbol
.iterator
] = function () {
236 return this.entries()[Symbol
.iterator
]();
240 Registry
.prototype.entries = function () {
241 var registry
= this[REGISTRY
];
242 return arrayValues(Object
.keys(registry
).map(function (key
) {
243 return [key
, registry
[key
]];
249 Registry
.prototype.keys = function () {
250 return arrayValues(Object
.keys(this[REGISTRY
]));
253 Registry
.prototype.values = function () {
254 var registry
= this[REGISTRY
];
255 return arrayValues(Object
.keys(registry
).map(function (key
) {
256 return registry
[key
];
260 Registry
.prototype.get = function (key
) {
261 return this[REGISTRY
][key
];
264 Registry
.prototype.set = function (key
, namespace) {
265 if (!(namespace instanceof ModuleNamespace
))
266 throw new Error('Registry must be set with an instance of Module Namespace');
267 this[REGISTRY
][key
] = namespace;
271 Registry
.prototype.has = function (key
) {
272 return Object
.hasOwnProperty
.call(this[REGISTRY
], key
);
275 Registry
.prototype.delete = function (key
) {
276 if (Object
.hasOwnProperty
.call(this[REGISTRY
], key
)) {
277 delete this[REGISTRY
][key
];
284 * Simple ModuleNamespace Exotic object based on a baseObject
285 * We export this for allowing a fast-path for module namespace creation over Module descriptors
287 // var EVALUATE = createSymbol('evaluate');
288 var BASE_OBJECT
= createSymbol('baseObject');
290 // 8.3.1 Reflect.Module
292 * Best-effort simplified non-spec implementation based on
293 * a baseObject referenced via getters.
297 * loader.registry.set('x', new Module({ default: 'x' }));
299 * Optional evaluation function provides experimental Module.evaluate
300 * support for non-executed modules in registry.
302 function ModuleNamespace (baseObject
/*, evaluate*/) {
303 Object
.defineProperty(this, BASE_OBJECT
, {
307 // evaluate defers namespace population
309 Object.defineProperty(this, EVALUATE, {
316 Object
.keys(baseObject
).forEach(extendNamespace
, this);
320 ModuleNamespace
.prototype = Object
.create(null);
322 if (typeof Symbol
!== 'undefined' && Symbol
.toStringTag
)
323 Object
.defineProperty(ModuleNamespace
.prototype, Symbol
.toStringTag
, {
327 function extendNamespace (key
) {
328 Object
.defineProperty(this, key
, {
331 return this[BASE_OBJECT
][key
];
336 /* function doEvaluate (evaluate, context) {
338 evaluate.call(context);
345 // 8.4.1 Module.evaluate... not documented or used because this is potentially unstable
346 Module.evaluate = function (ns) {
347 var evaluate = ns[EVALUATE];
349 ns[EVALUATE] = undefined;
350 var err = doEvaluate(evaluate);
353 ns[EVALUATE] = function () {
358 Object.keys(ns[BASE_OBJECT]).forEach(extendNamespace, ns);
365 * Optimized URL normalization assuming a syntax-valid URL parent
367 function throwResolveError (relUrl
, parentUrl
) {
368 throw new RangeError('Unable to resolve "' + relUrl
+ '" to ' + parentUrl
);
370 function resolveIfNotPlain (relUrl
, parentUrl
) {
371 relUrl
= relUrl
.trim();
372 var parentProtocol
= parentUrl
&& parentUrl
.substr(0, parentUrl
.indexOf(':') + 1);
374 var firstChar
= relUrl
[0];
375 var secondChar
= relUrl
[1];
378 if (firstChar
=== '/' && secondChar
=== '/') {
380 throwResolveError(relUrl
, parentUrl
);
381 return parentProtocol
+ relUrl
;
384 else if (firstChar
=== '.' && (secondChar
=== '/' || secondChar
=== '.' && (relUrl
[2] === '/' || relUrl
.length
=== 2) || relUrl
.length
=== 1)
385 || firstChar
=== '/') {
386 var parentIsPlain
= !parentProtocol
|| parentUrl
[parentProtocol
.length
] !== '/';
388 // read pathname from parent if a URL
389 // pathname taken to be part after leading "/"
392 // resolving to a plain parent -> skip standard URL prefix, and treat entire parent as pathname
393 if (parentUrl
=== undefined)
394 throwResolveError(relUrl
, parentUrl
);
395 pathname
= parentUrl
;
397 else if (parentUrl
[parentProtocol
.length
+ 1] === '/') {
398 // resolving to a :// so we need to read out the auth and host
399 if (parentProtocol
!== 'file:') {
400 pathname
= parentUrl
.substr(parentProtocol
.length
+ 2);
401 pathname
= pathname
.substr(pathname
.indexOf('/') + 1);
404 pathname
= parentUrl
.substr(8);
408 // resolving to :/ so pathname is the /... part
409 pathname
= parentUrl
.substr(parentProtocol
.length
+ 1);
412 if (firstChar
=== '/') {
414 throwResolveError(relUrl
, parentUrl
);
416 return parentUrl
.substr(0, parentUrl
.length
- pathname
.length
- 1) + relUrl
;
419 // join together and split for removal of .. and . segments
420 // looping the string instead of anything fancy for perf reasons
421 // '../../../../../z' resolved to 'x/y' is just 'z' regardless of parentIsPlain
422 var segmented
= pathname
.substr(0, pathname
.lastIndexOf('/') + 1) + relUrl
;
425 var segmentIndex
= undefined;
427 for (var i
= 0; i
< segmented
.length
; i
++) {
428 // busy reading a segment - only terminate on '/'
429 if (segmentIndex
!== undefined) {
430 if (segmented
[i
] === '/') {
431 output
.push(segmented
.substr(segmentIndex
, i
- segmentIndex
+ 1));
432 segmentIndex
= undefined;
437 // new segment - check if it is relative
438 if (segmented
[i
] === '.') {
440 if (segmented
[i
+ 1] === '.' && (segmented
[i
+ 2] === '/' || i
=== segmented
.length
- 2)) {
445 else if (segmented
[i
+ 1] === '/' || i
=== segmented
.length
- 1) {
449 // the start of a new segment as below
454 // this is the plain URI backtracking error (../, package:x -> error)
455 if (parentIsPlain
&& output
.length
=== 0)
456 throwResolveError(relUrl
, parentUrl
);
458 // trailing . or .. segment
459 if (i
=== segmented
.length
)
464 // it is the start of a new segment
467 // finish reading out the last segment
468 if (segmentIndex
!== undefined)
469 output
.push(segmented
.substr(segmentIndex
, segmented
.length
- segmentIndex
));
471 return parentUrl
.substr(0, parentUrl
.length
- pathname
.length
) + output
.join('');
474 // sanitizes and verifies (by returning undefined if not a valid URL-like form)
475 // Windows filepath compatibility is an added convenience here
476 var protocolIndex
= relUrl
.indexOf(':');
477 if (protocolIndex
!== -1) {
479 // C:\x becomes file:///c:/x (we don't support C|\x)
480 if (relUrl
[1] === ':' && relUrl
[2] === '\\' && relUrl
[0].match(/[a-z]/i))
481 return 'file:///' + relUrl
.replace(/\\/g, '/');
490 * Builds directly on top of loader polyfill to provide:
491 * - loader.register support
492 * - hookable higher-level resolve
493 * - instantiate hook returning a ModuleNamespace or undefined for es module loading
494 * - loader error behaviour as in HTML and loader specs, clearing failed modules from registration cache synchronously
495 * - build tracing support by providing a .trace=true and .loads object format
498 var REGISTER_INTERNAL = createSymbol('register
-internal');
500 function RegisterLoader$1 () {
503 var registryDelete = this.registry.delete;
504 this.registry.delete = function (key) {
505 var deleted = registryDelete.call(this, key);
507 // also delete from register registry if linked
508 if (records.hasOwnProperty(key) && !records[key].linkRecord)
516 this[REGISTER_INTERNAL] = {
517 // last anonymous System.register call
518 lastRegister: undefined,
519 // in-flight es module load records
527 RegisterLoader$1.prototype = Object.create(Loader.prototype);
528 RegisterLoader$1.prototype.constructor = RegisterLoader$1;
530 var INSTANTIATE = RegisterLoader$1.instantiate = createSymbol('instantiate
');
532 // default normalize is the WhatWG style normalizer
533 RegisterLoader$1.prototype[RegisterLoader$1.resolve = Loader.resolve] = function (key, parentKey) {
534 return resolveIfNotPlain(key, parentKey || baseURI);
537 RegisterLoader$1.prototype[INSTANTIATE] = function (key, processAnonRegister) {};
539 // once evaluated, the linkRecord is set to undefined leaving just the other load record properties
540 // this allows tracking new binding listeners for es modules through importerSetters
541 // for dynamic modules, the load record is removed entirely.
542 function createLoadRecord (state, key, registration) {
543 return state.records[key] = {
546 // defined System.register cache
547 registration: registration,
549 // module namespace object
553 // this sticks around so new module loads can listen to binding changes
554 // for already-loaded modules by adding themselves to their importerSetters
555 importerSetters: undefined,
557 // in-flight linking record
559 // promise for instantiated
560 instantiatePromise: undefined,
561 dependencies: undefined,
563 executingRequire: false,
565 // underlying module object bindings
566 moduleObj: undefined,
568 // es only, also indicates if es or not
571 // promise for instantiated dependencies (dependencyInstantiations populated)
572 depsInstantiatePromise: undefined,
573 // will be the array of dependency load record or a module namespace
574 dependencyInstantiations: undefined,
576 // indicates if the load and all its dependencies are instantiated and linked
577 // but not yet executed
578 // mostly just a performance shortpath to avoid rechecking the promises above
582 // NB optimization and way of ensuring module objects in setters
583 // indicates setters which should run pre-execution of that dependency
584 // setters is then just for completely executed module objects
585 // alternatively we just pass the partially filled module objects as
586 // arguments into the execute function
587 // hoisted: undefined
592 RegisterLoader$1.prototype[Loader.resolveInstantiate] = function (key, parentKey) {
594 var state = this[REGISTER_INTERNAL];
595 var registry = loader.registry[loader.registry._registry];
597 return resolveInstantiate(loader, key, parentKey, registry, state)
598 .then(function (instantiated) {
599 if (instantiated instanceof ModuleNamespace)
602 // if already beaten to linked, return
603 if (instantiated.module)
604 return instantiated.module;
606 // resolveInstantiate always returns a load record with a link record and no module value
607 if (instantiated.linkRecord.linked)
608 return ensureEvaluate(loader, instantiated, instantiated.linkRecord, registry, state, undefined);
610 return instantiateDeps(loader, instantiated, instantiated.linkRecord, registry, state, [instantiated])
612 return ensureEvaluate(loader, instantiated, instantiated.linkRecord, registry, state, undefined);
614 .catch(function (err) {
615 clearLoadErrors(loader, instantiated);
621 function resolveInstantiate (loader, key, parentKey, registry, state) {
622 // normalization shortpath for already-normalized key
623 // could add a plain name filter, but doesn't yet seem necessary
for perf
624 var module
= registry
[key
];
626 return Promise
.resolve(module
);
628 var load
= state
.records
[key
];
630 // already linked but not in main registry is ignored
631 if (load
&& !load
.module
)
632 return instantiate(loader
, load
, load
.linkRecord
, registry
, state
);
634 return loader
.resolve(key
, parentKey
)
635 .then(function (resolvedKey
) {
636 // main loader registry always takes preference
637 module
= registry
[resolvedKey
];
641 load
= state
.records
[resolvedKey
];
643 // already has a module value but not already in the registry (load.module)
644 // means it was removed by registry.delete, so we should
645 // disgard the current load record creating a new one over it
646 // but keep any existing registration
647 if (!load
|| load
.module
)
648 load
= createLoadRecord(state
, resolvedKey
, load
&& load
.registration
);
650 var link
= load
.linkRecord
;
654 return instantiate(loader
, load
, link
, registry
, state
);
658 function createProcessAnonRegister (loader
, load
, state
) {
660 var lastRegister
= state
.lastRegister
;
663 return !!load
.registration
;
665 state
.lastRegister
= undefined;
666 load
.registration
= lastRegister
;
672 function instantiate (loader
, load
, link
, registry
, state
) {
673 return link
.instantiatePromise
|| (link
.instantiatePromise
=
674 // if there is already an existing registration, skip running instantiate
675 (load
.registration
? Promise
.resolve() : Promise
.resolve().then(function () {
676 state
.lastRegister
= undefined;
677 return loader
[INSTANTIATE
](load
.key
, loader
[INSTANTIATE
].length
> 1 && createProcessAnonRegister(loader
, load
, state
));
679 .then(function (instantiation
) {
680 // direct module return from instantiate -> we're done
681 if (instantiation
!== undefined) {
682 if (!(instantiation
instanceof ModuleNamespace
))
683 throw new TypeError('Instantiate did not return a valid Module object.');
685 delete state
.records
[load
.key
];
687 traceLoad(loader
, load
, link
);
688 return registry
[load
.key
] = instantiation
;
691 // run the cached loader.register declaration if there is one
692 var registration
= load
.registration
;
693 // clear to allow new registrations for future loads (combined with registry delete)
694 load
.registration
= undefined;
696 throw new TypeError('Module instantiation did not call an anonymous or correctly named System.register.');
698 link
.dependencies
= registration
[0];
700 load
.importerSetters
= [];
704 // process System.registerDynamic declaration
705 if (registration
[2]) {
706 link
.moduleObj
.default = {};
707 link
.moduleObj
.__useDefault
= true;
708 link
.executingRequire
= registration
[1];
709 link
.execute
= registration
[2];
712 // process System.register declaration
714 registerDeclarative(loader
, load
, link
, registration
[1]);
717 // shortpath to instantiateDeps
718 if (!link
.dependencies
.length
) {
721 traceLoad(loader
, load
, link
);
726 .catch(function (err
) {
727 throw link
.error
= LoaderError__Check_error_message_for_loader_stack(err
, 'Instantiating ' + load
.key
);
731 // like resolveInstantiate, but returning load records for linking
732 function resolveInstantiateDep (loader
, key
, parentKey
, registry
, state
, traceDepMap
) {
733 // normalization shortpaths for already-normalized key
734 // DISABLED to prioritise consistent resolver calls
735 // could add a plain name filter, but doesn't yet seem necessary for perf
736 /* var load = state.records[key];
737 var module = registry[key];
741 traceDepMap[key] = key;
743 // registry authority check in case module was deleted or replaced in main registry
744 if (load && load.module && load.module === module)
750 // already linked but not in main registry is ignored
751 if (load && !load.module) {
753 traceDepMap[key] = key;
754 return instantiate(loader, load, load.linkRecord, registry, state);
756 return loader
.resolve(key
, parentKey
)
757 .then(function (resolvedKey
) {
759 traceDepMap
[key
] = resolvedKey
;
761 // normalization shortpaths for already-normalized key
762 var load
= state
.records
[resolvedKey
];
763 var module
= registry
[resolvedKey
];
765 // main loader registry always takes preference
766 if (module
&& (!load
|| load
.module
&& module
!== load
.module
))
769 // already has a module value but not already in the registry (load.module)
770 // means it was removed by registry.delete, so we should
771 // disgard the current load record creating a new one over it
772 // but keep any existing registration
773 if (!load
|| !module
&& load
.module
)
774 load
= createLoadRecord(state
, resolvedKey
, load
&& load
.registration
);
776 var link
= load
.linkRecord
;
780 return instantiate(loader
, load
, link
, registry
, state
);
784 function traceLoad (loader
, load
, link
) {
785 loader
.loads
= loader
.loads
|| {};
786 loader
.loads
[load
.key
] = {
788 deps
: link
.dependencies
,
789 depMap
: link
.depMap
|| {}
794 * Convert a CJS module.exports into a valid object for new Module:
796 * new Module(getEsModule(module.exports))
798 * Sets the default value to the module, while also reading off named exports carefully.
800 function registerDeclarative (loader
, load
, link
, declare
) {
801 var moduleObj
= link
.moduleObj
;
802 var importerSetters
= load
.importerSetters
;
806 // closure especially not based on link to allow link record disposal
807 var declared
= declare
.call(envGlobal
, function (name
, value
) {
808 // export setter propogation with locking to avoid cycles
812 if (typeof name
=== 'object') {
814 if (p
!== '__useDefault')
815 moduleObj
[p
] = name
[p
];
818 moduleObj
[name
] = value
;
822 for (var i
= 0; i
< importerSetters
.length
; i
++)
823 importerSetters
[i
](moduleObj
);
827 }, new ContextualLoader(loader
, load
.key
));
829 link
.setters
= declared
.setters
;
830 link
.execute
= declared
.execute
;
831 if (declared
.exports
)
832 link
.moduleObj
= moduleObj
= declared
.exports
;
835 function instantiateDeps (loader
, load
, link
, registry
, state
, seen
) {
836 return (link
.depsInstantiatePromise
|| (link
.depsInstantiatePromise
= Promise
.resolve()
838 var depsInstantiatePromises
= Array(link
.dependencies
.length
);
840 for (var i
= 0; i
< link
.dependencies
.length
; i
++)
841 depsInstantiatePromises
[i
] = resolveInstantiateDep(loader
, link
.dependencies
[i
], load
.key
, registry
, state
, loader
.trace
&& link
.depMap
|| (link
.depMap
= {}));
843 return Promise
.all(depsInstantiatePromises
);
845 .then(function (dependencyInstantiations
) {
846 link
.dependencyInstantiations
= dependencyInstantiations
;
848 // run setters to set up bindings to instantiated dependencies
850 for (var i
= 0; i
< dependencyInstantiations
.length
; i
++) {
851 var setter
= link
.setters
[i
];
853 var instantiation
= dependencyInstantiations
[i
];
855 if (instantiation
instanceof ModuleNamespace
) {
856 setter(instantiation
);
859 setter(instantiation
.module
|| instantiation
.linkRecord
.moduleObj
);
860 // this applies to both es and dynamic registrations
861 if (instantiation
.importerSetters
)
862 instantiation
.importerSetters
.push(setter
);
869 // now deeply instantiateDeps on each dependencyInstantiation that is a load record
870 var deepDepsInstantiatePromises
= [];
872 for (var i
= 0; i
< link
.dependencies
.length
; i
++) {
873 var depLoad
= link
.dependencyInstantiations
[i
];
874 var depLink
= depLoad
.linkRecord
;
876 if (!depLink
|| depLink
.linked
)
879 if (seen
.indexOf(depLoad
) !== -1)
883 deepDepsInstantiatePromises
.push(instantiateDeps(loader
, depLoad
, depLoad
.linkRecord
, registry
, state
, seen
));
886 return Promise
.all(deepDepsInstantiatePromises
);
889 // as soon as all dependencies instantiated, we are ready for evaluation so can add to the registry
890 // this can run multiple times, but so what
893 traceLoad(loader
, load
, link
);
897 .catch(function (err
) {
898 err
= LoaderError__Check_error_message_for_loader_stack(err
, 'Loading ' + load
.key
);
900 // throw up the instantiateDeps stack
901 // loads are then synchonously cleared at the top-level through the clearLoadErrors helper below
902 // this then ensures avoiding partially unloaded tree states
903 link
.error
= link
.error
|| err
;
909 // clears an errored load and all its errored dependencies from the loads registry
910 function clearLoadErrors (loader
, load
) {
911 var state
= loader
[REGISTER_INTERNAL
];
914 if (state
.records
[load
.key
] === load
)
915 delete state
.records
[load
.key
];
917 var link
= load
.linkRecord
;
922 if (link
.dependencyInstantiations
)
923 link
.dependencyInstantiations
.forEach(function (depLoad
, index
) {
924 if (!depLoad
|| depLoad
instanceof ModuleNamespace
)
927 if (depLoad
.linkRecord
) {
928 if (depLoad
.linkRecord
.error
) {
929 // provides a circular reference check
930 if (state
.records
[depLoad
.key
] === depLoad
)
931 clearLoadErrors(loader
, depLoad
);
934 // unregister setters for es dependency load records that will remain
935 if (link
.setters
&& depLoad
.importerSetters
) {
936 var setterIndex
= depLoad
.importerSetters
.indexOf(link
.setters
[index
]);
937 depLoad
.importerSetters
.splice(setterIndex
, 1);
946 RegisterLoader
$1.prototype.register = function (key
, deps
, declare
) {
947 var state
= this[REGISTER_INTERNAL
];
949 // anonymous modules get stored as lastAnon
950 if (declare
=== undefined) {
951 state
.lastRegister
= [key
, deps
, undefined];
954 // everything else registers into the register cache
956 var load
= state
.records
[key
] || createLoadRecord(state
, key
, undefined);
957 load
.registration
= [deps
, declare
, undefined];
962 * System.registerDyanmic
964 RegisterLoader
$1.prototype.registerDynamic = function (key
, deps
, executingRequire
, execute
) {
965 var state
= this[REGISTER_INTERNAL
];
967 // anonymous modules get stored as lastAnon
968 if (typeof key
!== 'string') {
969 state
.lastRegister
= [key
, deps
, executingRequire
];
972 // everything else registers into the register cache
974 var load
= state
.records
[key
] || createLoadRecord(state
, key
, undefined);
975 load
.registration
= [deps
, executingRequire
, execute
];
979 // ContextualLoader class
980 // backwards-compatible with previous System.register context argument by exposing .id
981 function ContextualLoader (loader
, key
) {
982 this.loader
= loader
;
983 this.key
= this.id
= key
;
985 ContextualLoader
.prototype.constructor = function () {
986 throw new TypeError('Cannot subclass the contextual loader only Reflect.Loader.');
988 ContextualLoader
.prototype.import = function (key
) {
989 return this.loader
.import(key
, this.key
);
991 ContextualLoader
.prototype.resolve = function (key
) {
992 return this.loader
.resolve(key
, this.key
);
994 ContextualLoader
.prototype.load = function (key
) {
995 return this.loader
.load(key
, this.key
);
998 // this is the execution function bound to the Module namespace record
999 function ensureEvaluate (loader
, load
, link
, registry
, state
, seen
) {
1006 if (seen
&& seen
.indexOf(load
) !== -1)
1007 return load
.linkRecord
.moduleObj
;
1009 // for ES loads we always run ensureEvaluate on top-level, so empty seen is passed regardless
1010 // for dynamic loads, we pass seen if also dynamic
1011 var err
= doEvaluate(loader
, load
, link
, registry
, state
, link
.setters
? [] : seen
|| []);
1013 clearLoadErrors(loader
, load
);
1020 function makeDynamicRequire (loader
, key
, dependencies
, dependencyInstantiations
, registry
, state
, seen
) {
1021 // we can only require from already-known dependencies
1022 return function (name
) {
1023 for (var i
= 0; i
< dependencies
.length
; i
++) {
1024 if (dependencies
[i
] === name
) {
1025 var depLoad
= dependencyInstantiations
[i
];
1028 if (depLoad
instanceof ModuleNamespace
)
1031 module
= ensureEvaluate(loader
, depLoad
, depLoad
.linkRecord
, registry
, state
, seen
);
1033 return module
.__useDefault
? module
.default : module
;
1036 throw new Error('Module ' + name
+ ' not declared as a System.registerDynamic dependency of ' + key
);
1040 // ensures the given es load is evaluated
1041 // returns the error if any
1042 function doEvaluate (loader
, load
, link
, registry
, state
, seen
) {
1047 // es modules evaluate dependencies first
1048 // non es modules explicitly call moduleEvaluate through require
1050 var depLoad
, depLink
;
1051 for (var i
= 0; i
< link
.dependencies
.length
; i
++) {
1052 depLoad
= link
.dependencyInstantiations
[i
];
1054 if (depLoad
instanceof ModuleNamespace
)
1057 // custom Module returned from instantiate
1058 depLink
= depLoad
.linkRecord
;
1059 if (depLink
&& seen
.indexOf(depLoad
) === -1) {
1061 err
= depLink
.error
;
1063 // dynamic / declarative boundaries clear the "seen" list
1064 // we just let cross format circular throw as would happen in real implementations
1065 err
= doEvaluate(loader
, depLoad
, depLink
, registry
, state
, depLink
.setters
? seen
: []);
1069 return link
.error
= LoaderError__Check_error_message_for_loader_stack(err
, 'Evaluating ' + load
.key
);
1073 // link.execute won't exist for Module returns from instantiate on top-level load
1075 // ES System.register execute
1076 // "this" is null in ES
1078 err
= declarativeExecute(link
.execute
);
1080 // System.registerDynamic execute
1081 // "this" is "exports" in CJS
1083 var module
= { id
: load
.key
};
1084 var moduleObj
= link
.moduleObj
;
1085 Object
.defineProperty(module
, 'exports', {
1087 set: function (exports
) {
1088 moduleObj
.default = exports
;
1091 return moduleObj
.default;
1095 var require
= makeDynamicRequire(loader
, load
.key
, link
.dependencies
, link
.dependencyInstantiations
, registry
, state
, seen
);
1097 // evaluate deps first
1098 if (!link
.executingRequire
)
1099 for (var i
= 0; i
< link
.dependencies
.length
; i
++)
1100 require(link
.dependencies
[i
]);
1102 err
= dynamicExecute(link
.execute
, require
, moduleObj
.default, module
);
1104 // pick up defineProperty calls to module.exports when we can
1105 if (module
.exports
!== moduleObj
.default)
1106 moduleObj
.default = module
.exports
;
1108 var moduleDefault
= moduleObj
.default;
1110 // __esModule flag extension support via lifting
1111 if (moduleDefault
&& moduleDefault
.__esModule
) {
1112 if (moduleObj
.__useDefault
)
1113 delete moduleObj
.__useDefault
;
1114 for (var p
in moduleDefault
) {
1115 if (Object
.hasOwnProperty
.call(moduleDefault
, p
))
1116 moduleObj
[p
] = moduleDefault
[p
];
1118 moduleObj
.__esModule
= true;
1124 return link
.error
= LoaderError__Check_error_message_for_loader_stack(err
, 'Evaluating ' + load
.key
);
1126 registry
[load
.key
] = load
.module
= new ModuleNamespace(link
.moduleObj
);
1128 // if not an esm module, run importer setters and clear them
1129 // this allows dynamic modules to update themselves into es modules
1130 // as soon as execution has completed
1131 if (!link
.setters
) {
1132 if (load
.importerSetters
)
1133 for (var i
= 0; i
< load
.importerSetters
.length
; i
++)
1134 load
.importerSetters
[i
](load
.module
);
1135 load
.importerSetters
= undefined;
1138 // dispose link record
1139 load
.linkRecord
= undefined;
1142 // {} is the closest we can get to call(undefined)
1143 var nullContext
= {};
1145 Object
.freeze(nullContext
);
1147 function declarativeExecute (execute
) {
1149 execute
.call(nullContext
);
1156 function dynamicExecute (execute
, require
, exports
, module
) {
1158 var output
= execute
.call(envGlobal
, require
, exports
, module
);
1159 if (output
!== undefined)
1160 module
.exports
= output
;
1169 // <script type="module"> support
1170 var anonSources
= {};
1171 if (typeof document
!= 'undefined' && document
.getElementsByTagName
) {
1172 var handleError = function(err
) {
1173 // dispatch an error event so that we can display in errors in browsers
1174 // that don't yet support unhandledrejection
1175 if (window
.onunhandledrejection
=== undefined) {
1177 var evt
= new Event('error');
1178 } catch (_eventError
) {
1179 var evt
= document
.createEvent('Event');
1180 evt
.initEvent('error', true, true);
1182 evt
.message
= err
.message
;
1184 evt
.filename
= err
.fileName
;
1185 evt
.lineno
= err
.lineNumber
;
1186 evt
.colno
= err
.columnNumber
;
1187 } else if (err
.sourceURL
) {
1188 evt
.filename
= err
.sourceURL
;
1189 evt
.lineno
= err
.line
;
1190 evt
.colno
= err
.column
;
1193 window
.dispatchEvent(evt
);
1196 // throw so it still shows up in the console
1200 var ready = function() {
1201 document
.removeEventListener('DOMContentLoaded', ready
, false );
1205 var scripts
= document
.getElementsByTagName('script');
1206 for (var i
= 0; i
< scripts
.length
; i
++) {
1207 var script
= scripts
[i
];
1208 if (script
.type
== 'module' && !script
.loaded
) {
1209 script
.loaded
= true;
1211 loader
.import(script
.src
).catch(handleError
);
1213 // anonymous modules supported via a custom naming scheme and registry
1215 var uri
= './<anon' + ++anonCnt
+ '>';
1216 if (script
.id
!== ""){
1217 uri
= "./" + script
.id
;
1220 var anonName
= resolveIfNotPlain(uri
, baseURI
);
1221 anonSources
[anonName
] = script
.innerHTML
;
1222 loader
.import(anonName
).catch(handleError
);
1229 if (document
.readyState
=== 'complete')
1232 document
.addEventListener('DOMContentLoaded', ready
, false);
1235 function BrowserESModuleLoader(baseKey
) {
1237 this.baseKey
= resolveIfNotPlain(baseKey
, baseURI
) || resolveIfNotPlain('./' + baseKey
, baseURI
);
1239 RegisterLoader
$1.call(this);
1243 // ensure System.register is available
1244 envGlobal
.System
= envGlobal
.System
|| {};
1245 if (typeof envGlobal
.System
.register
== 'function')
1246 var prevRegister
= envGlobal
.System
.register
;
1247 envGlobal
.System
.register = function() {
1248 loader
.register
.apply(loader
, arguments
);
1250 prevRegister
.apply(this, arguments
);
1253 BrowserESModuleLoader
.prototype = Object
.create(RegisterLoader
$1.prototype);
1255 // normalize is never given a relative name like "./x", that part is already handled
1256 BrowserESModuleLoader
.prototype[RegisterLoader
$1.resolve
] = function(key
, parent
) {
1257 var resolved
= RegisterLoader
$1.prototype[RegisterLoader
$1.resolve
].call(this, key
, parent
|| this.baseKey
) || key
;
1259 throw new RangeError('ES module loader does not resolve plain module names, resolving "' + key
+ '" to ' + parent
);
1264 function xhrFetch(url
, resolve
, reject
) {
1265 var xhr
= new XMLHttpRequest();
1266 var load = function(source
) {
1267 resolve(xhr
.responseText
);
1269 var error = function() {
1270 reject(new Error('XHR error' + (xhr
.status
? ' (' + xhr
.status
+ (xhr
.statusText
? ' ' + xhr
.statusText
: '') + ')' : '') + ' loading ' + url
));
1273 xhr
.onreadystatechange = function () {
1274 if (xhr
.readyState
=== 4) {
1275 // in Chrome on file:/// URLs, status is 0
1276 if (xhr
.status
== 0) {
1277 if (xhr
.responseText
) {
1281 // when responseText is empty, wait for load or error event
1282 // to inform if it is a 404 or empty file
1283 xhr
.addEventListener('error', error
);
1284 xhr
.addEventListener('load', load
);
1287 else if (xhr
.status
=== 200) {
1295 xhr
.open("GET", url
, true);
1299 var WorkerPool = function (script
, size
) {
1300 script
= document
.currentScript
.src
.substr(0, document
.currentScript
.src
.lastIndexOf("/")) + "/" + script
;
1301 this._workers
= new Array(size
);
1305 this.onmessage
= undefined;
1306 this._stopTimeout
= undefined;
1307 for (var i
= 0; i
< size
; i
++) {
1308 var wrkr
= new Worker(script
);
1311 wrkr
.onmessage
= this._onmessage
.bind(this, wrkr
);
1312 wrkr
.onerror
= this._onerror
.bind(this);
1313 this._workers
[i
] = wrkr
;
1318 WorkerPool
.prototype = {
1319 postMessage: function (msg
) {
1320 if (this._stopTimeout
!== undefined) {
1321 clearTimeout(this._stopTimeout
);
1322 this._stopTimeout
= undefined;
1324 var wrkr
= this._workers
[this._ind
% this._size
];
1327 wrkr
.postMessage(msg
);
1331 _onmessage: function (wrkr
, evt
) {
1334 this.onmessage(evt
, wrkr
);
1338 _onerror: function(err
) {
1340 var evt
= new Event('error');
1341 } catch (_eventError
) {
1342 var evt
= document
.createEvent('Event');
1343 evt
.initEvent('error', true, true);
1345 evt
.message
= err
.message
;
1346 evt
.filename
= err
.filename
;
1347 evt
.lineno
= err
.lineno
;
1348 evt
.colno
= err
.colno
;
1349 evt
.error
= err
.error
;
1350 window
.dispatchEvent(evt
);
1353 _checkJobs: function () {
1354 if (this._jobs
=== 0 && this._stopTimeout
=== undefined) {
1355 // wait for 2s of inactivity before stopping (that should be enough for local loading)
1356 this._stopTimeout
= setTimeout(this._stop
.bind(this), 2000);
1360 _stop: function () {
1361 this._workers
.forEach(function(wrkr
) {
1367 var promiseMap
= new Map();
1368 var babelWorker
= new WorkerPool('babel-worker.js', 3);
1369 babelWorker
.onmessage = function (evt
) {
1370 var promFuncs
= promiseMap
.get(evt
.data
.key
);
1371 promFuncs
.resolve(evt
.data
);
1372 promiseMap
.delete(evt
.data
.key
);
1375 // instantiate just needs to run System.register
1376 // so we fetch the source, convert into the Babel System module format, then evaluate it
1377 BrowserESModuleLoader
.prototype[RegisterLoader
$1.instantiate
] = function(key
, processAnonRegister
) {
1380 // load as ES with Babel converting into System.register
1381 return new Promise(function(resolve
, reject
) {
1383 if (anonSources
[key
]) {
1384 resolve(anonSources
[key
]);
1385 anonSources
[key
] = undefined;
1387 // otherwise we fetch
1389 xhrFetch(key
, resolve
, reject
);
1392 .then(function(source
) {
1393 // check our cache first
1394 var cacheEntry
= localStorage
.getItem(key
);
1396 cacheEntry
= JSON
.parse(cacheEntry
);
1397 // TODO: store a hash instead
1398 if (cacheEntry
.source
=== source
) {
1399 return Promise
.resolve({key
: key
, code
: cacheEntry
.code
, source
: cacheEntry
.source
});
1402 return new Promise(function (resolve
, reject
) {
1403 promiseMap
.set(key
, {resolve
: resolve
, reject
: reject
});
1404 babelWorker
.postMessage({key
: key
, source
: source
});
1406 }).then(function (data
) {
1407 // evaluate without require, exports and module variables
1408 // we leave module in for now to allow module.require access
1410 var cacheEntry
= JSON
.stringify({source
: data
.source
, code
: data
.code
});
1411 localStorage
.setItem(key
, cacheEntry
);
1413 if (window
.console
) {
1414 window
.console
.warn('Unable to cache transpiled version of ' + key
+ ': ' + e
);
1417 (0, eval
)(data
.code
+ '\n//# sourceURL=' + data
.key
+ '!transpiled');
1418 processAnonRegister();
1422 // create a default loader instance in the browser
1424 loader
= new BrowserESModuleLoader();
1426 return BrowserESModuleLoader
;
1429 //# sourceMappingURL=browser-es-module-loader.js.map