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