-
Notifications
You must be signed in to change notification settings - Fork 31.8k
/
Copy pathloader.js
1891 lines (1891 loc) · 66.3 KB
/
loader.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
* Please make sure to make edits in the .ts file at https://github.com/microsoft/vscode-loader/
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*--------------------------------------------------------------------------------------------*/
const _amdLoaderGlobal = this;
const _commonjsGlobal = typeof global === 'object' ? global : {};
var AMDLoader;
(function (AMDLoader) {
AMDLoader.global = _amdLoaderGlobal;
class Environment {
get isWindows() {
this._detect();
return this._isWindows;
}
get isNode() {
this._detect();
return this._isNode;
}
get isElectronRenderer() {
this._detect();
return this._isElectronRenderer;
}
get isWebWorker() {
this._detect();
return this._isWebWorker;
}
get isElectronNodeIntegrationWebWorker() {
this._detect();
return this._isElectronNodeIntegrationWebWorker;
}
constructor() {
this._detected = false;
this._isWindows = false;
this._isNode = false;
this._isElectronRenderer = false;
this._isWebWorker = false;
this._isElectronNodeIntegrationWebWorker = false;
}
_detect() {
if (this._detected) {
return;
}
this._detected = true;
this._isWindows = Environment._isWindows();
this._isNode = (typeof module !== 'undefined' && !!module.exports);
this._isElectronRenderer = (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'renderer');
this._isWebWorker = (typeof AMDLoader.global.importScripts === 'function');
this._isElectronNodeIntegrationWebWorker = this._isWebWorker && (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'worker');
}
static _isWindows() {
if (typeof navigator !== 'undefined') {
if (navigator.userAgent && navigator.userAgent.indexOf('Windows') >= 0) {
return true;
}
}
if (typeof process !== 'undefined') {
return (process.platform === 'win32');
}
return false;
}
}
AMDLoader.Environment = Environment;
})(AMDLoader || (AMDLoader = {}));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var AMDLoader;
(function (AMDLoader) {
class LoaderEvent {
constructor(type, detail, timestamp) {
this.type = type;
this.detail = detail;
this.timestamp = timestamp;
}
}
AMDLoader.LoaderEvent = LoaderEvent;
class LoaderEventRecorder {
constructor(loaderAvailableTimestamp) {
this._events = [new LoaderEvent(1 /* LoaderEventType.LoaderAvailable */, '', loaderAvailableTimestamp)];
}
record(type, detail) {
this._events.push(new LoaderEvent(type, detail, AMDLoader.Utilities.getHighPerformanceTimestamp()));
}
getEvents() {
return this._events;
}
}
AMDLoader.LoaderEventRecorder = LoaderEventRecorder;
class NullLoaderEventRecorder {
record(type, detail) {
// Nothing to do
}
getEvents() {
return [];
}
}
NullLoaderEventRecorder.INSTANCE = new NullLoaderEventRecorder();
AMDLoader.NullLoaderEventRecorder = NullLoaderEventRecorder;
})(AMDLoader || (AMDLoader = {}));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var AMDLoader;
(function (AMDLoader) {
class Utilities {
/**
* This method does not take care of / vs \
*/
static fileUriToFilePath(isWindows, uri) {
uri = decodeURI(uri).replace(/%23/g, '#');
if (isWindows) {
if (/^file:\/\/\//.test(uri)) {
// This is a URI without a hostname => return only the path segment
return uri.substr(8);
}
if (/^file:\/\//.test(uri)) {
return uri.substr(5);
}
}
else {
if (/^file:\/\//.test(uri)) {
return uri.substr(7);
}
}
// Not sure...
return uri;
}
static startsWith(haystack, needle) {
return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
}
static endsWith(haystack, needle) {
return haystack.length >= needle.length && haystack.substr(haystack.length - needle.length) === needle;
}
// only check for "?" before "#" to ensure that there is a real Query-String
static containsQueryString(url) {
return /^[^\#]*\?/gi.test(url);
}
/**
* Does `url` start with http:// or https:// or file:// or / ?
*/
static isAbsolutePath(url) {
return /^((http:\/\/)|(https:\/\/)|(file:\/\/)|(\/))/.test(url);
}
static forEachProperty(obj, callback) {
if (obj) {
let key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
callback(key, obj[key]);
}
}
}
}
static isEmpty(obj) {
let isEmpty = true;
Utilities.forEachProperty(obj, () => {
isEmpty = false;
});
return isEmpty;
}
static recursiveClone(obj) {
if (!obj || typeof obj !== 'object' || obj instanceof RegExp) {
return obj;
}
if (!Array.isArray(obj) && Object.getPrototypeOf(obj) !== Object.prototype) {
// only clone "simple" objects
return obj;
}
let result = Array.isArray(obj) ? [] : {};
Utilities.forEachProperty(obj, (key, value) => {
if (value && typeof value === 'object') {
result[key] = Utilities.recursiveClone(value);
}
else {
result[key] = value;
}
});
return result;
}
static generateAnonymousModule() {
return '===anonymous' + (Utilities.NEXT_ANONYMOUS_ID++) + '===';
}
static isAnonymousModule(id) {
return Utilities.startsWith(id, '===anonymous');
}
static getHighPerformanceTimestamp() {
if (!this.PERFORMANCE_NOW_PROBED) {
this.PERFORMANCE_NOW_PROBED = true;
this.HAS_PERFORMANCE_NOW = (AMDLoader.global.performance && typeof AMDLoader.global.performance.now === 'function');
}
return (this.HAS_PERFORMANCE_NOW ? AMDLoader.global.performance.now() : Date.now());
}
}
Utilities.NEXT_ANONYMOUS_ID = 1;
Utilities.PERFORMANCE_NOW_PROBED = false;
Utilities.HAS_PERFORMANCE_NOW = false;
AMDLoader.Utilities = Utilities;
})(AMDLoader || (AMDLoader = {}));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var AMDLoader;
(function (AMDLoader) {
function ensureError(err) {
if (err instanceof Error) {
return err;
}
const result = new Error(err.message || String(err) || 'Unknown Error');
if (err.stack) {
result.stack = err.stack;
}
return result;
}
AMDLoader.ensureError = ensureError;
;
class ConfigurationOptionsUtil {
/**
* Ensure configuration options make sense
*/
static validateConfigurationOptions(options) {
function defaultOnError(err) {
if (err.phase === 'loading') {
console.error('Loading "' + err.moduleId + '" failed');
console.error(err);
console.error('Here are the modules that depend on it:');
console.error(err.neededBy);
return;
}
if (err.phase === 'factory') {
console.error('The factory function of "' + err.moduleId + '" has thrown an exception');
console.error(err);
console.error('Here are the modules that depend on it:');
console.error(err.neededBy);
return;
}
}
options = options || {};
if (typeof options.baseUrl !== 'string') {
options.baseUrl = '';
}
if (typeof options.isBuild !== 'boolean') {
options.isBuild = false;
}
if (typeof options.paths !== 'object') {
options.paths = {};
}
if (typeof options.config !== 'object') {
options.config = {};
}
if (typeof options.catchError === 'undefined') {
options.catchError = false;
}
if (typeof options.recordStats === 'undefined') {
options.recordStats = false;
}
if (typeof options.urlArgs !== 'string') {
options.urlArgs = '';
}
if (typeof options.onError !== 'function') {
options.onError = defaultOnError;
}
if (!Array.isArray(options.ignoreDuplicateModules)) {
options.ignoreDuplicateModules = [];
}
if (options.baseUrl.length > 0) {
if (!AMDLoader.Utilities.endsWith(options.baseUrl, '/')) {
options.baseUrl += '/';
}
}
if (typeof options.cspNonce !== 'string') {
options.cspNonce = '';
}
if (typeof options.preferScriptTags === 'undefined') {
options.preferScriptTags = false;
}
if (options.nodeCachedData && typeof options.nodeCachedData === 'object') {
if (typeof options.nodeCachedData.seed !== 'string') {
options.nodeCachedData.seed = 'seed';
}
if (typeof options.nodeCachedData.writeDelay !== 'number' || options.nodeCachedData.writeDelay < 0) {
options.nodeCachedData.writeDelay = 1000 * 7;
}
if (!options.nodeCachedData.path || typeof options.nodeCachedData.path !== 'string') {
const err = ensureError(new Error('INVALID cached data configuration, \'path\' MUST be set'));
err.phase = 'configuration';
options.onError(err);
options.nodeCachedData = undefined;
}
}
return options;
}
static mergeConfigurationOptions(overwrite = null, base = null) {
let result = AMDLoader.Utilities.recursiveClone(base || {});
// Merge known properties and overwrite the unknown ones
AMDLoader.Utilities.forEachProperty(overwrite, (key, value) => {
if (key === 'ignoreDuplicateModules' && typeof result.ignoreDuplicateModules !== 'undefined') {
result.ignoreDuplicateModules = result.ignoreDuplicateModules.concat(value);
}
else if (key === 'paths' && typeof result.paths !== 'undefined') {
AMDLoader.Utilities.forEachProperty(value, (key2, value2) => result.paths[key2] = value2);
}
else if (key === 'config' && typeof result.config !== 'undefined') {
AMDLoader.Utilities.forEachProperty(value, (key2, value2) => result.config[key2] = value2);
}
else {
result[key] = AMDLoader.Utilities.recursiveClone(value);
}
});
return ConfigurationOptionsUtil.validateConfigurationOptions(result);
}
}
AMDLoader.ConfigurationOptionsUtil = ConfigurationOptionsUtil;
class Configuration {
constructor(env, options) {
this._env = env;
this.options = ConfigurationOptionsUtil.mergeConfigurationOptions(options);
this._createIgnoreDuplicateModulesMap();
this._createSortedPathsRules();
if (this.options.baseUrl === '') {
if (this.options.nodeRequire && this.options.nodeRequire.main && this.options.nodeRequire.main.filename && this._env.isNode) {
let nodeMain = this.options.nodeRequire.main.filename;
let dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\'));
this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1);
}
}
}
_createIgnoreDuplicateModulesMap() {
// Build a map out of the ignoreDuplicateModules array
this.ignoreDuplicateModulesMap = {};
for (let i = 0; i < this.options.ignoreDuplicateModules.length; i++) {
this.ignoreDuplicateModulesMap[this.options.ignoreDuplicateModules[i]] = true;
}
}
_createSortedPathsRules() {
// Create an array our of the paths rules, sorted descending by length to
// result in a more specific -> less specific order
this.sortedPathsRules = [];
AMDLoader.Utilities.forEachProperty(this.options.paths, (from, to) => {
if (!Array.isArray(to)) {
this.sortedPathsRules.push({
from: from,
to: [to]
});
}
else {
this.sortedPathsRules.push({
from: from,
to: to
});
}
});
this.sortedPathsRules.sort((a, b) => {
return b.from.length - a.from.length;
});
}
/**
* Clone current configuration and overwrite options selectively.
* @param options The selective options to overwrite with.
* @result A new configuration
*/
cloneAndMerge(options) {
return new Configuration(this._env, ConfigurationOptionsUtil.mergeConfigurationOptions(options, this.options));
}
/**
* Get current options bag. Useful for passing it forward to plugins.
*/
getOptionsLiteral() {
return this.options;
}
_applyPaths(moduleId) {
let pathRule;
for (let i = 0, len = this.sortedPathsRules.length; i < len; i++) {
pathRule = this.sortedPathsRules[i];
if (AMDLoader.Utilities.startsWith(moduleId, pathRule.from)) {
let result = [];
for (let j = 0, lenJ = pathRule.to.length; j < lenJ; j++) {
result.push(pathRule.to[j] + moduleId.substr(pathRule.from.length));
}
return result;
}
}
return [moduleId];
}
_addUrlArgsToUrl(url) {
if (AMDLoader.Utilities.containsQueryString(url)) {
return url + '&' + this.options.urlArgs;
}
else {
return url + '?' + this.options.urlArgs;
}
}
_addUrlArgsIfNecessaryToUrl(url) {
if (this.options.urlArgs) {
return this._addUrlArgsToUrl(url);
}
return url;
}
_addUrlArgsIfNecessaryToUrls(urls) {
if (this.options.urlArgs) {
for (let i = 0, len = urls.length; i < len; i++) {
urls[i] = this._addUrlArgsToUrl(urls[i]);
}
}
return urls;
}
/**
* Transform a module id to a location. Appends .js to module ids
*/
moduleIdToPaths(moduleId) {
if (this._env.isNode) {
const isNodeModule = (this.options.amdModulesPattern instanceof RegExp
&& !this.options.amdModulesPattern.test(moduleId));
if (isNodeModule) {
// This is a node module...
if (this.isBuild()) {
// ...and we are at build time, drop it
return ['empty:'];
}
else {
// ...and at runtime we create a `shortcut`-path
return ['node|' + moduleId];
}
}
}
let result = moduleId;
let results;
if (!AMDLoader.Utilities.endsWith(result, '.js') && !AMDLoader.Utilities.isAbsolutePath(result)) {
results = this._applyPaths(result);
for (let i = 0, len = results.length; i < len; i++) {
if (this.isBuild() && results[i] === 'empty:') {
continue;
}
if (!AMDLoader.Utilities.isAbsolutePath(results[i])) {
results[i] = this.options.baseUrl + results[i];
}
if (!AMDLoader.Utilities.endsWith(results[i], '.js') && !AMDLoader.Utilities.containsQueryString(results[i])) {
results[i] = results[i] + '.js';
}
}
}
else {
if (!AMDLoader.Utilities.endsWith(result, '.js') && !AMDLoader.Utilities.containsQueryString(result)) {
result = result + '.js';
}
results = [result];
}
return this._addUrlArgsIfNecessaryToUrls(results);
}
/**
* Transform a module id or url to a location.
*/
requireToUrl(url) {
let result = url;
if (!AMDLoader.Utilities.isAbsolutePath(result)) {
result = this._applyPaths(result)[0];
if (!AMDLoader.Utilities.isAbsolutePath(result)) {
result = this.options.baseUrl + result;
}
}
return this._addUrlArgsIfNecessaryToUrl(result);
}
/**
* Flag to indicate if current execution is as part of a build.
*/
isBuild() {
return this.options.isBuild;
}
shouldInvokeFactory(strModuleId) {
if (!this.options.isBuild) {
// outside of a build, all factories should be invoked
return true;
}
// during a build, only explicitly marked or anonymous modules get their factories invoked
if (AMDLoader.Utilities.isAnonymousModule(strModuleId)) {
return true;
}
if (this.options.buildForceInvokeFactory && this.options.buildForceInvokeFactory[strModuleId]) {
return true;
}
return false;
}
/**
* Test if module `moduleId` is expected to be defined multiple times
*/
isDuplicateMessageIgnoredFor(moduleId) {
return this.ignoreDuplicateModulesMap.hasOwnProperty(moduleId);
}
/**
* Get the configuration settings for the provided module id
*/
getConfigForModule(moduleId) {
if (this.options.config) {
return this.options.config[moduleId];
}
}
/**
* Should errors be caught when executing module factories?
*/
shouldCatchError() {
return this.options.catchError;
}
/**
* Should statistics be recorded?
*/
shouldRecordStats() {
return this.options.recordStats;
}
/**
* Forward an error to the error handler.
*/
onError(err) {
this.options.onError(err);
}
}
AMDLoader.Configuration = Configuration;
})(AMDLoader || (AMDLoader = {}));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var AMDLoader;
(function (AMDLoader) {
/**
* Load `scriptSrc` only once (avoid multiple <script> tags)
*/
class OnlyOnceScriptLoader {
constructor(env) {
this._env = env;
this._scriptLoader = null;
this._callbackMap = {};
}
load(moduleManager, scriptSrc, callback, errorback) {
if (!this._scriptLoader) {
if (this._env.isWebWorker) {
this._scriptLoader = new WorkerScriptLoader();
}
else if (this._env.isElectronRenderer) {
const { preferScriptTags } = moduleManager.getConfig().getOptionsLiteral();
if (preferScriptTags) {
this._scriptLoader = new BrowserScriptLoader();
}
else {
this._scriptLoader = new NodeScriptLoader(this._env);
}
}
else if (this._env.isNode) {
this._scriptLoader = new NodeScriptLoader(this._env);
}
else {
this._scriptLoader = new BrowserScriptLoader();
}
}
let scriptCallbacks = {
callback: callback,
errorback: errorback
};
if (this._callbackMap.hasOwnProperty(scriptSrc)) {
this._callbackMap[scriptSrc].push(scriptCallbacks);
return;
}
this._callbackMap[scriptSrc] = [scriptCallbacks];
this._scriptLoader.load(moduleManager, scriptSrc, () => this.triggerCallback(scriptSrc), (err) => this.triggerErrorback(scriptSrc, err));
}
triggerCallback(scriptSrc) {
let scriptCallbacks = this._callbackMap[scriptSrc];
delete this._callbackMap[scriptSrc];
for (let i = 0; i < scriptCallbacks.length; i++) {
scriptCallbacks[i].callback();
}
}
triggerErrorback(scriptSrc, err) {
let scriptCallbacks = this._callbackMap[scriptSrc];
delete this._callbackMap[scriptSrc];
for (let i = 0; i < scriptCallbacks.length; i++) {
scriptCallbacks[i].errorback(err);
}
}
}
class BrowserScriptLoader {
/**
* Attach load / error listeners to a script element and remove them when either one has fired.
* Implemented for browsers supporting HTML5 standard 'load' and 'error' events.
*/
attachListeners(script, callback, errorback) {
let unbind = () => {
script.removeEventListener('load', loadEventListener);
script.removeEventListener('error', errorEventListener);
};
let loadEventListener = (e) => {
unbind();
callback();
};
let errorEventListener = (e) => {
unbind();
errorback(e);
};
script.addEventListener('load', loadEventListener);
script.addEventListener('error', errorEventListener);
}
load(moduleManager, scriptSrc, callback, errorback) {
if (/^node\|/.test(scriptSrc)) {
let opts = moduleManager.getConfig().getOptionsLiteral();
let nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire));
let pieces = scriptSrc.split('|');
let moduleExports = null;
try {
moduleExports = nodeRequire(pieces[1]);
}
catch (err) {
errorback(err);
return;
}
moduleManager.enqueueDefineAnonymousModule([], () => moduleExports);
callback();
}
else {
let script = document.createElement('script');
script.setAttribute('async', 'async');
script.setAttribute('type', 'text/javascript');
this.attachListeners(script, callback, errorback);
const { trustedTypesPolicy } = moduleManager.getConfig().getOptionsLiteral();
if (trustedTypesPolicy) {
scriptSrc = trustedTypesPolicy.createScriptURL(scriptSrc);
}
script.setAttribute('src', scriptSrc);
// Propagate CSP nonce to dynamically created script tag.
const { cspNonce } = moduleManager.getConfig().getOptionsLiteral();
if (cspNonce) {
script.setAttribute('nonce', cspNonce);
}
document.getElementsByTagName('head')[0].appendChild(script);
}
}
}
function canUseEval(moduleManager) {
const { trustedTypesPolicy } = moduleManager.getConfig().getOptionsLiteral();
try {
const func = (trustedTypesPolicy
? self.eval(trustedTypesPolicy.createScript('', 'true')) // CodeQL [SM01632] the loader is responsible with loading code, fetch + eval is used on the web worker instead of importScripts if possible because importScripts is synchronous and we observed deadlocks on Safari
: new Function('true') // CodeQL [SM01632] the loader is responsible with loading code, fetch + eval is used on the web worker instead of importScripts if possible because importScripts is synchronous and we observed deadlocks on Safari
);
func.call(self);
return true;
}
catch (err) {
return false;
}
}
class WorkerScriptLoader {
constructor() {
this._cachedCanUseEval = null;
}
_canUseEval(moduleManager) {
if (this._cachedCanUseEval === null) {
this._cachedCanUseEval = canUseEval(moduleManager);
}
return this._cachedCanUseEval;
}
load(moduleManager, scriptSrc, callback, errorback) {
if (/^node\|/.test(scriptSrc)) {
const opts = moduleManager.getConfig().getOptionsLiteral();
const nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire));
const pieces = scriptSrc.split('|');
let moduleExports = null;
try {
moduleExports = nodeRequire(pieces[1]);
}
catch (err) {
errorback(err);
return;
}
moduleManager.enqueueDefineAnonymousModule([], function () { return moduleExports; });
callback();
}
else {
const { trustedTypesPolicy } = moduleManager.getConfig().getOptionsLiteral();
const isCrossOrigin = (/^((http:)|(https:)|(file:))/.test(scriptSrc) && scriptSrc.substring(0, self.origin.length) !== self.origin);
if (!isCrossOrigin && this._canUseEval(moduleManager)) {
// use `fetch` if possible because `importScripts`
// is synchronous and can lead to deadlocks on Safari
fetch(scriptSrc).then((response) => {
if (response.status !== 200) {
throw new Error(response.statusText);
}
return response.text();
}).then((text) => {
text = `${text}\n//# sourceURL=${scriptSrc}`;
const func = (trustedTypesPolicy
? self.eval(trustedTypesPolicy.createScript('', text)) // CodeQL [SM01632] the loader is responsible with loading code, fetch + eval is used on the web worker instead of importScripts if possible because importScripts is synchronous and we observed deadlocks on Safari
: new Function(text) // CodeQL [SM01632] the loader is responsible with loading code, fetch + eval is used on the web worker instead of importScripts if possible because importScripts is synchronous and we observed deadlocks on Safari
);
func.call(self);
callback();
}).then(undefined, errorback);
return;
}
try {
if (trustedTypesPolicy) {
scriptSrc = trustedTypesPolicy.createScriptURL(scriptSrc);
}
importScripts(scriptSrc);
callback();
}
catch (e) {
errorback(e);
}
}
}
}
class NodeScriptLoader {
constructor(env) {
this._env = env;
this._didInitialize = false;
this._didPatchNodeRequire = false;
}
_init(nodeRequire) {
if (this._didInitialize) {
return;
}
this._didInitialize = true;
// capture node modules
this._fs = nodeRequire('fs');
this._vm = nodeRequire('vm');
this._path = nodeRequire('path');
this._crypto = nodeRequire('crypto');
}
// patch require-function of nodejs such that we can manually create a script
// from cached data. this is done by overriding the `Module._compile` function
_initNodeRequire(nodeRequire, moduleManager) {
// It is important to check for `nodeCachedData` first and then set `_didPatchNodeRequire`.
// That's because `nodeCachedData` is set _after_ calling this for the first time...
const { nodeCachedData } = moduleManager.getConfig().getOptionsLiteral();
if (!nodeCachedData) {
return;
}
if (this._didPatchNodeRequire) {
return;
}
this._didPatchNodeRequire = true;
const that = this;
const Module = nodeRequire('module');
function makeRequireFunction(mod) {
const Module = mod.constructor;
let require = function require(path) {
try {
return mod.require(path);
}
finally {
// nothing
}
};
require.resolve = function resolve(request, options) {
return Module._resolveFilename(request, mod, false, options);
};
require.resolve.paths = function paths(request) {
return Module._resolveLookupPaths(request, mod);
};
require.main = process.mainModule;
require.extensions = Module._extensions;
require.cache = Module._cache;
return require;
}
Module.prototype._compile = function (content, filename) {
// remove shebang and create wrapper function
const scriptSource = Module.wrap(content.replace(/^#!.*/, ''));
// create script
const recorder = moduleManager.getRecorder();
const cachedDataPath = that._getCachedDataPath(nodeCachedData, filename);
const options = { filename };
let hashData;
try {
const data = that._fs.readFileSync(cachedDataPath);
hashData = data.slice(0, 16);
options.cachedData = data.slice(16);
recorder.record(60 /* LoaderEventType.CachedDataFound */, cachedDataPath);
}
catch (_e) {
recorder.record(61 /* LoaderEventType.CachedDataMissed */, cachedDataPath);
}
const script = new that._vm.Script(scriptSource, options);
const compileWrapper = script.runInThisContext(options);
// run script
const dirname = that._path.dirname(filename);
const require = makeRequireFunction(this);
const args = [this.exports, require, this, filename, dirname, process, _commonjsGlobal, Buffer];
const result = compileWrapper.apply(this.exports, args);
// cached data aftermath
that._handleCachedData(script, scriptSource, cachedDataPath, !options.cachedData, moduleManager);
that._verifyCachedData(script, scriptSource, cachedDataPath, hashData, moduleManager);
return result;
};
}
load(moduleManager, scriptSrc, callback, errorback) {
const opts = moduleManager.getConfig().getOptionsLiteral();
const nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire));
const nodeInstrumenter = (opts.nodeInstrumenter || function (c) { return c; });
this._init(nodeRequire);
this._initNodeRequire(nodeRequire, moduleManager);
let recorder = moduleManager.getRecorder();
if (/^node\|/.test(scriptSrc)) {
let pieces = scriptSrc.split('|');
let moduleExports = null;
try {
moduleExports = nodeRequire(pieces[1]);
}
catch (err) {
errorback(err);
return;
}
moduleManager.enqueueDefineAnonymousModule([], () => moduleExports);
callback();
}
else {
scriptSrc = AMDLoader.Utilities.fileUriToFilePath(this._env.isWindows, scriptSrc);
const normalizedScriptSrc = this._path.normalize(scriptSrc);
const vmScriptPathOrUri = this._getElectronRendererScriptPathOrUri(normalizedScriptSrc);
const wantsCachedData = Boolean(opts.nodeCachedData);
const cachedDataPath = wantsCachedData ? this._getCachedDataPath(opts.nodeCachedData, scriptSrc) : undefined;
this._readSourceAndCachedData(normalizedScriptSrc, cachedDataPath, recorder, (err, data, cachedData, hashData) => {
if (err) {
errorback(err);
return;
}
let scriptSource;
if (data.charCodeAt(0) === NodeScriptLoader._BOM) {
scriptSource = NodeScriptLoader._PREFIX + data.substring(1) + NodeScriptLoader._SUFFIX;
}
else {
scriptSource = NodeScriptLoader._PREFIX + data + NodeScriptLoader._SUFFIX;
}
scriptSource = nodeInstrumenter(scriptSource, normalizedScriptSrc);
const scriptOpts = { filename: vmScriptPathOrUri, cachedData };
const script = this._createAndEvalScript(moduleManager, scriptSource, scriptOpts, callback, errorback);
this._handleCachedData(script, scriptSource, cachedDataPath, wantsCachedData && !cachedData, moduleManager);
this._verifyCachedData(script, scriptSource, cachedDataPath, hashData, moduleManager);
});
}
}
_createAndEvalScript(moduleManager, contents, options, callback, errorback) {
const recorder = moduleManager.getRecorder();
recorder.record(31 /* LoaderEventType.NodeBeginEvaluatingScript */, options.filename);
const script = new this._vm.Script(contents, options);
const ret = script.runInThisContext(options);
const globalDefineFunc = moduleManager.getGlobalAMDDefineFunc();
let receivedDefineCall = false;
const localDefineFunc = function () {
receivedDefineCall = true;
return globalDefineFunc.apply(null, arguments);
};
localDefineFunc.amd = globalDefineFunc.amd;
ret.call(AMDLoader.global, moduleManager.getGlobalAMDRequireFunc(), localDefineFunc, options.filename, this._path.dirname(options.filename));
recorder.record(32 /* LoaderEventType.NodeEndEvaluatingScript */, options.filename);
if (receivedDefineCall) {
callback();
}
else {
errorback(new Error(`Didn't receive define call in ${options.filename}!`));
}
return script;
}
_getElectronRendererScriptPathOrUri(path) {
if (!this._env.isElectronRenderer) {
return path;
}
let driveLetterMatch = path.match(/^([a-z])\:(.*)/i);
if (driveLetterMatch) {
// windows
return `file:///${(driveLetterMatch[1].toUpperCase() + ':' + driveLetterMatch[2]).replace(/\\/g, '/')}`;
}
else {
// nix
return `file://${path}`;
}
}
_getCachedDataPath(config, filename) {
const hash = this._crypto.createHash('md5').update(filename, 'utf8').update(config.seed, 'utf8').update(process.arch, '').digest('hex');
const basename = this._path.basename(filename).replace(/\.js$/, '');
return this._path.join(config.path, `${basename}-${hash}.code`);
}
_handleCachedData(script, scriptSource, cachedDataPath, createCachedData, moduleManager) {
if (script.cachedDataRejected) {
// cached data got rejected -> delete and re-create
this._fs.unlink(cachedDataPath, err => {
moduleManager.getRecorder().record(62 /* LoaderEventType.CachedDataRejected */, cachedDataPath);
this._createAndWriteCachedData(script, scriptSource, cachedDataPath, moduleManager);
if (err) {
moduleManager.getConfig().onError(err);
}
});
}
else if (createCachedData) {
// no cached data, but wanted
this._createAndWriteCachedData(script, scriptSource, cachedDataPath, moduleManager);
}
}
// Cached data format: | SOURCE_HASH | V8_CACHED_DATA |
// -SOURCE_HASH is the md5 hash of the JS source (always 16 bytes)
// -V8_CACHED_DATA is what v8 produces
_createAndWriteCachedData(script, scriptSource, cachedDataPath, moduleManager) {
let timeout = Math.ceil(moduleManager.getConfig().getOptionsLiteral().nodeCachedData.writeDelay * (1 + Math.random()));
let lastSize = -1;
let iteration = 0;
let hashData = undefined;
const createLoop = () => {
setTimeout(() => {
if (!hashData) {
hashData = this._crypto.createHash('md5').update(scriptSource, 'utf8').digest();
}
const cachedData = script.createCachedData();
if (cachedData.length === 0 || cachedData.length === lastSize || iteration >= 5) {
// done
return;
}
if (cachedData.length < lastSize) {
// less data than before: skip, try again next round
createLoop();
return;
}
lastSize = cachedData.length;
this._fs.writeFile(cachedDataPath, Buffer.concat([hashData, cachedData]), err => {
if (err) {
moduleManager.getConfig().onError(err);
}
moduleManager.getRecorder().record(63 /* LoaderEventType.CachedDataCreated */, cachedDataPath);
createLoop();
});
}, timeout * (Math.pow(4, iteration++)));
};
// with some delay (`timeout`) create cached data
// and repeat that (with backoff delay) until the
// data seems to be not changing anymore
createLoop();
}
_readSourceAndCachedData(sourcePath, cachedDataPath, recorder, callback) {
if (!cachedDataPath) {
// no cached data case
this._fs.readFile(sourcePath, { encoding: 'utf8' }, callback);
}
else {
// cached data case: read both files in parallel
let source = undefined;
let cachedData = undefined;
let hashData = undefined;
let steps = 2;
const step = (err) => {
if (err) {
callback(err);
}
else if (--steps === 0) {
callback(undefined, source, cachedData, hashData);
}
};
this._fs.readFile(sourcePath, { encoding: 'utf8' }, (err, data) => {
source = data;
step(err);
});
this._fs.readFile(cachedDataPath, (err, data) => {
if (!err && data && data.length > 0) {
hashData = data.slice(0, 16);
cachedData = data.slice(16);
recorder.record(60 /* LoaderEventType.CachedDataFound */, cachedDataPath);
}
else {
recorder.record(61 /* LoaderEventType.CachedDataMissed */, cachedDataPath);
}
step(); // ignored: cached data is optional
});
}
}
_verifyCachedData(script, scriptSource, cachedDataPath, hashData, moduleManager) {
if (!hashData) {
// nothing to do
return;
}
if (script.cachedDataRejected) {
// invalid anyways
return;
}
setTimeout(() => {
// check source hash - the contract is that file paths change when file content
// change (e.g use the commit or version id as cache path). this check is