This repository has been archived by the owner on Feb 18, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
resolve.js
1282 lines (1171 loc) · 42.6 KB
/
resolve.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 2017-2019 Guy Bedford (http://guybedford.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const { URL } = require('url');
const fs = require('fs');
const isWindows = process.platform === 'win32';
const winSepRegEx = /\\/g;
const encodedSepRegEx = /%(2E|2F|5C)/gi;
function throwModuleNotFound (name, parent) {
const e = new Error(`Cannot find module ${name}${parent ? ` from ${parent}` : ''}`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
function throwURLName (name) {
const e = new Error(`URL ${name} is not a valid file:/// URL to resolve.`);
e.code = 'MODULE_NAME_URL_NOT_FILE';
throw e;
}
function throwInvalidModuleName (msg) {
const e = new Error(msg);
e.code = 'INVALID_MODULE_NAME';
throw e;
}
function throwInvalidConfig (msg) {
const e = new Error(msg);
e.code = 'INVALID_CONFIG';
throw e;
}
const packageRegEx = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*|@)(\/.*)?$/;
function parsePackage (specifier) {
let [, name, path = ''] = specifier.match(packageRegEx) || [];
if (path.length)
path = '.' + path;
return { name, path };
}
function parsePkgPath (path, jspmProjectPath) {
const jspmPackagesPath = jspmProjectPath + '/jspm_packages';
if (!path.startsWith(jspmPackagesPath) || path[jspmPackagesPath.length] !=='/' && path.length !== jspmPackagesPath.length)
return;
const registrySep = path.indexOf('/', jspmPackagesPath.length + 1);
if (registrySep === -1) return;
const { name } = parsePackage(path.slice(registrySep + 1));
if (!name) return;
return path.substring(jspmPackagesPath.length + 1, registrySep) + ':' + name;
}
function packageToPath (pkgName, jspmProjectPath) {
const registryIndex = pkgName.indexOf(':');
if (registryIndex === -1) throwInvalidConfig(`Invald package resolution "${pkgName}" in jspm.json.`);
return jspmProjectPath + '/jspm_packages/' + pkgName.slice(0, registryIndex) + '/' + pkgName.slice(registryIndex + 1);
}
function uriToPath (path) {
if (path.match(encodedSepRegEx))
throwInvalidModuleName(`${path} cannot be URI decoded as it contains an unsafe percent-encoding.`);
if (path.indexOf('%') !== -1)
path = decodeURIComponent(path);
if (path.indexOf('\\') !== -1)
path = path.replace(winSepRegEx, '/');
return path;
}
function tryParseUrl (url) {
try {
return new URL(url);
}
catch (e) {}
}
function pathContains (path, containsPath) {
return containsPath === path || path.startsWith(containsPath) && path[containsPath.length] === '/';
}
// path is an absolute file system path with . and .. segments to be resolved
// works only with /-separated paths
function resolvePath (path, parent) {
if (path.indexOf('\\') !== -1)
path = path.replace(winSepRegEx, '/');
if (parent && (!isWindows || !hasWinDrivePrefix(path)) && path[0] !== '/') {
if (!path.startsWith('./') && !path.startsWith('../'))
path = './' + path;
path = parent.slice(0, parent.lastIndexOf('/') + 1) + path;
}
// linked list of path segments
const headSegment = {
prev: undefined,
next: undefined,
segment: undefined
};
let curSegment = headSegment;
let segmentIndex = 0;
for (var i = 0; i < path.length; i++) {
// busy reading a segment - only terminate on '/'
if (segmentIndex !== -1) {
if (path[i] === '/') {
const nextSegment = { segment: path.substring(segmentIndex, i + 1), next: undefined, prev: curSegment };
curSegment.next = nextSegment;
curSegment = nextSegment;
segmentIndex = -1;
}
continue;
}
// new segment - check if it is relative
if (path[i] === '.') {
// ../ segment
if (path[i + 1] === '.' && path[i + 2] === '/') {
curSegment = curSegment.prev || curSegment;
curSegment.next = undefined;
i += 2;
}
// ./ segment
else if (path[i + 1] === '/') {
i += 1;
}
else {
// the start of a new segment as below
segmentIndex = i;
continue;
}
// trailing . or .. segment
if (i === path.length) {
let nextSegment = { segment: '', next: undefined, prev: curSegment };
curSegment.next = nextSegment;
curSegment = nextSegment;
}
continue;
}
// it is the start of a new segment
segmentIndex = i;
}
// finish reading out the last segment
if (segmentIndex !== -1) {
if (path[segmentIndex] === '.') {
if (path[segmentIndex + 1] === '.') {
curSegment = curSegment.prev || curSegment;
curSegment.next = undefined;
}
// not a . trailer
else if (segmentIndex + 1 !== path.length) {
const nextSegment = { segment: path.slice(segmentIndex), next: undefined, prev: curSegment };
curSegment.next = nextSegment;
}
}
else {
const nextSegment = { segment: path.slice(segmentIndex), next: undefined, prev: curSegment };
curSegment.next = nextSegment;
}
}
curSegment = headSegment;
let outStr = '';
while (curSegment = curSegment.next)
outStr += curSegment.segment;
if (!path.endsWith('/') && outStr.endsWith('/'))
outStr = outStr.slice(0, -1);
return outStr;
}
function hasWinDrivePrefix (name) {
if (name[1] !== ':')
return false;
const charCode = name.charCodeAt(0);
return charCode > 64 && charCode < 90 || charCode > 96 && charCode < 123;
}
const seenCache = new WeakMap();
function initCache (cache) {
if (cache.jspmConfigCache === undefined)
cache.jspmConfigCache = Object.create(null);
if (cache.pjsonConfigCache === undefined)
cache.pjsonConfigCache = Object.create(null);
if (cache.statCache === undefined)
cache.statCache = Object.create(null);
if (cache.symlinkCache === undefined)
cache.symlinkCache = Object.create(null);
Object.freeze(cache);
seenCache.set(cache, true);
}
const defaultEnvModule = ['module', 'default'];
const defaultEnvCjs = ['default'];
const defaultBuiltins = new Set([
'@empty',
'@empty.dew',
'assert',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'dns',
'domain',
'events',
'fs',
'http',
'http2',
'https',
'module',
'net',
'os',
'path',
'process',
'punycode',
'querystring',
'readline',
'repl',
'stream',
'string_decoder',
'sys',
'timers',
'tls',
'tty',
'url',
'util',
'vm',
'worker_threads',
'zlib'
]);
async function resolve (specifier, parentPath = process.cwd() + '/', {
builtins = defaultBuiltins,
cache = undefined,
cjsResolve = false,
env,
fs = fsUtils,
isMain = false
} = {}) {
if (!env) env = cjsResolve ? defaultEnvModule : defaultEnvCjs;
if (parentPath.indexOf('\\') !== -1)
parentPath = parentPath.replace(winSepRegEx, '/');
if (cache && seenCache.has(cache) === false)
initCache(cache);
const jspmProjectPath = await getJspmProjectPath.call(fs, parentPath, cache);
const relativeResolved = relativeResolve.call(fs, specifier, parentPath);
if (relativeResolved) {
if (cjsResolve)
return cjsFinalizeResolve.call(fs, cjsFileResolve.call(fs, relativeResolved, parentPath, cache), parentPath, jspmProjectPath, cache);
return await finalizeResolve.call(fs, relativeResolved, parentPath, jspmProjectPath, isMain, cache);
}
const parentScope = await getPackageScope.call(fs, parentPath, cache);
const parentConfig = parentScope && await readPkgConfig.call(fs, parentPath, cache);
if (parentConfig && parentConfig.map) {
const mapped = resolveMap(specifier, parentConfig.map, parentScope, parentPath, env, builtins);
if (mapped) {
if (!mapped.startsWith(parentScope + '/')) {
specifier = mapped;
}
else {
if (cjsResolve)
return cjsFinalizeResolve.call(fs, cjsFileResolve.call(fs, mapped, parentPath, cache), parentPath, jspmProjectPath, cache);
return await finalizeResolve.call(fs, mapped, parentPath, jspmProjectPath, isMain, cache);
}
}
}
if (jspmProjectPath)
return await jspmProjectResolve.call(fs, specifier, parentPath, jspmProjectPath, cjsResolve, isMain, env, builtins, cache);
else
return nodeModulesResolve.call(fs, specifier, parentPath, cjsResolve, isMain, env, builtins, cache);
}
function resolveSync (specifier, parentPath = process.cwd() + '/', {
builtins = defaultBuiltins,
cache = undefined,
cjsResolve = false,
env,
fs = fsUtils,
isMain = false
} = {}) {
if (!env) env = cjsResolve ? defaultEnvModule : defaultEnvCjs;
if (parentPath.indexOf('\\') !== -1)
parentPath = parentPath.replace(winSepRegEx, '/');
if (cache && seenCache.has(cache) === false)
initCache(cache);
const jspmProjectPath = getJspmProjectPathSync.call(fs, parentPath, cache);
const relativeResolved = relativeResolve.call(fs, specifier, parentPath);
if (relativeResolved) {
if (cjsResolve)
return cjsFinalizeResolve.call(fs, cjsFileResolve.call(fs, relativeResolved, parentPath, cache), parentPath, jspmProjectPath, cache);
return finalizeResolveSync.call(fs, relativeResolved, parentPath, jspmProjectPath, isMain, cache);
}
const parentScope = getPackageScopeSync.call(fs, parentPath, cache);
const parentConfig = parentScope && readPkgConfigSync.call(fs, parentPath, cache);
if (parentConfig && parentConfig.map) {
const mapped = resolveMap(specifier, parentConfig.map, parentScope, parentPath, env, builtins);
if (mapped) {
if (!mapped.startsWith(parentScope + '/')) {
specifier = mapped;
}
else {
if (cjsResolve)
return cjsFinalizeResolve.call(fs, cjsFileResolve.call(fs, mapped, parentPath, cache), parentPath, jspmProjectPath, cache);
return finalizeResolveSync.call(fs, mapped, parentPath, jspmProjectPath, isMain, cache);
}
}
}
if (jspmProjectPath)
return jspmProjectResolveSync.call(fs, specifier, parentPath, jspmProjectPath, cjsResolve, isMain, env, builtins, cache);
else
return nodeModulesResolve.call(fs, specifier, parentPath, cjsResolve, isMain, env, builtins, cache);
}
function relativeResolve (name, parentPath) {
if (name[0] === '/') {
name = uriToPath(name);
if (name[1] === '/') {
if (name[2] === '/')
throwInvalidModuleName(`${name} is not a valid module name.`);
else
return resolvePath(name.slice(1 + isWindows));
}
else {
let path = isWindows ? name.slice(1) : name;
if (isWindows && !hasWinDrivePrefix(path))
path = name;
return resolvePath(path);
}
}
// Relative path
else if (name[0] === '.' && (name.length === 1 || (name[1] === '/' && (name = name.slice(2), true) || name[1] === '.' && (name.length === 2 || name[2] === '/')))) {
return resolvePath(uriToPath(name), parentPath);
}
// URL
else if (name.indexOf(':') !== -1) {
if (isWindows && hasWinDrivePrefix(name)) {
return uriToPath(name);
}
else {
const url = tryParseUrl(name);
if (url.protocol === 'file:')
return uriToPath(isWindows ? url.pathname.slice(1) : url.pathname);
else
throwURLName(name);
}
}
}
async function jspmProjectResolve (specifier, parentPath, jspmProjectPath, cjsResolve, isMain, env, builtins, cache) {
const jspmConfig = await readJspmConfig.call(this, jspmProjectPath, cache);
const parentPkg = parsePkgPath(parentPath, jspmProjectPath);
const { name, path } = parsePackage(specifier);
if (!name)
throwInvalidPackageName(specifier + ' is not a valid package name, imported from ' + parentPath);
let pkgPath;
if (name === '@') {
if (parentPkg)
pkgPath = packageToPath(parentPkg, jspmProjectPath);
else if (!(pkgPath = await getPackageScope.call(this, parentPath, cache)))
throwModuleNotFound(specifier, parentPath);
}
else {
let pkgResolution;
if (parentPkg) {
const parentDeps = jspmConfig.dependencies[parentPkg];
pkgResolution = parentDeps && parentDeps.resolve && parentDeps.resolve[name] || jspmConfig.resolvePeer[name];
}
else {
pkgResolution = jspmConfig.resolve[name] || jspmConfig.resolvePeer[name];
}
if (!pkgResolution) {
if (parentPkg && name === parentPkg.substring(parentPkg.indexOf(':') + 1, parentPkg.lastIndexOf('@')))
pkgPath = packageToPath(parentPkg, jspmProjectPath);
else if (builtins.has(name))
return { resolved: name, format: 'builtin' };
else
throwModuleNotFound(specifier, parentPath);
}
pkgPath = packageToPath(pkgResolution, jspmProjectPath);
}
const pkgConfig = await readPkgConfig.call(this, pkgPath, cache);
const resolved = resolvePackage.call(this, pkgPath, path, parentPath, pkgConfig, cjsResolve, env, builtins, cache);
if (cjsResolve)
return cjsFinalizeResolve.call(this, cjsFileResolve.call(this, resolved, parentPath, cache), parentPath, jspmProjectPath, cache);
return await finalizeResolve.call(this, resolved, parentPath, jspmProjectPath, isMain, cache);
}
function jspmProjectResolveSync (specifier, parentPath, jspmProjectPath, cjsResolve, isMain, env, builtins, cache) {
const jspmConfig = readJspmConfigSync.call(this, jspmProjectPath, cache);
const parentPkg = parsePkgPath(parentPath, jspmProjectPath);
const { name, path } = parsePackage(specifier);
if (!name)
throwInvalidPackageName(specifier + ' is not a valid package name, imported from ' + parentPath);
let pkgPath;
if (name === '@') {
if (parentPkg)
pkgPath = packageToPath(parentPkg, jspmProjectPath);
else if (!(pkgPath = getPackageScopeSync.call(this, parentPath, cache)))
throwModuleNotFound(specifier, parentPath);
}
else {
let pkgResolution;
if (parentPkg) {
const parentDeps = jspmConfig.dependencies[parentPkg];
pkgResolution = parentDeps && parentDeps.resolve && parentDeps.resolve[name] || jspmConfig.resolvePeer[name];
}
else {
pkgResolution = jspmConfig.resolve[name] || jspmConfig.resolvePeer[name];
}
if (!pkgResolution) {
if (parentPkg && name === parentPkg.substring(parentPkg.indexOf(':') + 1, parentPkg.lastIndexOf('@')))
pkgPath = packageToPath(parentPkg, jspmProjectPath);
else if (builtins.has(name))
return { resolved: name, format: 'builtin' };
else
throwModuleNotFound(specifier, parentPath);
}
pkgPath = packageToPath(pkgResolution, jspmProjectPath);
}
const pkgConfig = readPkgConfigSync.call(this, pkgPath, cache);
const resolved = resolvePackage.call(this, pkgPath, path, parentPath, pkgConfig, cjsResolve, env, builtins, cache);
if (cjsResolve)
return cjsFinalizeResolve.call(this, cjsFileResolve.call(this, resolved, parentPath, cache), parentPath, jspmProjectPath, cache);
return finalizeResolveSync.call(this, resolved, parentPath, jspmProjectPath, isMain, cache);
}
function nodeModulesResolve (name, parentPath, cjsResolve, isMain, env, builtins, cache) {
if (builtins.has(name))
return { resolved: name, format: 'builtin' };
let curParentPath = parentPath;
let separatorIndex, path;
({ name, path } = parsePackage(name));
if (!name)
throwInvalidModuleName("Invalid package name '" + name + "', loaded from " + parentPath);
if (name === '@') {
const pkgPath = getPackageScopeSync.call(this, parentPath, cache);
if (!pkgPath)
throwModuleNotFound(name, parentPath);
const pkgConfig = readPkgConfigSync.call(this, pkgPath, cache);
const resolved = resolvePackage.call(this, pkgPath, path, parentPath, pkgConfig, cjsResolve, env, builtins, cache);
if (cjsResolve)
return cjsFinalizeResolve.call(this, cjsFileResolve.call(this, resolved, parentPath, cache), parentPath, undefined, cache);
return finalizeResolveSync.call(this, resolved, parentPath, undefined, isMain, cache);
}
const rootSeparatorIndex = curParentPath.indexOf('/');
while ((separatorIndex = curParentPath.lastIndexOf('/')) > rootSeparatorIndex) {
curParentPath = curParentPath.slice(0, separatorIndex);
const pkgPath = curParentPath + '/node_modules/' + name;
if (this.isDirSync(pkgPath, cache)) {
const pkgConfig = readPkgConfigSync.call(this, pkgPath, cache);
const resolved = resolvePackage.call(this, pkgPath, path, parentPath, pkgConfig, cjsResolve, env, builtins, cache);
if (cjsResolve)
return cjsFinalizeResolve.call(this, cjsFileResolve.call(this, resolved, parentPath, cache), parentPath, undefined, cache);
return finalizeResolveSync.call(this, resolved, parentPath, undefined, isMain, cache);
}
}
throwModuleNotFound(name, parentPath);
}
async function finalizeResolve (path, parentPath, jspmProjectPath, isMain, cache) {
const resolved = await this.realpath(path, jspmProjectPath ? (parsePkgPath(path, jspmProjectPath) || jspmProjectPath) : undefined, cache);
const scope = await getPackageScope.call(this, resolved, cache);
const scopeConfig = scope && await readPkgConfig.call(this, scope, cache);
if (resolved && resolved[resolved.length - 1] === '/') {
if (!(await this.isDir(resolved, cache)))
throwModuleNotFound(path, parentPath);
return { resolved, format: 'unknown' };
}
if (!resolved || !(await this.isFile(resolved, cache)))
throwModuleNotFound(path, parentPath);
if (resolved.endsWith('.mjs'))
return { resolved, format: 'module' };
if (resolved.endsWith('.node'))
return { resolved, format: 'addon' };
if (resolved.endsWith('.json'))
return { resolved, format: 'json' };
if (!isMain && !resolved.endsWith('.js'))
return { resolved, format: 'unknown' };
return { resolved, format: scopeConfig && scopeConfig.type || 'commonjs' };
}
function finalizeResolveSync (path, parentPath, jspmProjectPath, isMain, cache) {
const resolved = this.realpathSync(path, jspmProjectPath ? (parsePkgPath(path, jspmProjectPath) || jspmProjectPath) : undefined, cache);
const scope = getPackageScopeSync.call(this, resolved, cache);
const scopeConfig = scope && readPkgConfigSync.call(this, scope, cache);
if (resolved && resolved[resolved.length - 1] === '/') {
if (!(this.isDirSync(resolved, cache)))
throwModuleNotFound(path, parentPath);
return { resolved, format: 'unknown' };
}
if (!resolved || !(this.isFileSync(resolved, cache)))
throwModuleNotFound(path, parentPath);
if (resolved.endsWith('.mjs'))
return { resolved, format: 'module' };
if (resolved.endsWith('.node'))
return { resolved, format: 'addon' };
if (resolved.endsWith('.json'))
return { resolved, format: 'json' };
if (!isMain && !resolved.endsWith('.js'))
return { resolved, format: 'unknown' };
return { resolved, format: scopeConfig && scopeConfig.type || 'commonjs' };
}
function legacyFileResolve (path, cache) {
if (this.isFileSync(path, cache))
return path;
if (this.isFileSync(path + '.js', cache))
return path + '.js';
if (this.isFileSync(path + '.json', cache))
return path + '.json';
if (this.isFileSync(path + '.node', cache))
return path + '.node';
}
function legacyDirResolve (path, main, cache) {
if (!this.isDirSync(path, cache))
return;
if (main) {
const resolved = legacyFileResolve.call(this, path + '/' + main, cache);
if (resolved)
return resolved;
if (this.isFileSync(path + '/' + main + '/index.js', cache))
return path + '/' + main + '/index.js';
if (this.isFileSync(path + '/' + main + '/index.json', cache))
return path + '/' + main + '/index.json';
if (this.isFileSync(path + '/' + main + '/index.node', cache))
return path + '/' + main + '/index.node';
}
if (this.isFileSync(path + '/index.js', cache))
return path + '/index.js';
if (this.isFileSync(path + '/index.json', cache))
return path + '/index.json';
if (this.isFileSync(path + '/index.node', cache))
return path + '/index.node';
}
function cjsFileResolve (path, parentPath, cache) {
let resolved = legacyFileResolve.call(this, path, cache);
if (!resolved) {
const pjson = readPkgConfigSync.call(this, path + '/package.json', cache);
resolved = legacyDirResolve.call(this, path, pjson && pjson.entries.default, cache);
}
if (!resolved)
throwModuleNotFound(path, parentPath);
return resolved;
}
function cjsFinalizeResolve (path, parentPath, jspmProjectPath, cache) {
const resolved = this.realpathSync(path, jspmProjectPath ? (parsePkgPath(path) || jspmProjectPath) : undefined, cache);
const scope = getPackageScopeSync.call(this, resolved, cache);
const scopeConfig = scope && readPkgConfigSync.call(this, scope, cache);
if (resolved.endsWith('.mjs') || resolved.endsWith('.js') && scopeConfig && scopeConfig.type === 'module') {
throwInvalidModuleName(`Cannot load ES module ${resolved} from CommonJS module ${parentPath}.`);
}
if (resolved.endsWith('.json'))
return { resolved, format: 'json' };
if (resolved.endsWith('.node'))
return { resolved, format: 'addon' };
return { resolved, format: 'commonjs' };
}
async function getJspmProjectPath (modulePath, cache) {
let basePackagePath;
const jspmPackagesIndex = modulePath.lastIndexOf('/jspm_packages/');
if (jspmPackagesIndex !== -1 && modulePath.lastIndexOf('/node_modules/', jspmPackagesIndex) === -1) {
const baseProjectPath = modulePath.slice(0, jspmPackagesIndex);
const pkgName = parsePkgPath(modulePath, baseProjectPath);
basePackagePath = pkgName && packageToPath(pkgName, baseProjectPath);
}
let separatorIndex = modulePath.lastIndexOf('/');
const rootSeparatorIndex = modulePath.indexOf('/');
do {
const dir = modulePath.slice(0, separatorIndex);
if (dir.endsWith('/node_modules'))
return;
if (dir !== basePackagePath && await this.isFile(dir + '/jspm.json', cache))
return dir;
separatorIndex = modulePath.lastIndexOf('/', separatorIndex - 1);
}
while (separatorIndex > rootSeparatorIndex);
}
function getJspmProjectPathSync (modulePath, cache) {
let basePackagePath;
const jspmPackagesIndex = modulePath.lastIndexOf('/jspm_packages/');
if (jspmPackagesIndex !== -1 && modulePath.lastIndexOf('/node_modules/', jspmPackagesIndex) === -1) {
const baseProjectPath = modulePath.slice(0, jspmPackagesIndex);
const pkgName = parsePkgPath(modulePath, baseProjectPath);
basePackagePath = pkgName && packageToPath(pkgName, baseProjectPath);
}
let separatorIndex = modulePath.lastIndexOf('/');
const rootSeparatorIndex = modulePath.indexOf('/');
do {
const dir = modulePath.slice(0, separatorIndex);
if (dir.endsWith('/node_modules'))
return;
if (dir !== basePackagePath && this.isFileSync(dir + '/jspm.json', cache))
return dir;
separatorIndex = modulePath.lastIndexOf('/', separatorIndex - 1);
}
while (separatorIndex > rootSeparatorIndex);
}
async function getPackageScope (resolved, cache) {
const rootSeparatorIndex = resolved.indexOf('/');
let separatorIndex;
while ((separatorIndex = resolved.lastIndexOf('/')) > rootSeparatorIndex) {
resolved = resolved.slice(0, separatorIndex);
if (resolved.endsWith('/node_modules') || resolved.endsWith('/jspm_packages'))
return;
if (await this.stat(resolved + '/package.json', cache))
return resolved;
}
}
function getPackageScopeSync (resolved, cache) {
const rootSeparatorIndex = resolved.indexOf('/');
let separatorIndex;
while ((separatorIndex = resolved.lastIndexOf('/')) > rootSeparatorIndex) {
resolved = resolved.slice(0, separatorIndex);
if (resolved.endsWith('/node_modules') || resolved.endsWith('/jspm_packages'))
return;
if (this.statSync(resolved + '/package.json', cache))
return resolved;
}
}
async function readJspmConfig (jspmProjectPath, cache) {
if (cache) {
const cached = cache.jspmConfigCache[jspmProjectPath];
if (cached)
return cached;
}
let source;
try {
source = await this.readFile(jspmProjectPath + '/jspm.json', cache);
}
catch (e) {
if (e.code === 'ENOENT') {
throwInvalidConfig(`Unable to resolve in jspm project as jspm.json does not exist in ${jspmProjectPath}`);
}
throw e;
}
let parsed;
try {
parsed = JSON.parse(source);
}
catch (e) {
e.stack = `Unable to parse JSON file ${jspmProjectPath}/jspm.json\n${e.stack}`;
e.code = 'INVALID_CONFIG';
throw e;
}
if (!parsed.resolve)
parsed.resolve = Object.create(null);
if (!parsed.resolvePeer)
parsed.resolvePeer = Object.create(null);
if (!parsed.dependencies)
parsed.dependencies = Object.create(null);
if (cache)
cache.jspmConfigCache[jspmProjectPath] = parsed;
return parsed;
}
function readJspmConfigSync (jspmProjectPath, cache) {
if (cache) {
const cached = cache.jspmConfigCache[jspmProjectPath];
if (cached)
return cached;
}
let source;
try {
source = this.readFileSync(jspmProjectPath + '/jspm.json', cache);
}
catch (e) {
if (e.code === 'ENOENT') {
throwInvalidConfig(`Unable to resolve in jspm project as jspm.json does not exist in ${jspmProjectPath}`);
}
throw e;
}
let parsed;
try {
parsed = JSON.parse(source);
}
catch (e) {
e.stack = `Unable to parse JSON file ${jspmProjectPath}/jspm.json\n${e.stack}`;
e.code = 'INVALID_CONFIG';
throw e;
}
if (!parsed.resolve)
parsed.resolve = Object.create(null);
if (!parsed.resolvePeer)
parsed.resolvePeer = Object.create(null);
if (!parsed.dependencies)
parsed.dependencies = Object.create(null);
if (cache)
cache.jspmConfigCache[jspmProjectPath] = parsed;
return parsed;
}
async function readPkgConfig (pkgPath, cache) {
if (cache) {
const cached = cache.pjsonConfigCache[pkgPath];
if (cached !== undefined)
return cached;
}
let source;
try {
source = await this.readFile(pkgPath + '/package.json', cache);
}
catch (e) {
if (e.code === 'ENOENT' || e.code === 'EISDIR') {
if (cache) {
if (e.code === 'ENOENT') {
cache.pjsonConfigCache[pkgPath] = null;
cache.statCache[pkgPath + '/package.json'] = null;
}
}
return null;
}
throw e;
}
let pjson;
try {
pjson = JSON.parse(source);
}
catch (e) {
e.stack = `Unable to parse JSON file ${pkgPath}/package.json\n${e.stack}`;
e.code = 'INVALID_CONFIG';
throw e;
}
const processed = processPkgConfig(pjson);
if (cache)
cache.pjsonConfigCache[pkgPath] = processed;
return processed;
}
function readPkgConfigSync (pkgPath, cache) {
if (cache) {
const cached = cache.pjsonConfigCache[pkgPath];
if (cached !== undefined)
return cached;
}
let source;
try {
source = this.readFileSync(pkgPath + '/package.json', cache);
}
catch (e) {
if (e.code === 'ENOENT' || e.code === 'EISDIR') {
if (cache) {
if (e.code === 'ENOENT') {
cache.pjsonConfigCache[pkgPath] = null;
cache.statCache[pkgPath + '/package.json'] = null;
}
}
return null;
}
throw e;
}
let pjson;
try {
pjson = JSON.parse(source);
}
catch (e) {
e.stack = `Unable to parse JSON file ${pkgPath}/package.json\n${e.stack}`;
e.code = 'INVALID_CONFIG';
throw e;
}
const processed = processPkgConfig(pjson);
if (cache)
cache.pjsonConfigCache[pkgPath] = processed;
return processed;
}
const fsUtils = {
async isFile (path, cache) {
const stats = await this.stat(path, cache);
return stats && stats.isFile();
},
isFileSync (path, cache) {
const stats = this.statSync(path, cache);
return stats && stats.isFile();
},
async isDir (path, cache) {
const stats = await this.stat(path, cache);
return stats && stats.isDirectory();
},
isDirSync (path, cache) {
const stats = this.statSync(path, cache);
return stats && stats.isDirectory();
},
async stat (path, cache) {
if (cache) {
const cached = cache.statCache[path];
if (cached !== undefined)
return cached;
}
try {
var stats = await new Promise((resolve, reject) => fs.stat(path, (err, stats) => err ? reject(err) : resolve(stats)));
}
catch (e) {
if (e.code === 'ENOENT' || e.code === 'ENOTDIR') {
if (cache)
cache.statCache[path] = null;
return null;
}
throw e;
}
if (cache)
cache.statCache[path] = stats;
return stats;
},
statSync (path, cache) {
const cached = cache && cache.statCache[path];
if (cached !== undefined)
return cache.statCache[path];
try {
var stats = fs.statSync(path);
}
catch (e) {
if (e.code === 'ENOENT' || e.code === 'ENOTDIR') {
if (cache)
cache.statCache[path] = null;
return null;
}
throw e;
}
if (cache)
cache.statCache[path] = stats;
return stats;
},
async realpath (path, realpathBase = path.slice(0, path.indexOf('/')), cache, seen = new Set()) {
const trailingSlash = path[path.length - 1] === '/';
if (trailingSlash)
path = path.slice(0, -1);
if (seen.has(path))
throw new Error('Recursive symlink resolving ' + path);
seen.add(path);
const symlink = await this.readlink(path, cache);
if (symlink) {
const resolved = resolvePath(symlink, path);
if (realpathBase && !pathContains(realpathBase, resolved))
return path + (trailingSlash ? '/' : '');
return this.realpath(resolved + (trailingSlash ? '/' : ''), realpathBase, cache, seen);
}
else {
const parent = resolvePath('.', path);
if (realpathBase && !pathContains(realpathBase, parent))
return path + (trailingSlash ? '/' : '');
return (await this.realpath(parent, realpathBase, cache, seen)) + path.slice(parent.length) + (trailingSlash ? '/' : '');
}
},
realpathSync (path, realpathBase = path.slice(0, path.indexOf('/')), cache, seen = new Set()) {
const trailingSlash = path[path.length - 1] === '/';
if (trailingSlash)
path = path.slice(0, -1);
if (seen.has(path))
throw new Error('Recursive symlink resolving ' + path);
seen.add(path);
const symlink = this.readlinkSync(path, cache);
if (symlink) {
const resolved = resolvePath(symlink, path);
if (realpathBase && !pathContains(realpathBase, resolved))
return path + (trailingSlash ? '/' : '');
return this.realpathSync(resolved + (trailingSlash ? '/' : ''), realpathBase, cache, seen);
}
else {
const parent = resolvePath('.', path);
if (realpathBase && !pathContains(realpathBase, parent))
return path + (trailingSlash ? '/' : '');
return this.realpathSync(parent, parent, cache, seen) + path.slice(parent.length) + (trailingSlash ? '/' : '');
}
},
async readlink (path, cache) {
if (cache) {
const cached = cache.symlinkCache[path];
if (cached !== undefined)
return cached;
}
try {
const fsLink = await new Promise((resolve, reject) => fs.readlink(path, (err, link) => err ? reject(err) : resolve(link)));
const link = resolvePath(fsLink, path);
if (cache) {
cache.symlinkCache[path] = link;
const stats = cache.statCache[path];
if (stats)
cache.statCache[link] = stats;
}
return link;
}
catch (e) {
if (e.code !== 'EINVAL' && e.code !== 'ENOENT' && e.code !== 'UNKNOWN')
throw e;
if (cache)
cache.symlinkCache[path] = null;
return null;
}
},
readlinkSync (path, cache) {
if (cache) {
const cached = cache.symlinkCache[path];
if (cached !== undefined)
return cached;
}
try {
const link = resolvePath(fs.readlinkSync(path), path);
if (cache) {
cache.symlinkCache[path] = link;
const stats = cache.statCache[path];
if (stats)
cache.statCache.set(link, stats);
}
return link;
}
catch (e) {
if (e.code !== 'EINVAL' && e.code !== 'ENOENT' && e.code !== 'UNKNOWN')
throw e;
if (cache)
cache.symlinkCache[path] = null;
return null;
}
},
readFile (path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, source) => err ? reject(err) : resolve(source.toString()));
});
},
readFileSync (path) {
return fs.readFileSync(path);
}
};
resolve.sync = resolveSync;
resolve.builtins = Object.freeze([...defaultBuiltins]);
const winPathRegEx = /^[a-z]:\//i;
resolve.cjsResolve = function (request, parent) {
if (request.match(winPathRegEx))
request = '/' + request;
if (request.endsWith('/'))
request = request.slice(0, request.length - 1);
return resolveSync(request, parent && parent.filename, { cjsResolve: true, cache: parent && parent.cache }).resolved;