-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathutils.js
More file actions
276 lines (235 loc) · 7.89 KB
/
Copy pathutils.js
File metadata and controls
276 lines (235 loc) · 7.89 KB
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
'use strict'
// The content of this file is copied from the `import-in-the-middle` package with minor modifications (https://www.npmjs.com/package/import-in-the-middle)
const { pathToFileURL, fileURLToPath } = require('node:url')
const fs = require('node:fs')
const path = require('node:path')
const { NODE_MAJOR, NODE_MINOR } = require('../../../version.js')
const LOAD_OPERATION = 0
const RESOLVE_OPERATION = 1
const getExportsImporting = (url) => import(url).then(Object.keys)
let getExportsModulePromise
const loadGetExportsModule = () => {
if (!getExportsModulePromise) {
getExportsModulePromise = import('import-in-the-middle/lib/get-exports.mjs')
}
return getExportsModulePromise
}
const getExports = NODE_MAJOR >= 20 || (NODE_MAJOR === 18 && NODE_MINOR >= 19)
? async (srcUrl, context, getSource) => {
const mod = await loadGetExportsModule()
const exportNames = mod.getExports(srcUrl, context, getSource)
if (exportNames?.next) {
return driveGetExportsGenerator(exportNames, getSource)
}
return exportNames
}
: getExportsImporting
function isStarExportLine (line) {
return /^\* from /.test(line)
}
function isBareSpecifier (specifier) {
// Relative and absolute paths are not bare specifiers.
if (
specifier.startsWith('.') ||
specifier.startsWith('/')) {
return false
}
// Valid URLs are not bare specifiers. (file:, http:, node:, etc.)
if (URL.hasOwnProperty('canParse')) {
// eslint-disable-next-line n/no-unsupported-features/node-builtins
return !URL.canParse(specifier)
}
try {
// eslint-disable-next-line no-new
new URL(specifier)
return false
} catch {
return true
}
}
function resolve (specifier, context) {
// This comes from an import, that is why import makes preference
const conditions = ['import']
if (specifier.startsWith('file://')) {
specifier = fileURLToPath(specifier)
}
const resolved = require.resolve(specifier, {
paths: [fileURLToPath(context.parentURL)],
// @ts-expect-error - Node.js 22+ unofficially supports a conditions option
conditions,
})
return {
url: pathToFileURL(resolved),
format: isESMFile(resolved) ? 'module' : 'commonjs',
}
}
function getSource (url, { format }) {
return {
source: fs.readFileSync(fileURLToPath(url), 'utf8'),
format,
}
}
/**
* @typedef {[typeof LOAD_OPERATION, URL, object] | [typeof RESOLVE_OPERATION, string, object]} GetExportsOperation
*/
/**
* @typedef {{ done: false, value: GetExportsOperation } | { done: true, value: Set<string> }} GetExportsResult
*/
/**
* @typedef {{
* next: (value?: unknown) => GetExportsResult,
* throw: (error?: unknown) => GetExportsResult,
* }} GetExportsGenerator
*/
/**
* Drives the generator returned by import-in-the-middle >=3.1.0 export discovery.
*
* @param {GetExportsGenerator} exportsGenerator Generator returned by getExports
* @param {(url: URL, context: object) => { source: string, format: string }} getSource
* Function that loads module source
* @returns {Set<string>}
*/
function driveGetExportsGenerator (exportsGenerator, getSource) {
let next = exportsGenerator.next()
while (next.done === false) {
let result
let error
let threw = false
try {
const operation = next.value
const operationType = operation[0]
if (operationType === LOAD_OPERATION) {
result = getSource(operation[1], operation[2])
} else if (operationType === RESOLVE_OPERATION) {
result = resolve(operation[1], operation[2])
} else {
throw new Error(`Unsupported import-in-the-middle getExports operation: ${operationType}`)
}
} catch (err) {
threw = true
error = err
}
next = threw ? exportsGenerator.throw(error) : exportsGenerator.next(result)
}
return next.value
}
/**
* Generates the pieces of code for the proxy module before the path
*
* @param {object} moduleData
* @param {string} moduleData.path
* @param {boolean} [moduleData.internal]
* @param {object} moduleData.context
* @param {boolean} [moduleData.excludeDefault]
* @returns {Promise<Map>}
*/
async function processModule ({ path, internal = false, context, excludeDefault = false }) {
let exportNames, srcUrl
if (internal) {
// we can not read and parse of internal modules
exportNames = await getExportsImporting(path)
} else {
srcUrl = pathToFileURL(path)
exportNames = await getExports(srcUrl, context, getSource)
}
const starExports = new Set()
const setters = new Map()
const addSetter = (name, setter, isStarExport = false) => {
if (setters.has(name)) {
if (isStarExport) {
// If there's already a matching star export, delete it
if (starExports.has(name)) {
setters.delete(name)
}
// and return so this is excluded
return
}
// if we already have this export but it is from a * export, overwrite it
if (starExports.has(name)) {
starExports.delete(name)
setters.set(name, setter)
}
} else {
// Store export * exports so we know they can be overridden by explicit
// named exports
if (isStarExport) {
starExports.add(name)
}
setters.set(name, setter)
}
}
for (const n of exportNames) {
if (n === 'default' && excludeDefault) continue
if (isStarExportLine(n)) {
// export * from 'wherever'
const [, modFile] = n.split('* from ')
// Relative paths need to be resolved relative to the parent module
const newSpecifier = isBareSpecifier(modFile) ? modFile : new URL(modFile, srcUrl).href
// We need to call `parentResolve` to resolve bare specifiers to a full
// URL. We also need to call `parentResolve` for all sub-modules to get
// the `format`. We can't rely on the parents `format` to know if this
// sub-module is ESM or CJS!
const result = resolve(newSpecifier, { parentURL: srcUrl })
// eslint-disable-next-line no-await-in-loop
const subSetters = await processModule({
path: fileURLToPath(result.url),
context: { ...context, format: result.format },
excludeDefault: true,
})
for (const [name, setter] of subSetters.entries()) {
addSetter(name, setter, true)
}
} else {
const variableName = `$${n.replaceAll(/[^a-zA-Z0-9_$]/g, '_')}`
const objectKey = JSON.stringify(n)
const reExportedName = n === 'default' ? n : objectKey
addSetter(n, `
let ${variableName}
try {
${variableName} = _[${objectKey}] = namespace[${objectKey}]
} catch (err) {
if (!(err instanceof ReferenceError)) throw err
}
export { ${variableName} as ${reExportedName} }
set[${objectKey}] = (v) => {
${variableName} = v
return true
}
get[${objectKey}] = () => ${variableName}
`)
}
}
return setters
}
/**
* Determines if a file is a ESM module or CommonJS
*
* @param {string} fullPathToModule File to analize
* @param {string} [modulePackageJsonPath] Path of the package.json
* @param {object} [packageJson] The content of the module package.json
* @returns {boolean}
*/
function isESMFile (fullPathToModule, modulePackageJsonPath, packageJson = {}) {
if (fullPathToModule.endsWith('.mjs')) return true
if (fullPathToModule.endsWith('.cjs')) return false
const pathParts = fullPathToModule.split(path.sep)
do {
pathParts.pop()
const packageJsonPath = [...pathParts, 'package.json'].join(path.sep)
if (packageJsonPath === modulePackageJsonPath) {
return packageJson.type === 'module'
}
try {
const packageJsonContent = fs.readFileSync(packageJsonPath).toString()
const packageJson = JSON.parse(packageJsonContent)
return packageJson.type === 'module'
} catch {
// file does not exit, continue
}
} while (pathParts.length > 0)
return packageJson.type === 'module'
}
module.exports = {
processModule,
isESMFile,
}