-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
initialize_import_meta.js
89 lines (77 loc) Β· 2.7 KB
/
initialize_import_meta.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
'use strict';
const { StringPrototypeSlice } = primordials
const { getOptionValue } = require('internal/options');
const { fileURLToPath } = require('url');
const { dirname } = require('path');
const experimentalImportMetaResolve = getOptionValue('--experimental-import-meta-resolve');
/**
* Generate a function to be used as import.meta.resolve for a particular module.
* @param {string} defaultParentUrl The default base to use for resolution
* @param {typeof import('./loader.js').ModuleLoader} loader Reference to the current module loader
* @returns {(specifier: string, parentUrl?: string) => string} Function to assign to import.meta.resolve
*/
function createImportMetaResolve(defaultParentUrl, loader) {
return function resolve(specifier, parentUrl = defaultParentUrl) {
let url;
try {
({ url } = loader.resolve(specifier, parentUrl));
} catch (error) {
if (error?.code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
({ url } = error);
} else {
throw error;
}
}
return url;
};
}
/**
* Create the `import.meta` object for a module.
* @param {object} meta
* @param {{url: string}} context
* @param {typeof import('./loader.js').ModuleLoader} loader Reference to the current module loader
* @returns {{__dirname?: string, __filename?: string, url: string, resolve?: Function}}
*/
function initializeImportMeta(meta, context, loader) {
const { url } = context;
// Alphabetical
const moduleMeta = resolveModuleMeta(url);
meta.__dirname = moduleMeta.__dirname;
meta.__filename = moduleMeta.__filename;
if (experimentalImportMetaResolve && loader.loaderType !== 'internal') {
meta.resolve = createImportMetaResolve(url, loader);
}
meta.url = url;
return meta;
}
/**
* Inspect the module URL and convert it to `__dirname` and `__filename`
* references if it does not point to a network module.
* @param {string} url
* @returns {{__dirname?: string, __filename?: string}}
*/
function resolveModuleMeta(url) {
if (StringPrototypeSlice(url, 0, 7) !== 'file://') {
// These only make sense for locally loaded modules,
// i.e. network modules are not supported.
return { __dirname: undefined, __filename: undefined };
}
// We return an object with getters to reduce memory usage in modules that
// do not use these properties, i.e. most modules don't need the values
// to be resolved until the first time the property is accessed.
let filePath;
let dirPath;
return {
get __dirname() {
return dirname(filePath ??= fileURLToPath(url));
},
get __filename() {
filePath ??= fileURLToPath(url);
dirPath ??= dirname(filePath);
return filePath;
},
};
}
module.exports = {
initializeImportMeta,
};