-
Notifications
You must be signed in to change notification settings - Fork 522
/
steal.js
7244 lines (6187 loc) · 211 KB
/
steal.js
1
2
3
4
5
6
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(__global) {
var isWorker = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined'
&& self instanceof WorkerGlobalScope;
var isBrowser = typeof window != 'undefined' && !isWorker;
__global.$__Object$getPrototypeOf = Object.getPrototypeOf || function(obj) {
return obj.__proto__;
};
var $__Object$defineProperty;
(function () {
try {
if (!!Object.defineProperty({}, 'a', {})) {
$__Object$defineProperty = Object.defineProperty;
}
} catch (e) {
$__Object$defineProperty = function (obj, prop, opt) {
try {
obj[prop] = opt.value || opt.get.call(obj);
}
catch(e) {}
}
}
}());
__global.$__Object$create = Object.create || function(o, props) {
function F() {}
F.prototype = o;
if (typeof(props) === "object") {
for (prop in props) {
if (props.hasOwnProperty((prop))) {
F[prop] = props[prop];
}
}
}
return new F();
};
var $__Object$defineProperties = Object.defineProperties;
var $__Object$defineProperty0 = Object.defineProperty;
var $__Object$create = Object.create;
var $__Object$getPrototypeOf = Object.getPrototypeOf;
(function() {
var Promise = __global.Promise || require("when/es6-shim/Promise");
var console;
var $__curScript;
if (__global.console) {
console = __global.console;
console.assert = console.assert || function() {};
} else {
console = { assert: function() {} };
}
if(isBrowser) {
var scripts = document.getElementsByTagName("script");
$__curScript = document.currentScript || scripts[scripts.length - 1];
}
// 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 = $__Object$defineProperty;
var emptyArray = [];
// 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));
})
.then(function(name) {
return Promise.resolve(loader.loaderObj.notifyLoad(request, name, refererName))
.then(function() {
return name;
});
})
// 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;
}
var failedLoads = loader.loaderObj.failed || emptyArray;
for(var i = 0, l = failedLoads.length; i < l; i++) {
load = failedLoads[i];
if(load.name !== name)
continue;
return Promise.reject("The load " + name + " already failed.");
}
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) {
var pass = load.pass || 0;
var passCancelled = function() {
return (load.pass << 0) !== pass ;
};
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) {
if(load.status != "loading" || passCancelled()) {
return;
}
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(load.status != "loading" || passCancelled()) {
return;
}
if (instantiateResult === undefined) {
load.address = load.address || "<Anonymous Module " + ++anonCnt + ">";
// instead of load.kind, use load.isDeclarative
load.isDeclarative = true;
return loader.loaderObj.transpile(load)
.then(function(transpiled) {
// Hijack System.register to set declare function
var curSystem = __global.System;
var curRegister = curSystem.register;
curSystem.register = function(name, regDeps, regDeclare) {
var declare = regDeclare;
var deps = regDeps;
if (typeof name != "string") {
declare = deps;
deps = name;
}
load.declare = declare;
load.depsList = deps;
};
__eval(transpiled, __global, load);
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() {
if(load.status != "loading" || passCancelled()) {
return;
}
load.dependencies = [];
var depsList = load.depsList;
var loadPromises = [];
function loadDep(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
};
// console.log('AddDependencyLoad ' + depLoad.name + ' for ' + load.name);
// snapshot(loader);
if (depLoad.status != "linked") {
var linkSets = load.linkSets.concat([]);
for (var i = 0, l = linkSets.length; i < l; i++)
addLoadToLinkSet(linkSets[i], depLoad);
}
})
);
}
for (var i = 0, l = depsList.length; i < l; i++) {
loadDep(depsList[i], i);
}
return Promise.all(loadPromises);
})
// 15.2.4.6.2 LoadSucceeded
.then(function() {
// console.log('LoadSucceeded ' + load.name);
// snapshot(loader);
if(load.status != "loading" || passCancelled()) {
return;
}
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
function incrementPass(load) {
load.pass = load.pass != null ? (load.pass + 1) : 1;
}
function changeLoadingStatus(load, newStatus) {
var oldStatus = load.status;
load.status = newStatus;
if(newStatus !== oldStatus && oldStatus === "loaded") {
load.linkSets.forEach(function(linkSet){
linkSet.loadingCount++;
});
}
}
// 15.2.4.7.1
function asyncStartLoadPartwayThrough(stepState) {
return function(resolve, reject) {
var loader = stepState.loader;
var name = stepState.moduleName;
var step = stepState.step;
var importingModuleName = stepState.moduleMetadata.importingModuleName;
if (loader.modules[name])
throw new TypeError("\"" + name + "\" already exists in the module table");
// adjusted to pick up existing loads
var existingLoad, firstLinkSet;
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));
}
// If the module importing this is part of the same linkSet, create
// a new one for this import.
firstLinkSet = existingLoad.linkSets[0];
if(importingModuleName && firstLinkSet.loads[importingModuleName]) {
continue;
}
return firstLinkSet.done.then(function() {
resolve(existingLoad);
});
}
}
var load;
if(existingLoad) {
load = existingLoad;
} else {
load = createLoad(name);
load.metadata = stepState.moduleMetadata;
}
var linkSet = createLinkSet(loader, load);
if(!existingLoad) {
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) {
console.assert(load.status == "loading" || load.status == "loaded" || load.status === "failed",
"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);
linkSet.loads[load.name] = true;
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;
// console.log('add to linkset ' + load.name);
// snapshot(linkSet.loader);
for (var i = 0, l = load.dependencies.length; i < l; i++) {
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;
}
}
}
// 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, linkExc) {
var loader = linkSet.loader;
var exc = linkExc;
/*
if (linkSet.loads[0].name != load.name)
exc = addToError(exc, 'Error loading "' + load.name + '" from "' + linkSet.loads[0].name + '" at ' + (linkSet.loads[0].address || '<unknown>') + '\n');
exc = addToError(exc, 'Error loading "' + load.name + '" at ' + (load.address || '<unknown>') + '\n');
*/
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 (load.status === "failed" && indexOf.call(loader.loaderObj.failed, load) == -1)
loader.loaderObj.failed.push(load);
else if(loader.loaderObj._pendingState)
loader.loaderObj._pendingState(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);
}
// 15.2.5.3 Module Linking Groups
// 15.2.5.3.2 BuildLinkageGroups alternative implementation
// Adjustments (also see https://bugs.ecmascript.org/show_bug.cgi?id=2755)
// 1. groups is an already-interleaved array of group kinds
// 2. load.groupIndex is set when this function runs
// 3. load.groupIndex is the interleaved index ie 0 declarative, 1 dynamic, 2 declarative, ... (or starting with dynamic)
function buildLinkageGroups(load, loads, groups) {
groups[load.groupIndex] = groups[load.groupIndex] || [];
// if the load already has a group index and its in its group, its already been done
// this logic naturally handles cycles
if (indexOf.call(groups[load.groupIndex], load) != -1)
return;
// now add it to the group to indicate its been seen
groups[load.groupIndex].push(load);
for (var i = 0, l = loads.length; i < l; i++) {
var loadDep = loads[i];
// dependencies not found are already linked
for (var j = 0; j < load.dependencies.length; j++) {
if (loadDep.name == load.dependencies[j].value) {
// by definition all loads in linkset are loaded, not linked
console.assert(loadDep.status == "loaded", "Load in linkSet not loaded!");
// if it is a group transition, the index of the dependency has gone up
// otherwise it is the same as the parent
var loadDepGroupIndex = load.groupIndex + (loadDep.isDeclarative != load.isDeclarative);
// the group index of an entry is always the maximum
if (loadDep.groupIndex === undefined || loadDep.groupIndex < loadDepGroupIndex) {
// if already in a group, remove from the old group
if (loadDep.groupIndex !== undefined) {
groups[loadDep.groupIndex].splice(indexOf.call(groups[loadDep.groupIndex], loadDep), 1);
// if the old group is empty, then we have a mixed depndency cycle
if (groups[loadDep.groupIndex].length == 0)
throw new TypeError("Mixed dependency cycle detected");
}
loadDep.groupIndex = loadDepGroupIndex;
}
buildLinkageGroups(loadDep, loads, groups);
}
}
}
}
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;
}
// 15.2.5.4
function link(linkSet, linkError) {
var loader = linkSet.loader;
if (!linkSet.loads.length)
return;
// console.log('linking {' + logloads(linkSet.loads) + '}');
// snapshot(loader);
// 15.2.5.3.1 LinkageGroups alternative implementation
// build all the groups
// because the first load represents the top of the tree
// for a given linkset, we can work down from there
var groups = [];
var startingLoad = linkSet.loads[0];
startingLoad.groupIndex = 0;
buildLinkageGroups(startingLoad, linkSet.loads, groups);
// determine the kind of the bottom group
var curGroupDeclarative = startingLoad.isDeclarative == groups.length % 2;
// run through the groups from bottom to top
for (var i = groups.length - 1; i >= 0; i--) {
var group = groups[i];
for (var j = 0; j < group.length; j++) {
var load = group[j];
// 15.2.5.5 LinkDeclarativeModules adjusted
if (curGroupDeclarative) {
linkDeclarativeModule(load, linkSet.loads, loader);
}
// 15.2.5.6 LinkDynamicModules adjusted
else {
var module = doDynamicExecute(linkSet, load, linkError);
if (!module)
return;
load.module = {
name: load.name,
module: module
};
load.status = "linked";
}
finishLoad(loader, load);
}
// alternative current kind for next loop
curGroupDeclarative = !curGroupDeclarative;
}
}
// custom module records for binding graph
// store linking module records in a separate table
function getOrCreateModuleRecord(name, loader) {
var moduleRecords = loader.moduleRecords;
return moduleRecords[name] || (moduleRecords[name] = {
name: name,
dependencies: [],
module: new Module(), // start from an empty module and extend
importers: []
});
}
// custom declarative linking function
function linkDeclarativeModule(load, loads, loader) {
if (load.module)
return;
var module = load.module = getOrCreateModuleRecord(load.name, loader);
var moduleObj = load.module.module;
var registryEntry = load.declare.call(__global, function(name, value) {
// NB This should be an Object.defineProperty, but that is very slow.
// By disaling this module write-protection we gain performance.
// It could be useful to allow an option to enable or disable this.
module.locked = true;
if(typeof name === "object") {
for(var p in name) {
moduleObj[p] = name[p];
}
} else {
moduleObj[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](moduleObj);
}
}
module.locked = false;
return value;
});
// setup our setters and execution function
module.setters = registryEntry.setters;
module.execute = registryEntry.execute;
// now link all the module dependencies
// amending the depMap as we go
for (var i = 0, l = load.dependencies.length; i < l; i++) {
var depName = load.dependencies[i].value;
var depModule = loader.modules[depName];
// if dependency not already in the module registry
// then try and link it now
if (!depModule) {
// get the dependency load record
for (var j = 0; j < loads.length; j++) {
if (loads[j].name != depName)
continue;
// only link if already not already started linking (stops at circular / dynamic)
if (!loads[j].module) {
linkDeclarativeModule(loads[j], loads, loader);
depModule = loads[j].module;
}
// if circular, create the module record
else {
depModule = getOrCreateModuleRecord(depName, loader);
}
}
}
// only declarative modules have dynamic bindings
if (depModule.importers) {
module.dependencies.push(depModule);
depModule.importers.push(module);
}
else {
// track dynamic records as null module records as already linked
module.dependencies.push(null);
}
// run the setter for this dependency
if (module.setters[i])
module.setters[i](depModule.module);
}
load.status = "linked";
}
// 15.2.5.5.1 LinkImports not implemented
// 15.2.5.7 ResolveExportEntries not implemented
// 15.2.5.8 ResolveExports not implemented
// 15.2.5.9 ResolveExport not implemented
// 15.2.5.10 ResolveImportEntries not implemented
// 15.2.6.1
function evaluateLoadedModule(loader, load) {
console.assert(load.status == "linked", "is linked " + load.name);
doEnsureEvaluated(load.module, [], loader);
return load.module.module;
}
/*
* Module Object non-exotic for ES5:
*
* module.module bound module object
* module.execute execution function for module
* module.dependencies list of module objects for dependencies
* See getOrCreateModuleRecord for all properties
*
*/
function doExecute(module, loader) {
try {
module.execute.call(__global);
}
catch(e) {
e.onModuleExecution = true;
cleanupStack(e);
return e;
}
}
function cleanupStack(err) {
if (!err.originalErr) {
var stack = (err.stack || err.message || err).toString().split("\n");
var newStack = [];
for (var i = 0; i < stack.length; i++) {
if (typeof $__curScript == "undefined" || stack[i].indexOf($__curScript.src) == -1)
newStack.push(stack[i]);
}
if(newStack.length) {
err.stack = newStack.join("\n\t");
}
}
return err;
}
// propogate execution errors
// see https://bugs.ecmascript.org/show_bug.cgi?id=2993
function doEnsureEvaluated(module, seen, loader) {
var err = ensureEvaluated(module, seen, loader);
if (err)
throw err;
}
// 15.2.6.2 EnsureEvaluated adjusted
function ensureEvaluated(module, seen, loader) {
if (module.evaluated || !module.dependencies)
return;
seen.push(module);
var deps = module.dependencies;
var err;
for (var i = 0, l = deps.length; i < l; i++) {
var dep = deps[i];
// dynamic dependencies are empty in module.dependencies
// as they are already linked
if (!dep)
continue;
if (indexOf.call(seen, dep) == -1) {
err = ensureEvaluated(dep, seen, loader);
// stop on error, see https://bugs.ecmascript.org/show_bug.cgi?id=2996
if (err) {
err = addToError(err, "Error evaluating " + dep.name + "\n");
return err;
}
}
}
if (module.failed)
return new Error("Module failed execution.");
if (module.evaluated)
return;
module.evaluated = true;
err = doExecute(module, loader);
if (err) {
module.failed = true;
}
else if (Object.preventExtensions) {
// spec variation
// we don't create a new module here because it was created and ammended
// we just disable further extensions instead
Object.preventExtensions(module.module);
}
module.execute = undefined;
return err;
}
function addToError(error, msg) {
var err = error;
if (err instanceof Error)
err.message = msg + err.message;
else
err = msg + err;
return err;
}
// 26.3 Loader
// 26.3.1.1
function Loader(options) {
if (typeof options != "object")
throw new TypeError("Options must be an object");
if (options.normalize)
this.normalize = options.normalize;
if (options.locate)
this.locate = options.locate;
if (options.fetch)
this.fetch = options.fetch;
if (options.translate)
this.translate = options.translate;
if (options.instantiate)
this.instantiate = options.instantiate;
this._loader = {
loaderObj: this,
loads: [],
modules: {},
importPromises: {},
moduleRecords: {}
};
// 26.3.3.6
// 26.3.3.13 realm not implemented
defineProperty(this, "global", {
get: function() {
return __global;
}
});
}
function Module() {}
// 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,
anonymousCount: 0,
// 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];
if(this.failed) {