@plugjs/plug 0.3.5 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/asserts.cjs +10 -12
- package/dist/asserts.cjs.map +1 -1
- package/dist/asserts.d.ts +1 -2
- package/dist/asserts.mjs +9 -10
- package/dist/asserts.mjs.map +1 -1
- package/dist/async.cjs +5 -20
- package/dist/async.cjs.map +2 -2
- package/dist/async.mjs +5 -20
- package/dist/async.mjs.map +2 -2
- package/dist/build.cjs +113 -64
- package/dist/build.cjs.map +2 -2
- package/dist/build.d.ts +9 -7
- package/dist/build.mjs +110 -63
- package/dist/build.mjs.map +2 -2
- package/dist/cli.d.mts +12 -0
- package/dist/cli.mjs +266 -0
- package/dist/cli.mjs.map +6 -0
- package/dist/files.cjs +5 -3
- package/dist/files.cjs.map +1 -1
- package/dist/files.d.ts +2 -1
- package/dist/files.mjs +11 -4
- package/dist/files.mjs.map +1 -1
- package/dist/fork.cjs +30 -12
- package/dist/fork.cjs.map +1 -1
- package/dist/fork.d.ts +10 -0
- package/dist/fork.mjs +31 -13
- package/dist/fork.mjs.map +1 -1
- package/dist/helpers.cjs +32 -13
- package/dist/helpers.cjs.map +2 -2
- package/dist/helpers.d.ts +12 -0
- package/dist/helpers.mjs +37 -14
- package/dist/helpers.mjs.map +2 -2
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.mjs +4 -1
- package/dist/index.mjs.map +1 -1
- package/dist/logging/emit.cjs +4 -4
- package/dist/logging/emit.cjs.map +1 -1
- package/dist/logging/emit.mjs +4 -4
- package/dist/logging/emit.mjs.map +1 -1
- package/dist/logging/logger.cjs +43 -2
- package/dist/logging/logger.cjs.map +1 -1
- package/dist/logging/logger.d.ts +36 -3
- package/dist/logging/logger.mjs +43 -3
- package/dist/logging/logger.mjs.map +1 -1
- package/dist/logging/options.cjs +8 -12
- package/dist/logging/options.cjs.map +1 -1
- package/dist/logging/options.d.ts +44 -1
- package/dist/logging/options.mjs +8 -12
- package/dist/logging/options.mjs.map +1 -1
- package/dist/logging.cjs +14 -3
- package/dist/logging.cjs.map +1 -1
- package/dist/logging.d.ts +2 -0
- package/dist/logging.mjs +13 -3
- package/dist/logging.mjs.map +1 -1
- package/dist/plugs/build.cjs +63 -0
- package/dist/plugs/build.cjs.map +6 -0
- package/dist/plugs/build.d.ts +13 -0
- package/dist/plugs/build.mjs +37 -0
- package/dist/plugs/build.mjs.map +6 -0
- package/dist/plugs/debug.cjs +7 -9
- package/dist/plugs/debug.cjs.map +1 -1
- package/dist/plugs/debug.mjs +8 -10
- package/dist/plugs/debug.mjs.map +1 -1
- package/dist/types.cjs +12 -0
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +35 -9
- package/dist/types.mjs +5 -0
- package/dist/types.mjs.map +2 -2
- package/dist/utils/diff.cjs +1 -4
- package/dist/utils/diff.cjs.map +1 -1
- package/dist/utils/diff.mjs +1 -4
- package/dist/utils/diff.mjs.map +1 -1
- package/dist/utils/exec.cjs +5 -12
- package/dist/utils/exec.cjs.map +2 -2
- package/dist/utils/exec.d.ts +0 -2
- package/dist/utils/exec.mjs +6 -13
- package/dist/utils/exec.mjs.map +1 -1
- package/dist/utils/{types.cjs → singleton.cjs} +14 -13
- package/dist/utils/singleton.cjs.map +6 -0
- package/dist/utils/singleton.d.ts +12 -0
- package/dist/utils/singleton.mjs +13 -0
- package/dist/utils/singleton.mjs.map +6 -0
- package/dist/utils.cjs +2 -2
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.ts +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +7 -9
- package/src/asserts.ts +10 -12
- package/src/async.ts +6 -29
- package/src/build.ts +169 -106
- package/{extra/plug.mts → src/cli.mts} +115 -141
- package/src/files.ts +14 -6
- package/src/fork.ts +42 -16
- package/src/helpers.ts +56 -5
- package/src/index.ts +2 -1
- package/src/logging/emit.ts +4 -4
- package/src/logging/logger.ts +60 -7
- package/src/logging/options.ts +9 -14
- package/src/logging.ts +20 -5
- package/src/plugs/build.ts +45 -0
- package/src/plugs/debug.ts +10 -9
- package/src/types.ts +54 -23
- package/src/utils/diff.ts +1 -6
- package/src/utils/exec.ts +6 -20
- package/src/utils/singleton.ts +19 -0
- package/src/utils.ts +1 -1
- package/cli/plug.mjs +0 -1385
- package/cli/ts-loader.mjs +0 -275
- package/cli/tsrun.mjs +0 -1204
- package/dist/utils/types.cjs.map +0 -6
- package/dist/utils/types.d.ts +0 -4
- package/dist/utils/types.mjs +0 -12
- package/dist/utils/types.mjs.map +0 -6
- package/extra/ts-loader.mts +0 -546
- package/extra/tsrun.mts +0 -127
- package/extra/utils.ts +0 -150
- package/src/utils/types.ts +0 -11
package/dist/utils/types.cjs.map
DELETED
package/dist/utils/types.d.ts
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/** A type adding the values `null` or `array` to the result of `typeof` */
|
|
2
|
-
export type BasicType = 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function' | 'null' | 'array';
|
|
3
|
-
/** Get the _real_ type of a value, including `null` or `array` */
|
|
4
|
-
export declare function getTypeOf(what: unknown): BasicType;
|
package/dist/utils/types.mjs
DELETED
package/dist/utils/types.mjs.map
DELETED
package/extra/ts-loader.mts
DELETED
|
@@ -1,546 +0,0 @@
|
|
|
1
|
-
/* ========================================================================== *
|
|
2
|
-
* HACK BEYOND REDEMPTION: TRANSPILE .ts FILES (the esm loader) *
|
|
3
|
-
* -------------------------------------------------------------------------- *
|
|
4
|
-
* This relies on the Node's `--experimental-loader` feature, and uses *
|
|
5
|
-
* ESBuild build magic to quickly transpile TypeScript files into JavaScript. *
|
|
6
|
-
* *
|
|
7
|
-
* The plan as it stands is as follows: *
|
|
8
|
-
* - `.mts` files always get transpiled to ESM modules *
|
|
9
|
-
* - `.cts` files always get transpiled to CJS modules *
|
|
10
|
-
* - `.ts` files are treanspiled according to what's in `package.json` *
|
|
11
|
-
* *
|
|
12
|
-
* Additionally, when transpiling to ESM modules, we can't rely on the magic *
|
|
13
|
-
* that Node's `require(...)` call uses to figure out which file to import. *
|
|
14
|
-
* We need to _actually verify_ on disk what's the correct file to import. *
|
|
15
|
-
* *
|
|
16
|
-
* This is a single module, only available as ESM, and it will _both_ behave *
|
|
17
|
-
* as a NodeJS' loader, _and_ inject the CJS extension handlers (hack) found *
|
|
18
|
-
* in the `_extensions` of `node:module` (same as `require.extensions`). *
|
|
19
|
-
* ========================================================================== */
|
|
20
|
-
|
|
21
|
-
// NodeJS dependencies
|
|
22
|
-
import _fs from 'node:fs'
|
|
23
|
-
import _module from 'node:module'
|
|
24
|
-
import _path from 'node:path'
|
|
25
|
-
import _url from 'node:url'
|
|
26
|
-
import _util from 'node:util'
|
|
27
|
-
|
|
28
|
-
// ESBuild is the only external dependency
|
|
29
|
-
import _esbuild from 'esbuild'
|
|
30
|
-
|
|
31
|
-
// Local imports
|
|
32
|
-
import { isDirectory, isFile } from './utils.js'
|
|
33
|
-
|
|
34
|
-
/* ========================================================================== *
|
|
35
|
-
* DEBUGGING AND ERRORS *
|
|
36
|
-
* ========================================================================== */
|
|
37
|
-
|
|
38
|
-
/** Supported types from `package.json` */
|
|
39
|
-
export type Type = 'commonjs' | 'module'
|
|
40
|
-
/** Constant identifying a `commonjs` module */
|
|
41
|
-
const CJS = 'commonjs'
|
|
42
|
-
/** Constant identifying an ESM `module` */
|
|
43
|
-
const ESM = 'module'
|
|
44
|
-
|
|
45
|
-
/** Setup debugging */
|
|
46
|
-
const _debugLog = _util.debuglog('plug:ts-loader')
|
|
47
|
-
const _debug = _debugLog.enabled
|
|
48
|
-
|
|
49
|
-
/** Emit some logs if `DEBUG_TS_LOADER` is set to `true` */
|
|
50
|
-
function _log(type: Type | null, arg: string, ...args: any []): void {
|
|
51
|
-
if (! _debug) return
|
|
52
|
-
|
|
53
|
-
const t = type === ESM ? 'esm' : type === CJS ? 'cjs' : '---'
|
|
54
|
-
_debugLog(`[${t}] ${arg}`, ...args)
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** Fail miserably */
|
|
58
|
-
function _throw(
|
|
59
|
-
type: Type | null,
|
|
60
|
-
message: string,
|
|
61
|
-
options: { start?: Function, code?: string, cause?: any } = {},
|
|
62
|
-
): never {
|
|
63
|
-
const t = type === ESM ? 'esm' : type === CJS ? 'cjs' : '---'
|
|
64
|
-
const prefix = `[ts-loader|${t}|pid=${process.pid}]`
|
|
65
|
-
|
|
66
|
-
const { start = _throw, ...extra } = options
|
|
67
|
-
const error = new Error(`${prefix} ${message}`)
|
|
68
|
-
Error.captureStackTrace(error, start)
|
|
69
|
-
Object.assign(error, extra)
|
|
70
|
-
|
|
71
|
-
throw error
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
/* ========================================================================== *
|
|
76
|
-
* MODULE TYPES AND FORCING TYPE *
|
|
77
|
-
* ========================================================================== */
|
|
78
|
-
|
|
79
|
-
function _checkType(type: string): Type {
|
|
80
|
-
if (type === CJS) return CJS
|
|
81
|
-
if (type === ESM) return ESM
|
|
82
|
-
_throw(null, `Invalid type "${process.env.__TS_LOADER_FORCE_TYPE}"`)
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
let _type: Type = ((): Type => {
|
|
86
|
-
if (process.env.__TS_LOADER_FORCE_TYPE) {
|
|
87
|
-
const type = process.env.__TS_LOADER_FORCE_TYPE
|
|
88
|
-
_log(null, `Forcing type to "${type}" from environment`)
|
|
89
|
-
return _checkType(type)
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
const findType = (directory: string): Type => {
|
|
93
|
-
const packageFile = _path.join(directory, 'package.json')
|
|
94
|
-
try {
|
|
95
|
-
const packageData = _fs.readFileSync(packageFile, 'utf-8')
|
|
96
|
-
const packageJson = JSON.parse(packageData)
|
|
97
|
-
const packageType = packageJson.type
|
|
98
|
-
switch (packageType) {
|
|
99
|
-
case undefined:
|
|
100
|
-
_log(null, `File "${packageFile}" does not declare a default type`)
|
|
101
|
-
return CJS
|
|
102
|
-
|
|
103
|
-
case CJS:
|
|
104
|
-
case ESM:
|
|
105
|
-
_log(null, `File "${packageFile}" declares type as "${CJS}"`)
|
|
106
|
-
return packageType
|
|
107
|
-
|
|
108
|
-
default:
|
|
109
|
-
_log(null, `File "${packageFile}" specifies unknown type "${packageType}"`)
|
|
110
|
-
return CJS
|
|
111
|
-
}
|
|
112
|
-
} catch (cause: any) {
|
|
113
|
-
if ((cause.code !== 'ENOENT') && (cause.code !== 'EISDIR')) {
|
|
114
|
-
_throw(null, `Unable to read or parse "${packageFile}"`, { cause, start: findType })
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
const parent = _path.dirname(directory)
|
|
119
|
-
if (directory !== parent) return findType(directory)
|
|
120
|
-
|
|
121
|
-
_log(null, `Type defaulted to "${CJS}"`)
|
|
122
|
-
return CJS
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
return findType(process.cwd())
|
|
126
|
-
})()
|
|
127
|
-
|
|
128
|
-
/* The `tsLoaderMarker` (symbol in global) will be a setter/getter for type */
|
|
129
|
-
const tsLoaderMarker = Symbol.for('plugjs:tsLoader')
|
|
130
|
-
|
|
131
|
-
Object.defineProperty(globalThis, tsLoaderMarker, {
|
|
132
|
-
set(type: string): void {
|
|
133
|
-
_log(null, `Setting type to "${type}"`)
|
|
134
|
-
process.env.__TS_LOADER_FORCE_TYPE = _type = _checkType(type)
|
|
135
|
-
},
|
|
136
|
-
get(): Type {
|
|
137
|
-
return _type
|
|
138
|
-
},
|
|
139
|
-
})
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
/* ========================================================================== *
|
|
143
|
-
* ESBUILD HELPERS *
|
|
144
|
-
* ========================================================================== */
|
|
145
|
-
|
|
146
|
-
/**
|
|
147
|
-
* Take an ESBuild `BuildResult` or `BuildFailure` (they both have arrays
|
|
148
|
-
* of `Message` in both `warnings` and `errors`), format them and print them
|
|
149
|
-
* out nicely. Then fail if any error was detected.
|
|
150
|
-
*/
|
|
151
|
-
function _esbReport(
|
|
152
|
-
kind: 'error' | 'warning',
|
|
153
|
-
messages: _esbuild.Message[] = [],
|
|
154
|
-
): void {
|
|
155
|
-
const output = process.stderr
|
|
156
|
-
const options = { color: !!output.isTTY, terminalWidth: output.columns || 80 }
|
|
157
|
-
|
|
158
|
-
const array = _esbuild.formatMessagesSync(messages, { kind, ...options })
|
|
159
|
-
array.forEach((message) => output.write(`${message}\n`))
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* Transpile with ESBuild
|
|
164
|
-
*/
|
|
165
|
-
function _esbTranpile(filename: string, type: Type): string {
|
|
166
|
-
_log(type, `Transpiling "${filename}`)
|
|
167
|
-
|
|
168
|
-
const [ format, __fileurl ] = type === ESM ?
|
|
169
|
-
[ 'esm', 'import.meta.url' ] as const :
|
|
170
|
-
[ 'cjs', '__filename' ] as const
|
|
171
|
-
|
|
172
|
-
/* ESbuild options */
|
|
173
|
-
const options: _esbuild.TransformOptions = {
|
|
174
|
-
sourcefile: filename, // the original filename we're parsing
|
|
175
|
-
format, // what are we actually transpiling to???
|
|
176
|
-
loader: 'ts', // the format is always "typescript"
|
|
177
|
-
sourcemap: 'inline', // always inline source maps
|
|
178
|
-
sourcesContent: false, // do not include sources content in sourcemap
|
|
179
|
-
platform: 'node', // d'oh! :-)
|
|
180
|
-
minifyWhitespace: true, // https://github.com/evanw/esbuild/releases/tag/v0.16.14
|
|
181
|
-
logLevel: 'silent', // catching those in our _esbReport below
|
|
182
|
-
target: `node${process.versions['node']}`, // target _this_ version
|
|
183
|
-
define: { __fileurl }, // from "globals.d.ts"
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/* Emit a line on the console when loading in debug mode */
|
|
187
|
-
if (_debug) {
|
|
188
|
-
if (format === 'esm') {
|
|
189
|
-
options.banner = `;(await import('node:util')).debuglog('plug:ts-loader')('[esm] Loaded "%s"', ${__fileurl});`
|
|
190
|
-
} else if (format === 'cjs') {
|
|
191
|
-
options.banner = `;require('node:util').debuglog('plug:ts-loader')('[cjs] Loaded "%s"', ${__fileurl});`
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/* Transpile our TypeScript file into some JavaScript stuff */
|
|
196
|
-
let result
|
|
197
|
-
try {
|
|
198
|
-
const source = _fs.readFileSync(filename, 'utf-8')
|
|
199
|
-
result = _esbuild.transformSync(source, options)
|
|
200
|
-
} catch (cause: any) {
|
|
201
|
-
_esbReport('error', (cause as _esbuild.TransformFailure).errors)
|
|
202
|
-
_esbReport('warning', (cause as _esbuild.TransformFailure).warnings)
|
|
203
|
-
_throw(type, `ESBuild error transpiling "${filename}"`, { cause, start: _esbTranpile })
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
/* Log transpile warnings if debugging */
|
|
207
|
-
if (_debug) _esbReport('warning', result.warnings)
|
|
208
|
-
|
|
209
|
-
/* Done! */
|
|
210
|
-
return result.code
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
/* ========================================================================== *
|
|
215
|
-
* ESM VERSION *
|
|
216
|
-
* ========================================================================== */
|
|
217
|
-
|
|
218
|
-
/** The formats that can be handled by NodeJS' loader */
|
|
219
|
-
type Format = 'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'
|
|
220
|
-
|
|
221
|
-
/* ========================================================================== */
|
|
222
|
-
|
|
223
|
-
/** The type identifying a NodeJS' loader `resolve` hook. */
|
|
224
|
-
type ResolveHook = (
|
|
225
|
-
/** Whatever was requested to be imported (module, relative file, ...). */
|
|
226
|
-
specifier: string,
|
|
227
|
-
/** Context information around this `resolve` hook call. */
|
|
228
|
-
context: ResolveContext,
|
|
229
|
-
/** The subsequent resolve hook in the chain, or the Node.js default one. */
|
|
230
|
-
nextResolve: ResolveNext,
|
|
231
|
-
) => ResolveResult | Promise<ResolveResult>
|
|
232
|
-
|
|
233
|
-
/** Context information around a `resolve` hook call. */
|
|
234
|
-
interface ResolveContext {
|
|
235
|
-
importAssertions: object
|
|
236
|
-
/** Export conditions of the relevant `package.json`. */
|
|
237
|
-
conditions: string[]
|
|
238
|
-
/** The module importing this one, or undefined if this is the entry point. */
|
|
239
|
-
parentURL?: string | undefined
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
/** The subsequent resolve hook in the chain, or the Node.js default one. */
|
|
243
|
-
type ResolveNext = (specifier: string, context: ResolveContext) => ResolveResult | Promise<ResolveResult>
|
|
244
|
-
|
|
245
|
-
/** A type describing the required results from a `resolve` hook */
|
|
246
|
-
interface ResolveResult {
|
|
247
|
-
/** The absolute URL to which this input resolves. */
|
|
248
|
-
url: string
|
|
249
|
-
/** A format hint to the `load` hook (it might be ignored). */
|
|
250
|
-
format?: Format | null | undefined
|
|
251
|
-
/** A signal that this hook intends to terminate the chain of resolve hooks. */
|
|
252
|
-
shortCircuit?: boolean | undefined
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
/* ========================================================================== */
|
|
256
|
-
|
|
257
|
-
/** The type identifying a NodeJS' loader `load` hook. */
|
|
258
|
-
type LoadHook = (
|
|
259
|
-
/** The URL returned by the resolve chain. */
|
|
260
|
-
url: string,
|
|
261
|
-
/** Context information around this `load` hook call. */
|
|
262
|
-
context: LoadContext,
|
|
263
|
-
/** The subsequent load hook in the chain, or the Node.js default one. */
|
|
264
|
-
nextLoad: LoadNext,
|
|
265
|
-
) => LoadResult | Promise<LoadResult>
|
|
266
|
-
|
|
267
|
-
/** Context information around a `load` hook call. */
|
|
268
|
-
interface LoadContext {
|
|
269
|
-
importAssertions: object
|
|
270
|
-
/** Export conditions of the relevant `package.json` */
|
|
271
|
-
conditions: string[]
|
|
272
|
-
/** The format hint from the `resolve` hook. */
|
|
273
|
-
format?: ResolveResult['format']
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
/** The subsequent load hook in the chain, or the Node.js default one. */
|
|
277
|
-
type LoadNext = (url: string, context: LoadContext) => LoadResult | Promise<LoadResult>
|
|
278
|
-
|
|
279
|
-
/** A type describing the required results from a `resolve` hook */
|
|
280
|
-
type LoadResult = {
|
|
281
|
-
/** The format of the code being loaded. */
|
|
282
|
-
format: Format
|
|
283
|
-
/** A signal that this hook intends to terminate the chain of load hooks. */
|
|
284
|
-
shortCircuit?: boolean | undefined
|
|
285
|
-
} & ({
|
|
286
|
-
format: 'builtin' | 'commonjs'
|
|
287
|
-
/** When the source is `builtin` or `commonjs` no source must be returned */
|
|
288
|
-
source?: never | undefined
|
|
289
|
-
} | {
|
|
290
|
-
format: 'json' | 'module'
|
|
291
|
-
/** When the source is `json` or `module` the source can include strings */
|
|
292
|
-
source: string | ArrayBuffer | NodeJS.TypedArray
|
|
293
|
-
} | {
|
|
294
|
-
format: 'wasm'
|
|
295
|
-
/** When the source is `wasm` the source must not be a string */
|
|
296
|
-
source: ArrayBuffer | NodeJS.TypedArray
|
|
297
|
-
})
|
|
298
|
-
|
|
299
|
-
/* ========================================================================== */
|
|
300
|
-
|
|
301
|
-
/**
|
|
302
|
-
* Our main `resolve` hook: here we need to check for a couple of options
|
|
303
|
-
* when importing ""
|
|
304
|
-
*/
|
|
305
|
-
export const resolve: ResolveHook = (specifier, context, nextResolve): ResolveResult | Promise<ResolveResult> => {
|
|
306
|
-
_log(ESM, `Resolving "${specifier}" from "${context.parentURL}"`)
|
|
307
|
-
|
|
308
|
-
/* We only resolve relative paths ("./xxx" or "../xxx") */
|
|
309
|
-
if (! specifier.match(/^\.\.?\//)) return nextResolve(specifier, context)
|
|
310
|
-
|
|
311
|
-
/* We only resolve if we _do_ have a parent URL and it's a file */
|
|
312
|
-
const parentURL = context.parentURL
|
|
313
|
-
if (! parentURL) return nextResolve(specifier, context)
|
|
314
|
-
if (! parentURL.startsWith('file:')) return nextResolve(specifier, context)
|
|
315
|
-
|
|
316
|
-
/* We only resolve here if the importer is a ".ts" or ".mts" file */
|
|
317
|
-
if (! parentURL.match(/\.m?ts$/)) return nextResolve(specifier, context)
|
|
318
|
-
|
|
319
|
-
/* The resolved URL is the specifier resolved against the parent */
|
|
320
|
-
const url = new URL(specifier, parentURL).href
|
|
321
|
-
const path = _url.fileURLToPath(url)
|
|
322
|
-
|
|
323
|
-
/*
|
|
324
|
-
* Here we are sure that:
|
|
325
|
-
*
|
|
326
|
-
* 1) we are resolving a local path (not a module)
|
|
327
|
-
* 2) the importer is a file, ending with ".ts" or ".mts"
|
|
328
|
-
*
|
|
329
|
-
* Now we can check if "import 'foo'" resolves to:
|
|
330
|
-
*
|
|
331
|
-
* 1) directly to a file, e.g. "import './foo.js'" or "import './foo.mts'"
|
|
332
|
-
* 2) import a "pseudo-JS file", e.g. "import './foo.js'" becomes "import './foo.ts'"
|
|
333
|
-
* 3) imports a file without extension as if it were "import './foo.ts'"
|
|
334
|
-
* 4) imports a directory as in "import './foo/index.ts'"
|
|
335
|
-
*
|
|
336
|
-
* We resolve the _final_ specifier that will be passed to the next resolver
|
|
337
|
-
* for further potential resolution accordingly.
|
|
338
|
-
*
|
|
339
|
-
* We start with the easiest case: is this a real file on the disk?
|
|
340
|
-
*/
|
|
341
|
-
if (isFile(path)) {
|
|
342
|
-
_log(ESM, `Positive match for "${specifier}" as "${path}" (1)`)
|
|
343
|
-
return nextResolve(specifier, context) // straight on
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
/*
|
|
347
|
-
* TypeScript allows us to import "./foo.js", and internally resolves this to
|
|
348
|
-
* "./foo.ts" (yeah, nice, right?) and while we normally wouldn't want to deal
|
|
349
|
-
* with this kind of stuff, the "node16" module resolution mode _forces_ us to
|
|
350
|
-
* use this syntax.
|
|
351
|
-
*/
|
|
352
|
-
const match = specifier.match(/(.*)(\.[mc]?js$)/)
|
|
353
|
-
if (match) {
|
|
354
|
-
const [ , base, ext ] = match
|
|
355
|
-
const tsspecifier = base + ext!.replace('js', 'ts')
|
|
356
|
-
const tsurl = new URL(tsspecifier, parentURL).href
|
|
357
|
-
const tspath = _url.fileURLToPath(tsurl)
|
|
358
|
-
|
|
359
|
-
if (isFile(tspath)) {
|
|
360
|
-
_log(ESM, `Positive match for "${specifier}" as "${tspath}" (2)`)
|
|
361
|
-
return nextResolve(tsspecifier, context) // straight on
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
/* Check if the import is actually a file with a ".ts" extension */
|
|
366
|
-
if (isFile(`${path}.ts`)) {
|
|
367
|
-
_log(ESM, `Positive match for "${specifier}.ts" as "${path}.ts" (3)`)
|
|
368
|
-
return nextResolve(`${specifier}.ts`, context)
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
/* If the file is a directory, then see if we have an "index.ts" in there */
|
|
372
|
-
if (isDirectory(path)) {
|
|
373
|
-
const file = _path.resolve(path, 'index.ts') // resolve, as path is absolute
|
|
374
|
-
if (isFile(file)) {
|
|
375
|
-
_log(ESM, `Positive match for "${specifier}" as "${file}" (4)`)
|
|
376
|
-
const spec = _url.pathToFileURL(file).pathname
|
|
377
|
-
return nextResolve(spec, context)
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
/* There's really nothing else we can do */
|
|
382
|
-
return nextResolve(specifier, context)
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
/** Our main `load` hook */
|
|
386
|
-
export const load: LoadHook = (url, context, nextLoad): LoadResult | Promise<LoadResult> => {
|
|
387
|
-
_log(ESM, `Attempting to load "${url}"`)
|
|
388
|
-
|
|
389
|
-
/* We only load from disk, so ignore everything else */
|
|
390
|
-
if (! url.startsWith('file:')) return nextLoad(url, context)
|
|
391
|
-
|
|
392
|
-
/* Figure our the extension (especially ".ts", ".mts" or ".cts")... */
|
|
393
|
-
const ext = url.match(/\.[cm]?ts$/)?.[0]
|
|
394
|
-
|
|
395
|
-
/* Quick and easy bail-outs for non-TS or ".cts" (always `commonjs`) */
|
|
396
|
-
if (! ext) return nextLoad(url, context)
|
|
397
|
-
|
|
398
|
-
if (ext === '.cts') {
|
|
399
|
-
if (_debug) {
|
|
400
|
-
_log(null, `Switching type from "module" to "commonjs" for "${url}"`)
|
|
401
|
-
_log(null, 'Please note that named import WILL NOT WORK in this case, as Node.js performs a')
|
|
402
|
-
_log(null, 'static analisys on the CommonJS source code, and this file is transpiled from.')
|
|
403
|
-
_log(null, 'TypeScript to CommonJS dynamically.')
|
|
404
|
-
}
|
|
405
|
-
return { format: CJS, shortCircuit: true }
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
/* Convert the url into a file name, any error gets ignored */
|
|
409
|
-
const filename = _url.fileURLToPath(url)
|
|
410
|
-
|
|
411
|
-
/* If the file is a ".ts", we need to figure out the default type */
|
|
412
|
-
if (ext === '.ts') {
|
|
413
|
-
if (_type === CJS) {
|
|
414
|
-
if (_debug) {
|
|
415
|
-
_log(null, `Switching type from "module" to "commonjs" for "${url}"`)
|
|
416
|
-
_log(null, 'Please note that named import WILL NOT WORK in this case, as Node.js performs a')
|
|
417
|
-
_log(null, 'static analisys on the CommonJS source code, and this file is transpiled from.')
|
|
418
|
-
_log(null, 'TypeScript to CommonJS dynamically.')
|
|
419
|
-
}
|
|
420
|
-
return { format: CJS, shortCircuit: true }
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
/* Transpile with ESBuild and return our source code */
|
|
425
|
-
const source = _esbTranpile(filename, ESM)
|
|
426
|
-
return { source, format: ESM, shortCircuit: true }
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
/* ========================================================================== *
|
|
431
|
-
* CJS VERSION *
|
|
432
|
-
* ========================================================================== */
|
|
433
|
-
|
|
434
|
-
/** The extension handler type, loading CJS modules */
|
|
435
|
-
type ExtensionHandler = (module: NodeJS.Module, filename: string) => void
|
|
436
|
-
|
|
437
|
-
/* Add the `_compile(...)` method to NodeJS' `Module` interface */
|
|
438
|
-
declare global {
|
|
439
|
-
namespace NodeJS {
|
|
440
|
-
interface Module {
|
|
441
|
-
_compile: (contents: string, filename: string) => void
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
/**
|
|
447
|
-
* Add the `_extensions[...]` and `resolveFilename(...)` members to the
|
|
448
|
-
* definition of `node:module`.
|
|
449
|
-
*/
|
|
450
|
-
declare module 'node:module' {
|
|
451
|
-
const _extensions: Record<`.${string}`, ExtensionHandler>
|
|
452
|
-
function _resolveFilename(
|
|
453
|
-
request: string,
|
|
454
|
-
parent: _module | undefined,
|
|
455
|
-
isMain: boolean,
|
|
456
|
-
options?: any,
|
|
457
|
-
): string
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
/* ========================================================================== */
|
|
461
|
-
|
|
462
|
-
const loader: ExtensionHandler = (module, filename): void => {
|
|
463
|
-
_log(CJS, `Attempting to load "${filename}"`)
|
|
464
|
-
|
|
465
|
-
/* Figure our the extension (".ts" or ".cts")... */
|
|
466
|
-
const ext = _path.extname(filename)
|
|
467
|
-
|
|
468
|
-
/* If the file is a ".ts", we need to figure out the default type */
|
|
469
|
-
if (ext === '.ts') {
|
|
470
|
-
/* If the _default_ module type is CJS then load as such! */
|
|
471
|
-
if (_type === ESM) {
|
|
472
|
-
_throw(CJS, `Must use import to load ES Module: ${filename}`, { code: 'ERR_REQUIRE_ESM' })
|
|
473
|
-
}
|
|
474
|
-
} else if (ext !== '.cts') {
|
|
475
|
-
_throw(CJS, `Unsupported filename "${filename}"`)
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
const source = _esbTranpile(filename, CJS)
|
|
479
|
-
|
|
480
|
-
/* Let node do its thing, but wrap any error it throws */
|
|
481
|
-
try {
|
|
482
|
-
module._compile(source, filename)
|
|
483
|
-
} catch (cause) {
|
|
484
|
-
// eslint-disable-next-line no-console
|
|
485
|
-
console.error(`Error compiling module "${filename}"`, cause)
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
/* Remember to load our loader for .TS/.CTS as CommonJS modules */
|
|
490
|
-
_module._extensions['.ts'] = _module._extensions['.cts'] = loader
|
|
491
|
-
|
|
492
|
-
/**
|
|
493
|
-
* Replace _module._resolveFilename with our own.
|
|
494
|
-
*
|
|
495
|
-
* This is a _HACK BEYOND REDEMPTION_ and I'm ashamed of even _thinking_ about
|
|
496
|
-
* it, but, well, it makes things work.
|
|
497
|
-
*
|
|
498
|
-
* TypeScript allows us to import "./foo.js", and internally resolves this to
|
|
499
|
-
* "./foo.ts" (yeah, nice, right?) and while we normally wouldn't want to deal
|
|
500
|
-
* with this kind of stuff, the "node16" module resolution mode _forces_ us to
|
|
501
|
-
* use this syntax.
|
|
502
|
-
*
|
|
503
|
-
* And we _need_ the "node16" module resolution to properly consume "export
|
|
504
|
-
* conditions" from other packages. Since ESBuild's plugins only work in async
|
|
505
|
-
* mode, changing those import statements on the fly is out of the question, so
|
|
506
|
-
* we need to hack our way into Node's own resolver.
|
|
507
|
-
*
|
|
508
|
-
* See my post: https://twitter.com/ianosh/status/1559484168685379590
|
|
509
|
-
* ESBuild related fix: https://github.com/evanw/esbuild/commit/0cdc005e3d1c765a084f206741bc4bff78e30ec4
|
|
510
|
-
*/
|
|
511
|
-
const _oldResolveFilename = _module._resolveFilename
|
|
512
|
-
_module._resolveFilename = function(
|
|
513
|
-
request: string,
|
|
514
|
-
parent: _module | undefined,
|
|
515
|
-
...args: [ isMain: boolean, options: any ]
|
|
516
|
-
): any {
|
|
517
|
-
try {
|
|
518
|
-
/* First call the old _resolveFilename to see what Node thinks */
|
|
519
|
-
return _oldResolveFilename.call(this, request, parent, ...args)
|
|
520
|
-
} catch (error: any) {
|
|
521
|
-
/* If the error was anything but "MODULE_NOT_FOUND" bail out */
|
|
522
|
-
if (error.code !== 'MODULE_NOT_FOUND') throw error
|
|
523
|
-
|
|
524
|
-
/* Check if the "request" ends with ".js", ".mjs" or ".cjs" */
|
|
525
|
-
const match = request.match(/(.*)(\.[mc]?js$)/)
|
|
526
|
-
|
|
527
|
-
/*
|
|
528
|
-
* If the file matches our extension, _and_ we have a parent, we simply
|
|
529
|
-
* try with a new extension (e.g. ".js" becomes ".ts")...
|
|
530
|
-
*/
|
|
531
|
-
if (parent && match) {
|
|
532
|
-
const [ , name, ext ] = match
|
|
533
|
-
const tsrequest = name + ext!.replace('js', 'ts')
|
|
534
|
-
try {
|
|
535
|
-
const result = _oldResolveFilename.call(this, tsrequest, parent, ...args)
|
|
536
|
-
_log(CJS, `Resolution for "${request}" intercepted as "${tsrequest}`)
|
|
537
|
-
return result
|
|
538
|
-
} catch (discard) {
|
|
539
|
-
throw error // throw the _original_ error in this case
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
/* We have no parent, or we don't match our extension, throw! */
|
|
544
|
-
throw error
|
|
545
|
-
}
|
|
546
|
-
}
|