-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
loader.js
1880 lines (1695 loc) Β· 60 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 Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const {
ArrayIsArray,
ArrayPrototypeFilter,
ArrayPrototypeIncludes,
ArrayPrototypeIndexOf,
ArrayPrototypeJoin,
ArrayPrototypeMap,
ArrayPrototypePush,
ArrayPrototypePushApply,
ArrayPrototypeSlice,
ArrayPrototypeSplice,
ArrayPrototypeUnshift,
ArrayPrototypeUnshiftApply,
Boolean,
Error,
JSONParse,
ObjectDefineProperty,
ObjectFreeze,
ObjectGetOwnPropertyDescriptor,
ObjectGetPrototypeOf,
ObjectHasOwn,
ObjectKeys,
ObjectPrototype,
ObjectPrototypeHasOwnProperty,
ObjectSetPrototypeOf,
Proxy,
ReflectApply,
ReflectSet,
RegExpPrototypeExec,
SafeMap,
String,
StringPrototypeCharAt,
StringPrototypeCharCodeAt,
StringPrototypeEndsWith,
StringPrototypeIndexOf,
StringPrototypeRepeat,
StringPrototypeSlice,
StringPrototypeSplit,
StringPrototypeStartsWith,
Symbol,
} = primordials;
const {
privateSymbols: {
module_source_private_symbol,
module_export_names_private_symbol,
module_circular_visited_private_symbol,
module_export_private_symbol,
module_parent_private_symbol,
},
isInsideNodeModules,
} = internalBinding('util');
const { kEvaluated, createRequiredModuleFacade } = internalBinding('module_wrap');
// Internal properties for Module instances.
/**
* Cached {@link Module} source string.
*/
const kModuleSource = module_source_private_symbol;
/**
* Cached {@link Module} export names for ESM loader.
*/
const kModuleExportNames = module_export_names_private_symbol;
/**
* {@link Module} circular dependency visited flag.
*/
const kModuleCircularVisited = module_circular_visited_private_symbol;
/**
* {@link Module} export object snapshot for ESM loader.
*/
const kModuleExport = module_export_private_symbol;
/**
* {@link Module} parent module.
*/
const kModuleParent = module_parent_private_symbol;
const kIsMainSymbol = Symbol('kIsMainSymbol');
const kIsCachedByESMLoader = Symbol('kIsCachedByESMLoader');
const kRequiredModuleSymbol = Symbol('kRequiredModuleSymbol');
const kIsExecuting = Symbol('kIsExecuting');
const kFormat = Symbol('kFormat');
// Set first due to cycle with ESM loader functions.
module.exports = {
kModuleSource,
kModuleExport,
kModuleExportNames,
kModuleCircularVisited,
initializeCJS,
Module,
wrapSafe,
wrapModuleLoad,
kIsMainSymbol,
kIsCachedByESMLoader,
kRequiredModuleSymbol,
kIsExecuting,
};
const { BuiltinModule } = require('internal/bootstrap/realm');
const {
maybeCacheSourceMap,
} = require('internal/source_map/source_map_cache');
const { pathToFileURL, fileURLToPath, isURL } = require('internal/url');
const {
pendingDeprecate,
emitExperimentalWarning,
kEmptyObject,
setOwnProperty,
getLazy,
isWindows,
isUnderNodeModules,
} = require('internal/util');
const {
makeContextifyScript,
runScriptInThisContext,
} = require('internal/vm');
const {
containsModuleSyntax,
compileFunctionForCJSLoader,
} = internalBinding('contextify');
const assert = require('internal/assert');
const fs = require('fs');
const path = require('path');
const internalFsBinding = internalBinding('fs');
const { safeGetenv } = internalBinding('credentials');
const {
getCjsConditions,
initializeCjsConditions,
loadBuiltinModule,
makeRequireFunction,
setHasStartedUserCJSExecution,
stripBOM,
toRealPath,
} = require('internal/modules/helpers');
const { stripTypeScriptModuleTypes } = require('internal/modules/typescript');
const packageJsonReader = require('internal/modules/package_json_reader');
const { getOptionValue, getEmbedderOptions } = require('internal/options');
const shouldReportRequiredModules = getLazy(() => process.env.WATCH_REPORT_DEPENDENCIES);
const {
vm_dynamic_import_default_internal,
} = internalBinding('symbols');
const {
codes: {
ERR_INVALID_ARG_VALUE,
ERR_INVALID_MODULE_SPECIFIER,
ERR_REQUIRE_CYCLE_MODULE,
ERR_REQUIRE_ESM,
ERR_UNKNOWN_BUILTIN_MODULE,
},
setArrowMessage,
} = require('internal/errors');
const { validateString } = require('internal/validators');
const {
CHAR_BACKWARD_SLASH,
CHAR_COLON,
CHAR_DOT,
CHAR_FORWARD_SLASH,
} = require('internal/constants');
const {
isProxy,
} = require('internal/util/types');
const { debuglog, debugWithTimer } = require('internal/util/debuglog');
let { startTimer, endTimer } = debugWithTimer('module_timer', (start, end) => {
startTimer = start;
endTimer = end;
});
const { tracingChannel } = require('diagnostics_channel');
const onRequire = getLazy(() => tracingChannel('module.require'));
const relativeResolveCache = { __proto__: null };
let requireDepth = 0;
let isPreloading = false;
let statCache = null;
/**
* Internal method to add tracing capabilities for Module._load.
*
* See more {@link Module._load}
*/
function wrapModuleLoad(request, parent, isMain) {
const logLabel = `[${parent?.id || ''}] [${request}]`;
const traceLabel = `require('${request}')`;
startTimer(logLabel, traceLabel);
try {
return onRequire().traceSync(Module._load, {
__proto__: null,
parentFilename: parent?.filename,
id: request,
}, Module, request, parent, isMain);
} finally {
endTimer(logLabel, traceLabel);
}
}
/**
* Get a path's properties, using an in-memory cache to minimize lookups.
* @param {string} filename Absolute path to the file
*/
function stat(filename) {
filename = path.toNamespacedPath(filename);
if (statCache !== null) {
const result = statCache.get(filename);
if (result !== undefined) { return result; }
}
const result = internalFsBinding.internalModuleStat(internalFsBinding, filename);
if (statCache !== null && result >= 0) {
// Only set cache when `internalModuleStat(internalFsBinding, filename)` succeeds.
statCache.set(filename, result);
}
return result;
}
let _stat = stat;
ObjectDefineProperty(Module, '_stat', {
__proto__: null,
get() { return _stat; },
set(stat) {
emitExperimentalWarning('Module._stat');
_stat = stat;
return true;
},
configurable: true,
});
/**
* Update the parent's children array with the child module.
* @param {Module} parent Module requiring the children
* @param {Module} child Module being required
* @param {boolean} scan Add the child to the parent's children if not already present
*/
function updateChildren(parent, child, scan) {
const children = parent?.children;
if (children && !(scan && ArrayPrototypeIncludes(children, child))) {
ArrayPrototypePush(children, child);
}
}
/**
* Tell the watch mode that a module was required.
* @param {string} filename Absolute path of the module
*/
function reportModuleToWatchMode(filename) {
if (shouldReportRequiredModules() && process.send) {
process.send({ 'watch:require': [filename] });
}
}
/**
* Tell the watch mode that a module was not found.
* @param {string} basePath The absolute path that errored
* @param {string[]} extensions The extensions that were tried
*/
function reportModuleNotFoundToWatchMode(basePath, extensions) {
if (shouldReportRequiredModules() && process.send) {
process.send({ 'watch:require': ArrayPrototypeMap(extensions, (ext) => path.resolve(`${basePath}${ext}`)) });
}
}
/**
* Create a new module instance.
* @param {string} id
* @param {Module} parent
*/
function Module(id = '', parent) {
this.id = id;
this.path = path.dirname(id);
setOwnProperty(this, 'exports', {});
this[kModuleParent] = parent;
updateChildren(parent, this, false);
this.filename = null;
this.loaded = false;
this.children = [];
}
/** @type {Record<string, Module>} */
Module._cache = { __proto__: null };
/** @type {Record<string, string>} */
Module._pathCache = { __proto__: null };
/** @type {Record<string, (module: Module, filename: string) => void>} */
Module._extensions = { __proto__: null };
/** @type {string[]} */
let modulePaths = [];
/** @type {string[]} */
Module.globalPaths = [];
let patched = false;
/**
* Add the CommonJS wrapper around a module's source code.
* @param {string} script Module source code
*/
let wrap = function(script) { // eslint-disable-line func-style
return Module.wrapper[0] + script + Module.wrapper[1];
};
const wrapper = [
'(function (exports, require, module, __filename, __dirname) { ',
'\n});',
];
let wrapperProxy = new Proxy(wrapper, {
__proto__: null,
set(target, property, value, receiver) {
patched = true;
return ReflectSet(target, property, value, receiver);
},
defineProperty(target, property, descriptor) {
patched = true;
return ObjectDefineProperty(target, property, descriptor);
},
});
ObjectDefineProperty(Module, 'wrap', {
__proto__: null,
get() {
return wrap;
},
set(value) {
patched = true;
wrap = value;
},
});
ObjectDefineProperty(Module, 'wrapper', {
__proto__: null,
get() {
return wrapperProxy;
},
set(value) {
patched = true;
wrapperProxy = value;
},
});
const isPreloadingDesc = { get() { return isPreloading; } };
ObjectDefineProperty(Module.prototype, 'isPreloading', isPreloadingDesc);
ObjectDefineProperty(BuiltinModule.prototype, 'isPreloading', isPreloadingDesc);
/**
* Get the parent of the current module from our cache.
* @this {Module}
*/
function getModuleParent() {
return this[kModuleParent];
}
/**
* Set the parent of the current module in our cache.
* @this {Module}
* @param {Module} value
*/
function setModuleParent(value) {
this[kModuleParent] = value;
}
let debug = debuglog('module', (fn) => {
debug = fn;
});
ObjectDefineProperty(Module.prototype, 'parent', {
__proto__: null,
get: pendingDeprecate(
getModuleParent,
'module.parent is deprecated due to accuracy issues. Please use ' +
'require.main to find program entry point instead.',
'DEP0144',
),
set: pendingDeprecate(
setModuleParent,
'module.parent is deprecated due to accuracy issues. Please use ' +
'require.main to find program entry point instead.',
'DEP0144',
),
});
Module._debug = pendingDeprecate(debug, 'Module._debug is deprecated.', 'DEP0077');
Module.isBuiltin = BuiltinModule.isBuiltin;
/**
* Prepare to run CommonJS code.
* This function is called during pre-execution, before any user code is run.
*/
function initializeCJS() {
// This need to be done at runtime in case --expose-internals is set.
const builtinModules = BuiltinModule.getCanBeRequiredByUsersWithoutSchemeList();
Module.builtinModules = ObjectFreeze(builtinModules);
initializeCjsConditions();
if (!getEmbedderOptions().noGlobalSearchPaths) {
Module._initPaths();
}
// TODO(joyeecheung): deprecate this in favor of a proper hook?
Module.runMain =
require('internal/modules/run_main').executeUserEntryPoint;
const tsEnabled = getOptionValue('--experimental-strip-types');
if (tsEnabled) {
emitExperimentalWarning('Type Stripping');
Module._extensions['.cts'] = loadCTS;
Module._extensions['.ts'] = loadTS;
}
if (getOptionValue('--experimental-require-module')) {
if (tsEnabled) {
Module._extensions['.mts'] = loadMTS;
}
}
}
// Given a module name, and a list of paths to test, returns the first
// matching file in the following precedence.
//
// require("a.<ext>")
// -> a.<ext>
//
// require("a")
// -> a
// -> a.<ext>
// -> a/index.<ext>
let _readPackage = packageJsonReader.readPackage;
ObjectDefineProperty(Module, '_readPackage', {
__proto__: null,
get() { return _readPackage; },
set(readPackage) {
emitExperimentalWarning('Module._readPackage');
_readPackage = readPackage;
return true;
},
configurable: true,
});
/**
* Try to load a specifier as a package.
* @param {string} requestPath The path to what we are trying to load
* @param {string[]} exts File extensions to try appending in order to resolve the file
* @param {boolean} isMain Whether the file is the main entry point of the app
* @param {string} originalPath The specifier passed to `require`
*/
function tryPackage(requestPath, exts, isMain, originalPath) {
const { main: pkg, pjsonPath } = _readPackage(requestPath);
if (!pkg) {
return tryExtensions(path.resolve(requestPath, 'index'), exts, isMain);
}
const filename = path.resolve(requestPath, pkg);
let actual = tryFile(filename, isMain) ||
tryExtensions(filename, exts, isMain) ||
tryExtensions(path.resolve(filename, 'index'), exts, isMain);
if (actual === false) {
actual = tryExtensions(path.resolve(requestPath, 'index'), exts, isMain);
if (!actual) {
// eslint-disable-next-line no-restricted-syntax
const err = new Error(
`Cannot find module '${filename}'. ` +
'Please verify that the package.json has a valid "main" entry',
);
err.code = 'MODULE_NOT_FOUND';
err.path = pjsonPath;
err.requestPath = originalPath;
// TODO(BridgeAR): Add the requireStack as well.
throw err;
} else {
process.emitWarning(
`Invalid 'main' field in '${pjsonPath}' of '${pkg}'. ` +
'Please either fix that or report it to the module author',
'DeprecationWarning',
'DEP0128',
);
}
}
return actual;
}
/**
* Check if the file exists and is not a directory if using `--preserve-symlinks` and `isMain` is false or
* `--preserve-symlinks-main` and `isMain` is true , keep symlinks intact, otherwise resolve to the absolute realpath.
* @param {string} requestPath The path to the file to load.
* @param {boolean} isMain Whether the file is the main module.
*/
function tryFile(requestPath, isMain) {
const rc = _stat(requestPath);
if (rc !== 0) { return; }
if (getOptionValue(isMain ? '--preserve-symlinks-main' : '--preserve-symlinks')) {
return path.resolve(requestPath);
}
return toRealPath(requestPath);
}
/**
* Given a path, check if the file exists with any of the set extensions.
* @param {string} basePath The path and filename without extension
* @param {string[]} exts The extensions to try
* @param {boolean} isMain Whether the module is the main module
*/
function tryExtensions(basePath, exts, isMain) {
for (let i = 0; i < exts.length; i++) {
const filename = tryFile(basePath + exts[i], isMain);
if (filename) {
return filename;
}
}
return false;
}
/**
* Find the longest (possibly multi-dot) extension registered in `Module._extensions`.
* @param {string} filename The filename to find the longest registered extension for.
*/
function findLongestRegisteredExtension(filename) {
const name = path.basename(filename);
let currentExtension;
let index;
let startIndex = 0;
while ((index = StringPrototypeIndexOf(name, '.', startIndex)) !== -1) {
startIndex = index + 1;
if (index === 0) { continue; } // Skip dotfiles like .gitignore
currentExtension = StringPrototypeSlice(name, index);
if (Module._extensions[currentExtension]) { return currentExtension; }
}
return '.js';
}
/**
* Tries to get the absolute file path of the parent module.
* @param {Module} parent The parent module object.
*/
function trySelfParentPath(parent) {
if (!parent) { return false; }
if (parent.filename) {
return parent.filename;
} else if (parent.id === '<repl>' || parent.id === 'internal/preload') {
try {
return process.cwd() + path.sep;
} catch {
return false;
}
}
}
/**
* Attempt to resolve a module request using the parent module package metadata.
* @param {string} parentPath The path of the parent module
* @param {string} request The module request to resolve
*/
function trySelf(parentPath, request) {
if (!parentPath) { return false; }
const pkg = packageJsonReader.getNearestParentPackageJSON(parentPath);
if (pkg?.data.exports === undefined || pkg.data.name === undefined) {
return false;
}
let expansion;
if (request === pkg.data.name) {
expansion = '.';
} else if (StringPrototypeStartsWith(request, `${pkg.data.name}/`)) {
expansion = '.' + StringPrototypeSlice(request, pkg.data.name.length);
} else {
return false;
}
try {
const { packageExportsResolve } = require('internal/modules/esm/resolve');
return finalizeEsmResolution(packageExportsResolve(
pathToFileURL(pkg.path), expansion, pkg.data,
pathToFileURL(parentPath), getCjsConditions()), parentPath, pkg.path);
} catch (e) {
if (e.code === 'ERR_MODULE_NOT_FOUND') {
throw createEsmNotFoundErr(request, pkg.path);
}
throw e;
}
}
/**
* This only applies to requests of a specific form:
* 1. `name/.*`
* 2. `@scope/name/.*`
*/
const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/;
/**
* Resolves the exports for a given module path and request.
* @param {string} nmPath The path to the module.
* @param {string} request The request for the module.
*/
function resolveExports(nmPath, request) {
// The implementation's behavior is meant to mirror resolution in ESM.
const { 1: name, 2: expansion = '' } =
RegExpPrototypeExec(EXPORTS_PATTERN, request) || kEmptyObject;
if (!name) { return; }
const pkgPath = path.resolve(nmPath, name);
const pkg = _readPackage(pkgPath);
if (pkg.exists && pkg.exports != null) {
try {
const { packageExportsResolve } = require('internal/modules/esm/resolve');
return finalizeEsmResolution(packageExportsResolve(
pathToFileURL(pkgPath + '/package.json'), '.' + expansion, pkg, null,
getCjsConditions()), null, pkgPath);
} catch (e) {
if (e.code === 'ERR_MODULE_NOT_FOUND') {
throw createEsmNotFoundErr(request, pkgPath + '/package.json');
}
throw e;
}
}
}
// We don't cache this in case user extends the extensions.
function getDefaultExtensions() {
let extensions = ObjectKeys(Module._extensions);
const tsEnabled = getOptionValue('--experimental-strip-types');
if (tsEnabled) {
// remove .ts and .cts from the default extensions
// to avoid extensionless require of .ts and .cts files.
extensions = ArrayPrototypeFilter(extensions, (ext) =>
(ext !== '.ts' || Module._extensions['.ts'] !== loadTS) &&
(ext !== '.cts' || Module._extensions['.cts'] !== loadCTS),
);
}
if (!getOptionValue('--experimental-require-module')) {
return extensions;
}
if (tsEnabled) {
extensions = ArrayPrototypeFilter(extensions, (ext) =>
ext !== '.mts' || Module._extensions['.mts'] !== loadMTS,
);
}
return extensions;
}
/**
* Get the absolute path to a module.
* @param {string} request Relative or absolute file path
* @param {Array<string>} paths Folders to search as file paths
* @param {boolean} isMain Whether the request is the main app entry point
* @returns {string | false}
*/
Module._findPath = function(request, paths, isMain) {
const absoluteRequest = path.isAbsolute(request);
if (absoluteRequest) {
paths = [''];
} else if (!paths || paths.length === 0) {
return false;
}
const cacheKey = request + '\x00' + ArrayPrototypeJoin(paths, '\x00');
const entry = Module._pathCache[cacheKey];
if (entry) {
return entry;
}
let exts;
const trailingSlash = request.length > 0 &&
(StringPrototypeCharCodeAt(request, request.length - 1) === CHAR_FORWARD_SLASH || (
StringPrototypeCharCodeAt(request, request.length - 1) === CHAR_DOT &&
(
request.length === 1 ||
StringPrototypeCharCodeAt(request, request.length - 2) === CHAR_FORWARD_SLASH ||
(StringPrototypeCharCodeAt(request, request.length - 2) === CHAR_DOT && (
request.length === 2 ||
StringPrototypeCharCodeAt(request, request.length - 3) === CHAR_FORWARD_SLASH
))
)
));
const isRelative = StringPrototypeCharCodeAt(request, 0) === CHAR_DOT &&
(
request.length === 1 ||
StringPrototypeCharCodeAt(request, 1) === CHAR_FORWARD_SLASH ||
(isWindows && StringPrototypeCharCodeAt(request, 1) === CHAR_BACKWARD_SLASH) ||
(StringPrototypeCharCodeAt(request, 1) === CHAR_DOT && ((
request.length === 2 ||
StringPrototypeCharCodeAt(request, 2) === CHAR_FORWARD_SLASH) ||
(isWindows && StringPrototypeCharCodeAt(request, 2) === CHAR_BACKWARD_SLASH)))
);
let insidePath = true;
if (isRelative) {
const normalizedRequest = path.normalize(request);
if (StringPrototypeStartsWith(normalizedRequest, '..')) {
insidePath = false;
}
}
// For each path
for (let i = 0; i < paths.length; i++) {
// Don't search further if path doesn't exist
const curPath = paths[i];
if (insidePath && curPath && _stat(curPath) < 1) {
continue;
}
if (!absoluteRequest) {
const exportsResolved = resolveExports(curPath, request);
if (exportsResolved) {
return exportsResolved;
}
}
const basePath = path.resolve(curPath, request);
let filename;
const rc = _stat(basePath);
if (!trailingSlash) {
if (rc === 0) { // File.
if (!isMain) {
if (getOptionValue('--preserve-symlinks')) {
filename = path.resolve(basePath);
} else {
filename = toRealPath(basePath);
}
} else if (getOptionValue('--preserve-symlinks-main')) {
// For the main module, we use the --preserve-symlinks-main flag instead
// mainly for backward compatibility, as the preserveSymlinks flag
// historically has not applied to the main module. Most likely this
// was intended to keep .bin/ binaries working, as following those
// symlinks is usually required for the imports in the corresponding
// files to resolve; that said, in some use cases following symlinks
// causes bigger problems which is why the --preserve-symlinks-main option
// is needed.
filename = path.resolve(basePath);
} else {
filename = toRealPath(basePath);
}
}
if (!filename) {
// Try it with each of the extensions
if (exts === undefined) {
exts = getDefaultExtensions();
}
filename = tryExtensions(basePath, exts, isMain);
}
}
if (!filename && rc === 1) { // Directory.
// try it with each of the extensions at "index"
if (exts === undefined) {
exts = getDefaultExtensions();
}
filename = tryPackage(basePath, exts, isMain, request);
}
if (filename) {
Module._pathCache[cacheKey] = filename;
return filename;
}
const extensions = [''];
if (exts !== undefined) {
ArrayPrototypePushApply(extensions, exts);
}
reportModuleNotFoundToWatchMode(basePath, extensions);
}
return false;
};
/** `node_modules` character codes reversed */
const nmChars = [ 115, 101, 108, 117, 100, 111, 109, 95, 101, 100, 111, 110 ];
const nmLen = nmChars.length;
if (isWindows) {
/**
* Get the paths to the `node_modules` folder for a given path.
* @param {string} from `__dirname` of the module
*/
Module._nodeModulePaths = function(from) {
// Guarantee that 'from' is absolute.
from = path.resolve(from);
// note: this approach *only* works when the path is guaranteed
// to be absolute. Doing a fully-edge-case-correct path.split
// that works on both Windows and Posix is non-trivial.
// return root node_modules when path is 'D:\\'.
// path.resolve will make sure from.length >=3 in Windows.
if (StringPrototypeCharCodeAt(from, from.length - 1) ===
CHAR_BACKWARD_SLASH &&
StringPrototypeCharCodeAt(from, from.length - 2) === CHAR_COLON) {
return [from + 'node_modules'];
}
/** @type {string[]} */
const paths = [];
for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
const code = StringPrototypeCharCodeAt(from, i);
// The path segment separator check ('\' and '/') was used to get
// node_modules path for every path segment.
// Use colon as an extra condition since we can get node_modules
// path for drive root like 'C:\node_modules' and don't need to
// parse drive name.
if (code === CHAR_BACKWARD_SLASH ||
code === CHAR_FORWARD_SLASH ||
code === CHAR_COLON) {
if (p !== nmLen) {
ArrayPrototypePush(
paths,
StringPrototypeSlice(from, 0, last) + '\\node_modules',
);
}
last = i;
p = 0;
} else if (p !== -1) {
if (nmChars[p] === code) {
++p;
} else {
p = -1;
}
}
}
return paths;
};
} else { // posix
/**
* Get the paths to the `node_modules` folder for a given path.
* @param {string} from `__dirname` of the module
*/
Module._nodeModulePaths = function(from) {
// Guarantee that 'from' is absolute.
from = path.resolve(from);
// Return early not only to avoid unnecessary work, but to *avoid* returning
// an array of two items for a root: [ '//node_modules', '/node_modules' ]
if (from === '/') {
return ['/node_modules'];
}
// note: this approach *only* works when the path is guaranteed
// to be absolute. Doing a fully-edge-case-correct path.split
// that works on both Windows and Posix is non-trivial.
/** @type {string[]} */
const paths = [];
for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
const code = StringPrototypeCharCodeAt(from, i);
if (code === CHAR_FORWARD_SLASH) {
if (p !== nmLen) {
ArrayPrototypePush(
paths,
StringPrototypeSlice(from, 0, last) + '/node_modules',
);
}
last = i;
p = 0;
} else if (p !== -1) {
if (nmChars[p] === code) {
++p;
} else {
p = -1;
}
}
}
// Append /node_modules to handle root paths.
ArrayPrototypePush(paths, '/node_modules');
return paths;
};
}
/**
* Get the paths for module resolution.
* @param {string} request
* @param {Module} parent
*/
Module._resolveLookupPaths = function(request, parent) {
if (BuiltinModule.normalizeRequirableId(request)) {
debug('looking for %j in []', request);
return null;
}
// Check for node modules paths.
if (StringPrototypeCharAt(request, 0) !== '.' ||
(request.length > 1 &&
StringPrototypeCharAt(request, 1) !== '.' &&
StringPrototypeCharAt(request, 1) !== '/' &&
(!isWindows || StringPrototypeCharAt(request, 1) !== '\\'))) {
/** @type {string[]} */
let paths;
if (parent?.paths?.length) {
paths = ArrayPrototypeSlice(modulePaths);
ArrayPrototypeUnshiftApply(paths, parent.paths);
} else {
paths = modulePaths;
}
debug('looking for %j in %j', request, paths);
return paths.length > 0 ? paths : null;
}
// In REPL, parent.filename is null.
if (!parent || !parent.id || !parent.filename) {
// Make require('./path/to/foo') work - normally the path is taken
// from realpath(__filename) but in REPL there is no filename
const mainPaths = ['.'];
debug('looking for %j in %j', request, mainPaths);
return mainPaths;
}
debug('RELATIVE: requested: %s from parent.id %s', request, parent.id);
const parentDir = [path.dirname(parent.filename)];
debug('looking for %j', parentDir);
return parentDir;
};
/**
* Emits a warning when a non-existent property of module exports is accessed inside a circular dependency.
* @param {string} prop The name of the non-existent property.
*/
function emitCircularRequireWarning(prop) {
process.emitWarning(
`Accessing non-existent property '${String(prop)}' of module exports ` +
'inside circular dependency',
);
}
// A Proxy that can be used as the prototype of a module.exports object and
// warns when non-existent properties are accessed.
const CircularRequirePrototypeWarningProxy = new Proxy({}, {
__proto__: null,
get(target, prop) {
// Allow __esModule access in any case because it is used in the output
// of transpiled code to determine whether something comes from an
// ES module, and is not used as a regular key of `module.exports`.
if (prop in target || prop === '__esModule') { return target[prop]; }
emitCircularRequireWarning(prop);
return undefined;
},
getOwnPropertyDescriptor(target, prop) {
if (ObjectPrototypeHasOwnProperty(target, prop) || prop === '__esModule') {
return ObjectGetOwnPropertyDescriptor(target, prop);
}
emitCircularRequireWarning(prop);
return undefined;
},
});
/**
* Returns the exports object for a module that has a circular `require`.
* If the exports object is a plain object, it is wrapped in a proxy that warns
* about circular dependencies.
* @param {Module} module The module instance
*/
function getExportsForCircularRequire(module) {
const requiredESM = module[kRequiredModuleSymbol];
if (requiredESM && requiredESM.getStatus() !== kEvaluated) {
let message = `Cannot require() ES Module ${module.id} in a cycle.`;
const parent = module[kModuleParent];
if (parent) {
message += ` (from ${parent.filename})`;
}