unrun 0.2.38 → 0.3.0
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/cli.d.mts +1 -0
- package/dist/cli.mjs +103 -0
- package/dist/index.d.mts +81 -0
- package/dist/index.mjs +2 -0
- package/dist/src-DgjiW5nf.mjs +910 -0
- package/dist/sync/worker.d.mts +1 -0
- package/dist/sync/worker.mjs +48 -0
- package/package.json +1 -1
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
//#region src/cli.ts
|
|
4
|
+
function parseCLIArguments(argv) {
|
|
5
|
+
let debug = false;
|
|
6
|
+
let preset;
|
|
7
|
+
let filePath;
|
|
8
|
+
const beforeArgs = [];
|
|
9
|
+
const afterArgs = [];
|
|
10
|
+
let expectFilePathAfterDelimiter = false;
|
|
11
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
12
|
+
const argument = argv[index];
|
|
13
|
+
if (filePath !== void 0) {
|
|
14
|
+
if (argument === "--") {
|
|
15
|
+
afterArgs.push(...argv.slice(index + 1));
|
|
16
|
+
break;
|
|
17
|
+
}
|
|
18
|
+
afterArgs.push(argument);
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if (expectFilePathAfterDelimiter) {
|
|
22
|
+
filePath = argument;
|
|
23
|
+
expectFilePathAfterDelimiter = false;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (argument === "--") {
|
|
27
|
+
expectFilePathAfterDelimiter = true;
|
|
28
|
+
beforeArgs.push(argument);
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (argument === "--debug") {
|
|
32
|
+
debug = true;
|
|
33
|
+
beforeArgs.push(argument);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (argument === "--no-debug") {
|
|
37
|
+
debug = false;
|
|
38
|
+
beforeArgs.push(argument);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (argument.startsWith("--preset=")) {
|
|
42
|
+
preset = argument.slice(9);
|
|
43
|
+
beforeArgs.push(argument);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (argument === "--preset") {
|
|
47
|
+
const presetValue = argv[index + 1];
|
|
48
|
+
if (!presetValue || presetValue.startsWith("-")) throw new Error("[unrun] Missing preset value after --preset");
|
|
49
|
+
preset = presetValue;
|
|
50
|
+
beforeArgs.push(argument, presetValue);
|
|
51
|
+
index += 1;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (argument.startsWith("-")) {
|
|
55
|
+
beforeArgs.push(argument);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
filePath = argument;
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
debug,
|
|
62
|
+
preset,
|
|
63
|
+
filePath,
|
|
64
|
+
beforeArgs,
|
|
65
|
+
afterArgs
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
async function runCLI() {
|
|
69
|
+
let parsedArguments;
|
|
70
|
+
try {
|
|
71
|
+
parsedArguments = parseCLIArguments(process.argv.slice(2));
|
|
72
|
+
} catch (error) {
|
|
73
|
+
console.error(error.message);
|
|
74
|
+
process.exit(1);
|
|
75
|
+
}
|
|
76
|
+
if (!parsedArguments.filePath) {
|
|
77
|
+
console.error("[unrun] No input files provided");
|
|
78
|
+
process.exit(1);
|
|
79
|
+
}
|
|
80
|
+
process.argv = [
|
|
81
|
+
process.argv[0],
|
|
82
|
+
parsedArguments.filePath,
|
|
83
|
+
...parsedArguments.afterArgs
|
|
84
|
+
];
|
|
85
|
+
try {
|
|
86
|
+
const { unrunCli } = await import("./index.mjs");
|
|
87
|
+
const cliResult = await unrunCli({
|
|
88
|
+
path: parsedArguments.filePath,
|
|
89
|
+
debug: parsedArguments.debug,
|
|
90
|
+
preset: parsedArguments.preset
|
|
91
|
+
}, parsedArguments.afterArgs);
|
|
92
|
+
process.exit(cliResult.exitCode);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
console.error(error.message);
|
|
95
|
+
process.exit(1);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
runCLI().catch((error) => {
|
|
99
|
+
console.error(error.message);
|
|
100
|
+
process.exit(1);
|
|
101
|
+
});
|
|
102
|
+
//#endregion
|
|
103
|
+
export {};
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { InputOptions, OutputOptions } from "rolldown";
|
|
2
|
+
|
|
3
|
+
//#region src/options.d.ts
|
|
4
|
+
interface Options {
|
|
5
|
+
/**
|
|
6
|
+
* The path to the file to be imported. Supports filesystem paths, file URLs or URL objects.
|
|
7
|
+
* @default 'index.ts'
|
|
8
|
+
*/
|
|
9
|
+
path?: string | URL;
|
|
10
|
+
/**
|
|
11
|
+
* Debug mode.
|
|
12
|
+
* Wether or not to keep temporary files to help with debugging.
|
|
13
|
+
* Temporary files are stored in `node_modules/.unrun/` if possible,
|
|
14
|
+
* otherwise in the OS temporary directory.
|
|
15
|
+
* @default false
|
|
16
|
+
*/
|
|
17
|
+
debug?: boolean;
|
|
18
|
+
/**
|
|
19
|
+
* The preset to use for bundling and output format.
|
|
20
|
+
* @default 'none'
|
|
21
|
+
*/
|
|
22
|
+
preset?: "none" | "jiti" | "bundle-require";
|
|
23
|
+
/**
|
|
24
|
+
* Additional rolldown input options. These options will be merged with the
|
|
25
|
+
* defaults provided by unrun, with these options always taking precedence.
|
|
26
|
+
*/
|
|
27
|
+
inputOptions?: InputOptions;
|
|
28
|
+
/**
|
|
29
|
+
* Additional rolldown output options. These options will be merged with the
|
|
30
|
+
* defaults provided by unrun, with these options always taking precedence.
|
|
31
|
+
*/
|
|
32
|
+
outputOptions?: OutputOptions;
|
|
33
|
+
}
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/types.d.ts
|
|
36
|
+
interface Result<T = unknown> {
|
|
37
|
+
/**
|
|
38
|
+
* The module that was loaded.
|
|
39
|
+
* You can specify the type of the module by providing a type argument when using the `unrun` function.
|
|
40
|
+
*/
|
|
41
|
+
module: T;
|
|
42
|
+
/**
|
|
43
|
+
* The dependencies involved when loading the targeted module.
|
|
44
|
+
* Note: this only includes local file dependencies, npm-resolved dependencies are excluded.
|
|
45
|
+
*/
|
|
46
|
+
dependencies: string[];
|
|
47
|
+
}
|
|
48
|
+
interface CliResult {
|
|
49
|
+
/**
|
|
50
|
+
* The exit code of the CLI execution.
|
|
51
|
+
*/
|
|
52
|
+
exitCode: number;
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/index.d.ts
|
|
56
|
+
/**
|
|
57
|
+
* Loads a module with JIT transpilation based on the provided options.
|
|
58
|
+
*
|
|
59
|
+
* @param options - The options for loading the module.
|
|
60
|
+
* @returns A promise that resolves to the loaded module.
|
|
61
|
+
*/
|
|
62
|
+
declare function unrun<T>(options: Options): Promise<Result<T>>;
|
|
63
|
+
/**
|
|
64
|
+
* Loads a module with JIT transpilation based on the provided options.
|
|
65
|
+
* This function runs synchronously using a worker thread.
|
|
66
|
+
*
|
|
67
|
+
* @param options - The options for loading the module.
|
|
68
|
+
* @returns The loaded module.
|
|
69
|
+
*/
|
|
70
|
+
declare function unrunSync<T>(options: Options): Result<T>;
|
|
71
|
+
/**
|
|
72
|
+
* Runs a given module with JIT transpilation based on the provided options.
|
|
73
|
+
* This function does not return the module, as it simply executes it.
|
|
74
|
+
* Corresponds to the CLI behavior.
|
|
75
|
+
*
|
|
76
|
+
* @param options - The options for running the module.
|
|
77
|
+
* @param args - Additional command-line arguments to pass to the module.
|
|
78
|
+
*/
|
|
79
|
+
declare function unrunCli(options: Options, args?: string[]): Promise<CliResult>;
|
|
80
|
+
//#endregion
|
|
81
|
+
export { type CliResult, type Options, type Result, unrun, unrunCli, unrunSync };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,910 @@
|
|
|
1
|
+
import { builtinModules, createRequire } from "node:module";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import fs, { existsSync } from "node:fs";
|
|
4
|
+
import process from "node:process";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
import { rolldown } from "rolldown";
|
|
7
|
+
import { Buffer as Buffer$1 } from "node:buffer";
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
//#region \0rolldown/runtime.js
|
|
12
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/features/preset.ts
|
|
15
|
+
/**
|
|
16
|
+
* Applies preset-specific handling to the loaded module.
|
|
17
|
+
*/
|
|
18
|
+
function preset(options, module) {
|
|
19
|
+
if (options.preset === "bundle-require") return module;
|
|
20
|
+
if (options.preset === "jiti") {
|
|
21
|
+
const ext = path.extname(options.path);
|
|
22
|
+
if (module && typeof module === "object" && module[Symbol.toStringTag] === "Module" && Object.keys(module).length === 0) return ext === ".mjs" ? module : {};
|
|
23
|
+
}
|
|
24
|
+
if (module && typeof module === "object" && "default" in module) return module.default;
|
|
25
|
+
return module;
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/utils/normalize-path.ts
|
|
29
|
+
/**
|
|
30
|
+
* Normalize a path-like input to a string path.
|
|
31
|
+
* @param pathLike The path-like input (string or URL).
|
|
32
|
+
* @returns The normalized string path.
|
|
33
|
+
*/
|
|
34
|
+
function normalizePath(pathLike) {
|
|
35
|
+
if (!pathLike) return "index.ts";
|
|
36
|
+
if (pathLike instanceof URL) {
|
|
37
|
+
if (pathLike.protocol === "file:") return fileURLToPath(pathLike);
|
|
38
|
+
return pathLike.href;
|
|
39
|
+
}
|
|
40
|
+
if (typeof pathLike === "string") {
|
|
41
|
+
if (!pathLike.startsWith("file:")) return pathLike;
|
|
42
|
+
try {
|
|
43
|
+
return fileURLToPath(pathLike);
|
|
44
|
+
} catch {
|
|
45
|
+
try {
|
|
46
|
+
return fileURLToPath(new URL(pathLike));
|
|
47
|
+
} catch {
|
|
48
|
+
return pathLike;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return String(pathLike);
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/options.ts
|
|
56
|
+
function resolveOptions(options = {}) {
|
|
57
|
+
const resolvedOptions = {
|
|
58
|
+
path: path.resolve(process.cwd(), normalizePath(options.path)),
|
|
59
|
+
debug: options.debug || false,
|
|
60
|
+
preset: options.preset || "none",
|
|
61
|
+
inputOptions: options.inputOptions,
|
|
62
|
+
outputOptions: options.outputOptions
|
|
63
|
+
};
|
|
64
|
+
if (!fs.existsSync(resolvedOptions.path)) throw new Error(`[unrun] File not found: ${resolvedOptions.path}`);
|
|
65
|
+
if (!new Set([
|
|
66
|
+
"none",
|
|
67
|
+
"jiti",
|
|
68
|
+
"bundle-require"
|
|
69
|
+
]).has(resolvedOptions.preset)) throw new Error(`[unrun] Invalid preset "${resolvedOptions.preset}" (expected: none | jiti | bundle-require)`);
|
|
70
|
+
return resolvedOptions;
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/utils/module-resolution.ts
|
|
74
|
+
/**
|
|
75
|
+
* Precomputed set of Node.js builtin module specifiers, including both plain and `node:` prefixed forms.
|
|
76
|
+
*/
|
|
77
|
+
const BUILTIN_MODULE_SPECIFIERS = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
78
|
+
/**
|
|
79
|
+
* Returns true when `id` refers to a Node.js builtin module, accepting both plain and `node:` specifiers.
|
|
80
|
+
*/
|
|
81
|
+
function isBuiltinModuleSpecifier(id) {
|
|
82
|
+
if (!id) return false;
|
|
83
|
+
return BUILTIN_MODULE_SPECIFIERS.has(id) || id.startsWith("node:");
|
|
84
|
+
}
|
|
85
|
+
//#endregion
|
|
86
|
+
//#region src/features/external.ts
|
|
87
|
+
/**
|
|
88
|
+
* Builds the rolldown external resolver used to decide which imports remain external.
|
|
89
|
+
* Treat bare imports from the primary node_modules as external, but inline
|
|
90
|
+
* nested node_modules so they keep working once executed from .unrun.
|
|
91
|
+
*/
|
|
92
|
+
function createExternalResolver(options) {
|
|
93
|
+
const entryDir = path.dirname(options.path);
|
|
94
|
+
const canResolveFromEntry = (specifier) => {
|
|
95
|
+
const packageName = getPackageName(specifier);
|
|
96
|
+
if (!packageName) return false;
|
|
97
|
+
let currentDir = entryDir;
|
|
98
|
+
while (true) {
|
|
99
|
+
if (existsSync(path.join(currentDir, "node_modules", packageName))) return true;
|
|
100
|
+
const parentDir = path.dirname(currentDir);
|
|
101
|
+
if (parentDir === currentDir) break;
|
|
102
|
+
currentDir = parentDir;
|
|
103
|
+
}
|
|
104
|
+
return false;
|
|
105
|
+
};
|
|
106
|
+
return function external(id) {
|
|
107
|
+
if (!id || id.startsWith("\0")) return false;
|
|
108
|
+
if (id.startsWith(".") || id.startsWith("#") || path.isAbsolute(id)) return false;
|
|
109
|
+
if (isBuiltinModuleSpecifier(id)) return true;
|
|
110
|
+
if (!canResolveFromEntry(id)) return false;
|
|
111
|
+
return true;
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function getPackageName(specifier) {
|
|
115
|
+
if (!specifier) return void 0;
|
|
116
|
+
if (specifier.startsWith("@")) {
|
|
117
|
+
const segments = specifier.split("/");
|
|
118
|
+
if (segments.length >= 2) return `${segments[0]}/${segments[1]}`;
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const [name] = specifier.split("/");
|
|
122
|
+
return name || void 0;
|
|
123
|
+
}
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/plugins/console-output-customizer.ts
|
|
126
|
+
const INSPECT_HELPER_SNIPPET = `(function(){
|
|
127
|
+
function __unrun__fmt(names, getter, np){
|
|
128
|
+
var onlyDefault = names.length === 1 && names[0] === "default";
|
|
129
|
+
var o = np ? Object.create(null) : {};
|
|
130
|
+
for (var i = 0; i < names.length; i++) {
|
|
131
|
+
var n = names[i];
|
|
132
|
+
try { o[n] = getter(n) } catch {}
|
|
133
|
+
}
|
|
134
|
+
if (onlyDefault) {
|
|
135
|
+
try {
|
|
136
|
+
var s = JSON.stringify(o.default);
|
|
137
|
+
if (s !== undefined) {
|
|
138
|
+
s = s.replace(/"([^"]+)":/g, "$1: ").replace(/,/g, ", ").replace(/{/g, "{ ").replace(/}/g, " }");
|
|
139
|
+
return "[Module: null prototype] { default: " + s + " }";
|
|
140
|
+
}
|
|
141
|
+
} catch {}
|
|
142
|
+
return "[Module: null prototype] { default: " + String(o.default) + " }";
|
|
143
|
+
}
|
|
144
|
+
return o;
|
|
145
|
+
}
|
|
146
|
+
function __unrun__setInspect(obj, names, getter, np){
|
|
147
|
+
try {
|
|
148
|
+
var __insp = Symbol.for('nodejs.util.inspect.custom');
|
|
149
|
+
Object.defineProperty(obj, __insp, {
|
|
150
|
+
value: function(){ return __unrun__fmt(names, getter, np) },
|
|
151
|
+
enumerable: false, configurable: true
|
|
152
|
+
});
|
|
153
|
+
} catch {}
|
|
154
|
+
return obj;
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
Object.defineProperty(globalThis, "__unrun__setInspect", {
|
|
158
|
+
value: __unrun__setInspect,
|
|
159
|
+
enumerable: false,
|
|
160
|
+
});
|
|
161
|
+
} catch {}
|
|
162
|
+
})();`;
|
|
163
|
+
const WRAPPER_SNIPPET = `(function __unrun__wrapRolldownHelpers(){
|
|
164
|
+
if (typeof __unrun__setInspect !== "function") return;
|
|
165
|
+
if (typeof __export === "function" && !__export.__unrunPatched) {
|
|
166
|
+
var __unrun__origExport = __export;
|
|
167
|
+
var __unrun__patchedExport = (...__unrun__args) => {
|
|
168
|
+
var __unrun__target = __unrun__origExport(...__unrun__args);
|
|
169
|
+
if (__unrun__target && typeof __unrun__target === "object") {
|
|
170
|
+
try {
|
|
171
|
+
var __unrun__map = (__unrun__args[0] && typeof __unrun__args[0] === "object") ? __unrun__args[0] : {};
|
|
172
|
+
var __unrun__names = Object.keys(__unrun__map).filter(function(n){ return n !== "__esModule" });
|
|
173
|
+
__unrun__setInspect(
|
|
174
|
+
__unrun__target,
|
|
175
|
+
__unrun__names,
|
|
176
|
+
function(n){
|
|
177
|
+
var getter = __unrun__map[n];
|
|
178
|
+
return typeof getter === "function" ? getter() : getter;
|
|
179
|
+
},
|
|
180
|
+
false,
|
|
181
|
+
);
|
|
182
|
+
} catch {}
|
|
183
|
+
}
|
|
184
|
+
return __unrun__target;
|
|
185
|
+
};
|
|
186
|
+
__unrun__patchedExport.__unrunPatched = true;
|
|
187
|
+
__export = __unrun__patchedExport;
|
|
188
|
+
}
|
|
189
|
+
if (typeof __exportAll === "function" && !__exportAll.__unrunPatched) {
|
|
190
|
+
var __unrun__origExportAll = __exportAll;
|
|
191
|
+
var __unrun__patchedExportAll = (...__unrun__args) => {
|
|
192
|
+
var __unrun__target = __unrun__origExportAll(...__unrun__args);
|
|
193
|
+
if (__unrun__target && typeof __unrun__target === "object") {
|
|
194
|
+
try {
|
|
195
|
+
var __unrun__map = (__unrun__args[0] && typeof __unrun__args[0] === "object") ? __unrun__args[0] : {};
|
|
196
|
+
var __unrun__names = Object.keys(__unrun__map).filter(function(n){ return n !== "__esModule" });
|
|
197
|
+
__unrun__setInspect(
|
|
198
|
+
__unrun__target,
|
|
199
|
+
__unrun__names,
|
|
200
|
+
function(n){
|
|
201
|
+
var getter = __unrun__map[n];
|
|
202
|
+
return typeof getter === "function" ? getter() : getter;
|
|
203
|
+
},
|
|
204
|
+
false,
|
|
205
|
+
);
|
|
206
|
+
} catch {}
|
|
207
|
+
}
|
|
208
|
+
return __unrun__target;
|
|
209
|
+
};
|
|
210
|
+
__unrun__patchedExportAll.__unrunPatched = true;
|
|
211
|
+
__exportAll = __unrun__patchedExportAll;
|
|
212
|
+
}
|
|
213
|
+
if (typeof __copyProps === "function" && !__copyProps.__unrunPatched) {
|
|
214
|
+
var __unrun__origCopyProps = __copyProps;
|
|
215
|
+
var __unrun__patchedCopyProps = (...__unrun__args) => {
|
|
216
|
+
var __unrun__result = __unrun__origCopyProps(...__unrun__args);
|
|
217
|
+
if (__unrun__result && typeof __unrun__result === "object") {
|
|
218
|
+
try {
|
|
219
|
+
var __unrun__names = Object.keys(__unrun__result).filter(function(n){ return n !== "__esModule" });
|
|
220
|
+
__unrun__setInspect(__unrun__result, __unrun__names, function(n){ return __unrun__result[n] }, true);
|
|
221
|
+
} catch {}
|
|
222
|
+
}
|
|
223
|
+
return __unrun__result;
|
|
224
|
+
};
|
|
225
|
+
__unrun__patchedCopyProps.__unrunPatched = true;
|
|
226
|
+
__copyProps = __unrun__patchedCopyProps;
|
|
227
|
+
}
|
|
228
|
+
})();`;
|
|
229
|
+
const HELPER_DECLARATION_PATTERN = /__unrun__setInspect\b/;
|
|
230
|
+
const WRAPPER_MARKER = "__unrun__wrapRolldownHelpers";
|
|
231
|
+
function createConsoleOutputCustomizer() {
|
|
232
|
+
return {
|
|
233
|
+
name: "unrun-console-output-customizer",
|
|
234
|
+
generateBundle: { handler(_, bundle) {
|
|
235
|
+
for (const chunk of Object.values(bundle)) {
|
|
236
|
+
if (chunk.type !== "chunk") continue;
|
|
237
|
+
injectInspectHelper(chunk);
|
|
238
|
+
injectHelperWrappers(chunk);
|
|
239
|
+
}
|
|
240
|
+
} }
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
function injectInspectHelper(chunk) {
|
|
244
|
+
if (HELPER_DECLARATION_PATTERN.test(chunk.code)) return;
|
|
245
|
+
chunk.code = chunk.code.startsWith("#!") ? insertAfterShebang(chunk.code, `${INSPECT_HELPER_SNIPPET}\n`) : `${INSPECT_HELPER_SNIPPET}\n${chunk.code}`;
|
|
246
|
+
}
|
|
247
|
+
function injectHelperWrappers(chunk) {
|
|
248
|
+
if (chunk.code.includes(WRAPPER_MARKER)) return;
|
|
249
|
+
const insertIndex = findRuntimeBoundary(chunk.code);
|
|
250
|
+
const snippet = `${WRAPPER_SNIPPET}\n`;
|
|
251
|
+
if (insertIndex === -1) {
|
|
252
|
+
chunk.code = `${chunk.code}\n${snippet}`;
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
chunk.code = `${chunk.code.slice(0, insertIndex)}${snippet}${chunk.code.slice(insertIndex)}`;
|
|
256
|
+
}
|
|
257
|
+
function findRuntimeBoundary(code) {
|
|
258
|
+
const markerIndex = code.indexOf("//#endregion");
|
|
259
|
+
if (markerIndex === -1) return -1;
|
|
260
|
+
const newlineIndex = code.indexOf("\n", markerIndex);
|
|
261
|
+
return newlineIndex === -1 ? code.length : newlineIndex + 1;
|
|
262
|
+
}
|
|
263
|
+
function insertAfterShebang(code, insertion) {
|
|
264
|
+
const nl = code.indexOf("\n");
|
|
265
|
+
if (nl === -1) return `${code}\n${insertion}`;
|
|
266
|
+
return `${code.slice(0, nl + 1)}${insertion}${code.slice(nl + 1)}`;
|
|
267
|
+
}
|
|
268
|
+
//#endregion
|
|
269
|
+
//#region src/plugins/json-loader.ts
|
|
270
|
+
/**
|
|
271
|
+
* Minimal JSON loader to mimic jiti/Node behavior expected by tests:
|
|
272
|
+
* - Default export is the parsed JSON object
|
|
273
|
+
* - Also add a self-reference `default` property on the object (so obj.default === obj)
|
|
274
|
+
* - Provide named exports for top-level properties
|
|
275
|
+
*/
|
|
276
|
+
function createJsonLoader() {
|
|
277
|
+
return {
|
|
278
|
+
name: "unrun-json-loader",
|
|
279
|
+
resolveId: { handler(source, importer) {
|
|
280
|
+
if (!source.endsWith(".json")) return null;
|
|
281
|
+
const basedir = importer ? path.dirname(importer) : process.cwd();
|
|
282
|
+
const resolved = path.resolve(basedir, source);
|
|
283
|
+
let isRequire = false;
|
|
284
|
+
try {
|
|
285
|
+
if (importer) {
|
|
286
|
+
const src = fs.readFileSync(importer, "utf8");
|
|
287
|
+
const escaped = source.replaceAll(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`);
|
|
288
|
+
const pattern = String.raw`\brequire\s*\(\s*['"]${escaped}['"]\s*\)`;
|
|
289
|
+
isRequire = new RegExp(pattern).test(src);
|
|
290
|
+
}
|
|
291
|
+
} catch {}
|
|
292
|
+
return { id: `${resolved}?unrun-json.${isRequire ? "cjs" : "mjs"}` };
|
|
293
|
+
} },
|
|
294
|
+
load: {
|
|
295
|
+
filter: { id: /\?unrun-json\.(?:mjs|cjs)$/ },
|
|
296
|
+
handler(id) {
|
|
297
|
+
try {
|
|
298
|
+
const realId = id.replace(/\?unrun-json\.(?:mjs|cjs)$/, "");
|
|
299
|
+
const src = fs.readFileSync(realId, "utf8");
|
|
300
|
+
const data = JSON.parse(src);
|
|
301
|
+
const jsonLiteral = JSON.stringify(data);
|
|
302
|
+
if (id.endsWith("?unrun-json.cjs")) return { code: `const __data = ${jsonLiteral}\ntry { Object.defineProperty(__data, 'default', { value: __data, enumerable: false, configurable: true }) } catch {}\nmodule.exports = __data\n` };
|
|
303
|
+
const named = Object.keys(data).filter((k) => /^[$A-Z_]\w*$/i.test(k)).map((k) => `export const ${k} = __data[${JSON.stringify(k)}]`).join("\n");
|
|
304
|
+
return { code: [
|
|
305
|
+
`const __data = ${jsonLiteral}`,
|
|
306
|
+
`try { Object.defineProperty(__data, 'default', { value: __data, enumerable: false, configurable: true }) } catch {}`,
|
|
307
|
+
named,
|
|
308
|
+
`export default __data`
|
|
309
|
+
].filter(Boolean).join("\n") };
|
|
310
|
+
} catch {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/plugins/make-cjs-wrapper-async-friendly.ts
|
|
319
|
+
/**
|
|
320
|
+
* Transforms code strings containing CommonJS wrappers to be async-friendly.
|
|
321
|
+
*
|
|
322
|
+
* Rolldown may wrap CommonJS modules in a `__commonJS` function that uses
|
|
323
|
+
* arrow functions. If the wrapped code contains top-level `await`, this can lead
|
|
324
|
+
* to syntax errors since the callback function won't be marked as `async`.
|
|
325
|
+
* This function scans for such patterns and modifies the arrow functions to
|
|
326
|
+
* be `async` if they contain `await` expressions.
|
|
327
|
+
*/
|
|
328
|
+
function createMakeCjsWrapperAsyncFriendlyPlugin() {
|
|
329
|
+
return {
|
|
330
|
+
name: "unrun-make-cjs-wrapper-async-friendly",
|
|
331
|
+
generateBundle: { handler(_outputOptions, bundle) {
|
|
332
|
+
for (const chunk of Object.values(bundle)) {
|
|
333
|
+
if (chunk.type !== "chunk") continue;
|
|
334
|
+
let code = chunk.code;
|
|
335
|
+
const wrapperMarkers = ["__commonJS({", "__commonJSMin("];
|
|
336
|
+
if (!wrapperMarkers.some((marker) => code.includes(marker))) continue;
|
|
337
|
+
const arrowToken = "(() => {";
|
|
338
|
+
const asyncArrowToken = "(async () => {";
|
|
339
|
+
const patchMarker = (marker) => {
|
|
340
|
+
let pos = 0;
|
|
341
|
+
while (true) {
|
|
342
|
+
const markerIdx = code.indexOf(marker, pos);
|
|
343
|
+
if (markerIdx === -1) break;
|
|
344
|
+
const fnStart = code.indexOf(arrowToken, markerIdx);
|
|
345
|
+
if (fnStart === -1) {
|
|
346
|
+
pos = markerIdx + marker.length;
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
const bodyStart = fnStart + 8;
|
|
350
|
+
let i = bodyStart;
|
|
351
|
+
let depth = 1;
|
|
352
|
+
while (i < code.length && depth > 0) {
|
|
353
|
+
const ch = code[i++];
|
|
354
|
+
if (ch === "{") depth++;
|
|
355
|
+
else if (ch === "}") depth--;
|
|
356
|
+
}
|
|
357
|
+
if (depth !== 0) break;
|
|
358
|
+
const bodyEnd = i - 1;
|
|
359
|
+
const body = code.slice(bodyStart, bodyEnd);
|
|
360
|
+
if (/\bawait\b/.test(body) && code.slice(fnStart, fnStart + 14) !== asyncArrowToken) {
|
|
361
|
+
code = `${code.slice(0, fnStart + 1)}async ${code.slice(fnStart + 1)}`;
|
|
362
|
+
pos = fnStart + 1 + 6;
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
pos = bodyEnd;
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
for (const marker of wrapperMarkers) patchMarker(marker);
|
|
369
|
+
if (code !== chunk.code) chunk.code = code;
|
|
370
|
+
}
|
|
371
|
+
} }
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
//#endregion
|
|
375
|
+
//#region src/plugins/require-resolve-fix.ts
|
|
376
|
+
/**
|
|
377
|
+
* Fix require.resolve calls to use the correct base path.
|
|
378
|
+
* Replace __require.resolve("./relative") with proper resolution from original file location.
|
|
379
|
+
*/
|
|
380
|
+
function createRequireResolveFix(options) {
|
|
381
|
+
return {
|
|
382
|
+
name: "unrun-require-resolve-fix",
|
|
383
|
+
generateBundle: { handler(_, bundle) {
|
|
384
|
+
for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") chunk.code = chunk.code.replaceAll(/__require\.resolve\(["']([^"']+)["']\)/g, (match, id) => {
|
|
385
|
+
if (id.startsWith("./") || id.startsWith("../")) try {
|
|
386
|
+
const baseDir = path.dirname(options.path);
|
|
387
|
+
for (const ext of [
|
|
388
|
+
"",
|
|
389
|
+
".ts",
|
|
390
|
+
".js",
|
|
391
|
+
".mts",
|
|
392
|
+
".mjs",
|
|
393
|
+
".cts",
|
|
394
|
+
".cjs"
|
|
395
|
+
]) {
|
|
396
|
+
const testPath = path.resolve(baseDir, id + ext);
|
|
397
|
+
if (fs.existsSync(testPath)) return JSON.stringify(testPath);
|
|
398
|
+
}
|
|
399
|
+
const resolvedPath = path.resolve(baseDir, id);
|
|
400
|
+
return JSON.stringify(resolvedPath);
|
|
401
|
+
} catch {
|
|
402
|
+
return match;
|
|
403
|
+
}
|
|
404
|
+
return match;
|
|
405
|
+
});
|
|
406
|
+
} }
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
//#endregion
|
|
410
|
+
//#region src/plugins/require-typeof-fix.ts
|
|
411
|
+
/**
|
|
412
|
+
* Ensure typeof require in ESM stays undefined to match jiti behavior.
|
|
413
|
+
* Replaces typeof __require with typeof require to maintain compatibility.
|
|
414
|
+
*/
|
|
415
|
+
function createRequireTypeofFix() {
|
|
416
|
+
return {
|
|
417
|
+
name: "unrun-require-typeof-fix",
|
|
418
|
+
generateBundle: { handler(_, bundle) {
|
|
419
|
+
for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") chunk.code = chunk.code.replaceAll(/\btypeof\s+__require\b/g, "typeof require");
|
|
420
|
+
} }
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
//#endregion
|
|
424
|
+
//#region src/plugins/source-context-shims.ts
|
|
425
|
+
/**
|
|
426
|
+
* A rolldown plugin that injects source context shims:
|
|
427
|
+
* - Replaces import.meta.resolve calls with resolved file URLs
|
|
428
|
+
* - Injects per-module __filename/__dirname
|
|
429
|
+
* - Replaces import.meta.url with the source file URL
|
|
430
|
+
* - Replaces import.meta.dirname/import.meta.filename with source paths
|
|
431
|
+
* - Replaces import.meta entire object access
|
|
432
|
+
*/
|
|
433
|
+
function createSourceContextShimsPlugin() {
|
|
434
|
+
return {
|
|
435
|
+
name: "unrun-source-context-shims",
|
|
436
|
+
load: {
|
|
437
|
+
filter: { id: /\.(?:m?[jt]s|c?tsx?)(?:$|\?)/ },
|
|
438
|
+
handler(id) {
|
|
439
|
+
const physicalId = id.split("?")[0].split("#")[0];
|
|
440
|
+
const normalizedPhysicalId = path.normalize(physicalId);
|
|
441
|
+
let code;
|
|
442
|
+
try {
|
|
443
|
+
code = fs.readFileSync(normalizedPhysicalId, "utf8");
|
|
444
|
+
} catch {
|
|
445
|
+
return null;
|
|
446
|
+
}
|
|
447
|
+
if (normalizedPhysicalId.replaceAll("\\", "/").includes("/node_modules/")) return null;
|
|
448
|
+
const file = normalizedPhysicalId;
|
|
449
|
+
const dir = path.dirname(normalizedPhysicalId);
|
|
450
|
+
const url = pathToFileURL(normalizedPhysicalId).href;
|
|
451
|
+
const hasImportMeta = code.includes("import.meta");
|
|
452
|
+
const usesFilename = /\b__filename\b/.test(code);
|
|
453
|
+
const declaresFilename = /\b(?:const|let|var)\s+__filename\b/.test(code);
|
|
454
|
+
const usesDirname = /\b__dirname\b/.test(code);
|
|
455
|
+
const declaresDirname = /\b(?:const|let|var)\s+__dirname\b/.test(code);
|
|
456
|
+
const needsFilenameShim = usesFilename && !declaresFilename;
|
|
457
|
+
const needsDirnameShim = usesDirname && !declaresDirname;
|
|
458
|
+
if (needsFilenameShim || needsDirnameShim || hasImportMeta) {
|
|
459
|
+
const prologueLines = [];
|
|
460
|
+
if (needsFilenameShim) prologueLines.push(`const __filename = ${JSON.stringify(file)}`);
|
|
461
|
+
if (needsDirnameShim) prologueLines.push(`const __dirname = ${JSON.stringify(dir)}`);
|
|
462
|
+
let importMetaShimName = "__unrun_import_meta";
|
|
463
|
+
if (/\b__unrun_import_meta\b/.test(code)) importMetaShimName = "__unrun_import_meta_";
|
|
464
|
+
let transformedCode = code;
|
|
465
|
+
let replacedImportMeta = false;
|
|
466
|
+
let replacedImportMetaObject = false;
|
|
467
|
+
if (hasImportMeta) {
|
|
468
|
+
const resolveRe = /import\s*\.\s*meta\s*\.\s*resolve!?\s*\(\s*(["'])([^"']+)\1\s*\)/y;
|
|
469
|
+
const urlRe = /import\s*\.\s*meta\s*\.\s*url\b/y;
|
|
470
|
+
const dirnameRe = /import\s*\.\s*meta\s*\.\s*dirname\b/y;
|
|
471
|
+
const filenameRe = /import\s*\.\s*meta\s*\.\s*filename\b/y;
|
|
472
|
+
const metaRe = /import\s*\.\s*meta\b/y;
|
|
473
|
+
const parenMetaRe = /\(\s*import\s*\.\s*meta\s*\)/y;
|
|
474
|
+
let out = "";
|
|
475
|
+
let mode = "normal";
|
|
476
|
+
const modeStack = [];
|
|
477
|
+
let templateExprBraceDepth = 0;
|
|
478
|
+
const popMode = () => {
|
|
479
|
+
mode = modeStack.pop() ?? "normal";
|
|
480
|
+
};
|
|
481
|
+
for (let i = 0; i < transformedCode.length;) {
|
|
482
|
+
const ch = transformedCode[i];
|
|
483
|
+
const next = transformedCode[i + 1];
|
|
484
|
+
if (mode === "lineComment") {
|
|
485
|
+
out += ch;
|
|
486
|
+
i += 1;
|
|
487
|
+
if (ch === "\n") popMode();
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
if (mode === "blockComment") {
|
|
491
|
+
out += ch;
|
|
492
|
+
i += 1;
|
|
493
|
+
if (ch === "*" && next === "/") {
|
|
494
|
+
out += "/";
|
|
495
|
+
i += 1;
|
|
496
|
+
popMode();
|
|
497
|
+
}
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
if (mode === "single") {
|
|
501
|
+
out += ch;
|
|
502
|
+
i += 1;
|
|
503
|
+
if (ch === "\\") {
|
|
504
|
+
out += transformedCode[i] ?? "";
|
|
505
|
+
i += 1;
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
if (ch === "'") popMode();
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
if (mode === "double") {
|
|
512
|
+
out += ch;
|
|
513
|
+
i += 1;
|
|
514
|
+
if (ch === "\\") {
|
|
515
|
+
out += transformedCode[i] ?? "";
|
|
516
|
+
i += 1;
|
|
517
|
+
continue;
|
|
518
|
+
}
|
|
519
|
+
if (ch === "\"") popMode();
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
if (mode === "template") {
|
|
523
|
+
out += ch;
|
|
524
|
+
i += 1;
|
|
525
|
+
if (ch === "\\") {
|
|
526
|
+
out += transformedCode[i] ?? "";
|
|
527
|
+
i += 1;
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
if (ch === "`") {
|
|
531
|
+
popMode();
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
if (ch === "$" && next === "{") {
|
|
535
|
+
out += "{";
|
|
536
|
+
i += 1;
|
|
537
|
+
modeStack.push(mode);
|
|
538
|
+
mode = "templateExpr";
|
|
539
|
+
templateExprBraceDepth = 1;
|
|
540
|
+
}
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
if (mode === "templateExpr") {
|
|
544
|
+
if (ch === "{") templateExprBraceDepth += 1;
|
|
545
|
+
else if (ch === "}") {
|
|
546
|
+
templateExprBraceDepth -= 1;
|
|
547
|
+
if (templateExprBraceDepth === 0) {
|
|
548
|
+
out += ch;
|
|
549
|
+
i += 1;
|
|
550
|
+
popMode();
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
if (ch === "/" && next === "/") {
|
|
556
|
+
out += "//";
|
|
557
|
+
i += 2;
|
|
558
|
+
modeStack.push(mode);
|
|
559
|
+
mode = "lineComment";
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
if (ch === "/" && next === "*") {
|
|
563
|
+
out += "/*";
|
|
564
|
+
i += 2;
|
|
565
|
+
modeStack.push(mode);
|
|
566
|
+
mode = "blockComment";
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
if (ch === "'") {
|
|
570
|
+
out += ch;
|
|
571
|
+
i += 1;
|
|
572
|
+
modeStack.push(mode);
|
|
573
|
+
mode = "single";
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
if (ch === "\"") {
|
|
577
|
+
out += ch;
|
|
578
|
+
i += 1;
|
|
579
|
+
modeStack.push(mode);
|
|
580
|
+
mode = "double";
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
if (ch === "`") {
|
|
584
|
+
out += ch;
|
|
585
|
+
i += 1;
|
|
586
|
+
modeStack.push(mode);
|
|
587
|
+
mode = "template";
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
resolveRe.lastIndex = i;
|
|
591
|
+
const resolveMatch = resolveRe.exec(transformedCode);
|
|
592
|
+
if (resolveMatch) {
|
|
593
|
+
const spec = resolveMatch[2];
|
|
594
|
+
const resolvedUrl = pathToFileURL(path.resolve(path.dirname(normalizedPhysicalId), spec)).href;
|
|
595
|
+
out += JSON.stringify(resolvedUrl);
|
|
596
|
+
i = resolveRe.lastIndex;
|
|
597
|
+
replacedImportMeta = true;
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
urlRe.lastIndex = i;
|
|
601
|
+
if (urlRe.test(transformedCode)) {
|
|
602
|
+
out += JSON.stringify(url);
|
|
603
|
+
i = urlRe.lastIndex;
|
|
604
|
+
replacedImportMeta = true;
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
dirnameRe.lastIndex = i;
|
|
608
|
+
if (dirnameRe.test(transformedCode)) {
|
|
609
|
+
out += JSON.stringify(dir);
|
|
610
|
+
i = dirnameRe.lastIndex;
|
|
611
|
+
replacedImportMeta = true;
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
filenameRe.lastIndex = i;
|
|
615
|
+
if (filenameRe.test(transformedCode)) {
|
|
616
|
+
out += JSON.stringify(file);
|
|
617
|
+
i = filenameRe.lastIndex;
|
|
618
|
+
replacedImportMeta = true;
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
parenMetaRe.lastIndex = i;
|
|
622
|
+
if (parenMetaRe.test(transformedCode)) {
|
|
623
|
+
out += importMetaShimName;
|
|
624
|
+
i = parenMetaRe.lastIndex;
|
|
625
|
+
replacedImportMeta = true;
|
|
626
|
+
replacedImportMetaObject = true;
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
metaRe.lastIndex = i;
|
|
630
|
+
if (metaRe.test(transformedCode)) {
|
|
631
|
+
out += importMetaShimName;
|
|
632
|
+
i = metaRe.lastIndex;
|
|
633
|
+
replacedImportMeta = true;
|
|
634
|
+
replacedImportMetaObject = true;
|
|
635
|
+
continue;
|
|
636
|
+
}
|
|
637
|
+
out += ch;
|
|
638
|
+
i += 1;
|
|
639
|
+
}
|
|
640
|
+
if (replacedImportMeta) transformedCode = out;
|
|
641
|
+
}
|
|
642
|
+
if (replacedImportMetaObject) prologueLines.push(`const ${importMetaShimName} = { url: ${JSON.stringify(url)}, filename: ${JSON.stringify(file)}, dirname: ${JSON.stringify(dir)}, env: process.env, resolve: (spec) => new URL(spec, ${JSON.stringify(url)}).href, }`);
|
|
643
|
+
if (prologueLines.length > 0) transformedCode = `${prologueLines.join("\n")}\n${transformedCode}`;
|
|
644
|
+
if (transformedCode !== code) return { code: transformedCode };
|
|
645
|
+
}
|
|
646
|
+
return null;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
//#endregion
|
|
652
|
+
//#region src/utils/bundle.ts
|
|
653
|
+
async function bundle(options) {
|
|
654
|
+
const resolvedTsconfigPath = path.resolve(process.cwd(), "tsconfig.json");
|
|
655
|
+
const tsconfig = existsSync(resolvedTsconfigPath) ? resolvedTsconfigPath : void 0;
|
|
656
|
+
const inputOptions = {
|
|
657
|
+
input: options.path,
|
|
658
|
+
platform: "node",
|
|
659
|
+
external: createExternalResolver(options),
|
|
660
|
+
plugins: [
|
|
661
|
+
createMakeCjsWrapperAsyncFriendlyPlugin(),
|
|
662
|
+
createRequireResolveFix(options),
|
|
663
|
+
createSourceContextShimsPlugin(),
|
|
664
|
+
...options.preset === "jiti" ? [
|
|
665
|
+
createConsoleOutputCustomizer(),
|
|
666
|
+
createJsonLoader(),
|
|
667
|
+
createRequireTypeofFix()
|
|
668
|
+
] : []
|
|
669
|
+
],
|
|
670
|
+
transform: { define: {
|
|
671
|
+
__dirname: JSON.stringify(path.dirname(options.path)),
|
|
672
|
+
__filename: JSON.stringify(options.path),
|
|
673
|
+
"import.meta.url": JSON.stringify(pathToFileURL(options.path).href),
|
|
674
|
+
"import.meta.filename": JSON.stringify(options.path),
|
|
675
|
+
"import.meta.dirname": JSON.stringify(path.dirname(options.path)),
|
|
676
|
+
"import.meta.env": "process.env"
|
|
677
|
+
} },
|
|
678
|
+
logLevel: "silent",
|
|
679
|
+
...options.inputOptions
|
|
680
|
+
};
|
|
681
|
+
if (tsconfig) inputOptions.tsconfig = tsconfig;
|
|
682
|
+
const bundle = await rolldown(inputOptions);
|
|
683
|
+
const outputOptions = {
|
|
684
|
+
format: "esm",
|
|
685
|
+
codeSplitting: false,
|
|
686
|
+
keepNames: true,
|
|
687
|
+
...options.preset === "bundle-require" ? { generatedCode: { symbols: false } } : {},
|
|
688
|
+
...options.outputOptions
|
|
689
|
+
};
|
|
690
|
+
const rolldownOutput = await bundle.generate(outputOptions);
|
|
691
|
+
if (!rolldownOutput.output[0]) throw new Error("[unrun] No output chunk found");
|
|
692
|
+
const files = await bundle.watchFiles;
|
|
693
|
+
return {
|
|
694
|
+
chunk: rolldownOutput.output[0],
|
|
695
|
+
dependencies: files
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
//#endregion
|
|
699
|
+
//#region src/utils/module/clean-module.ts
|
|
700
|
+
/**
|
|
701
|
+
* Clean the module file at the given URL.
|
|
702
|
+
* Deletes the file if it exists.
|
|
703
|
+
* @param moduleUrl - The URL of the module file to be cleaned.
|
|
704
|
+
* @param options - Resolved options.
|
|
705
|
+
*/
|
|
706
|
+
function cleanModule(moduleUrl, options) {
|
|
707
|
+
if (options.debug) return;
|
|
708
|
+
try {
|
|
709
|
+
if (moduleUrl.startsWith("file://")) {
|
|
710
|
+
const filePath = new URL(moduleUrl);
|
|
711
|
+
fs.unlinkSync(filePath);
|
|
712
|
+
}
|
|
713
|
+
} catch (error) {
|
|
714
|
+
if (error.code !== "ENOENT") throw error;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
//#endregion
|
|
718
|
+
//#region src/utils/module/exec-module.ts
|
|
719
|
+
/**
|
|
720
|
+
* Execute the module at the given URL, in a separate Node.js process.
|
|
721
|
+
* @param moduleUrl - The URL of the module to execute.
|
|
722
|
+
* @param args - Additional command-line arguments to pass to the Node.js process.
|
|
723
|
+
* @returns A promise that resolves when the module execution is complete.
|
|
724
|
+
*/
|
|
725
|
+
function execModule(moduleUrl, args = []) {
|
|
726
|
+
return new Promise((resolve, reject) => {
|
|
727
|
+
const nodePath = process.execPath;
|
|
728
|
+
const spawnArgs = [];
|
|
729
|
+
if (moduleUrl.startsWith("data:")) {
|
|
730
|
+
const commaIndex = moduleUrl.indexOf(",");
|
|
731
|
+
if (commaIndex === -1) {
|
|
732
|
+
reject(/* @__PURE__ */ new Error("[unrun]: Invalid data URL for module execution"));
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
const metadata = moduleUrl.slice(5, commaIndex);
|
|
736
|
+
const payload = moduleUrl.slice(commaIndex + 1);
|
|
737
|
+
const code = metadata.endsWith(";base64") ? Buffer$1.from(payload, "base64").toString("utf8") : decodeURIComponent(payload);
|
|
738
|
+
spawnArgs.push("--input-type=module", "--eval", code);
|
|
739
|
+
} else {
|
|
740
|
+
let modulePath = moduleUrl;
|
|
741
|
+
if (moduleUrl.startsWith("file://")) try {
|
|
742
|
+
modulePath = fileURLToPath(moduleUrl);
|
|
743
|
+
} catch (error) {
|
|
744
|
+
reject(/* @__PURE__ */ new Error(`[unrun]: Failed to resolve module URL ${moduleUrl}: ${error.message}`));
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
spawnArgs.push(modulePath);
|
|
748
|
+
}
|
|
749
|
+
const childProcess = spawn(nodePath, [...spawnArgs, ...args], { stdio: [
|
|
750
|
+
"inherit",
|
|
751
|
+
"inherit",
|
|
752
|
+
"inherit"
|
|
753
|
+
] });
|
|
754
|
+
const lifecycleSignals = [
|
|
755
|
+
"SIGINT",
|
|
756
|
+
"SIGTERM",
|
|
757
|
+
"SIGQUIT"
|
|
758
|
+
];
|
|
759
|
+
const signalListeners = /* @__PURE__ */ new Map();
|
|
760
|
+
let exitListener;
|
|
761
|
+
const cleanupChildProcess = (signal) => {
|
|
762
|
+
if (childProcess.killed || childProcess.exitCode !== null) return;
|
|
763
|
+
try {
|
|
764
|
+
childProcess.kill(signal);
|
|
765
|
+
} catch {}
|
|
766
|
+
};
|
|
767
|
+
const removeLifecycleListeners = () => {
|
|
768
|
+
if (exitListener) {
|
|
769
|
+
process.removeListener("exit", exitListener);
|
|
770
|
+
exitListener = void 0;
|
|
771
|
+
}
|
|
772
|
+
for (const [signal, listener] of signalListeners) process.removeListener(signal, listener);
|
|
773
|
+
signalListeners.clear();
|
|
774
|
+
};
|
|
775
|
+
exitListener = () => {
|
|
776
|
+
cleanupChildProcess();
|
|
777
|
+
};
|
|
778
|
+
process.on("exit", exitListener);
|
|
779
|
+
for (const signal of lifecycleSignals) {
|
|
780
|
+
const listener = () => {
|
|
781
|
+
cleanupChildProcess(signal);
|
|
782
|
+
removeLifecycleListeners();
|
|
783
|
+
process.nextTick(() => {
|
|
784
|
+
process.kill(process.pid, signal);
|
|
785
|
+
});
|
|
786
|
+
};
|
|
787
|
+
signalListeners.set(signal, listener);
|
|
788
|
+
process.on(signal, listener);
|
|
789
|
+
}
|
|
790
|
+
childProcess.on("close", (exitCode) => {
|
|
791
|
+
removeLifecycleListeners();
|
|
792
|
+
resolve({ exitCode: exitCode ?? 0 });
|
|
793
|
+
});
|
|
794
|
+
childProcess.on("error", (error) => {
|
|
795
|
+
removeLifecycleListeners();
|
|
796
|
+
reject(/* @__PURE__ */ new Error(`[unrun]: Failed to start child process: ${error.message}`));
|
|
797
|
+
});
|
|
798
|
+
});
|
|
799
|
+
}
|
|
800
|
+
//#endregion
|
|
801
|
+
//#region src/utils/module/write-module.ts
|
|
802
|
+
function sanitize(name) {
|
|
803
|
+
return name.replaceAll(/[^\w.-]/g, "_");
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* Writes a module to the filesystem.
|
|
807
|
+
* @param code - The JavaScript code to be written as a module.
|
|
808
|
+
* @param options - Resolved options.
|
|
809
|
+
* @returns The file URL of the written module.
|
|
810
|
+
*/
|
|
811
|
+
function writeModule(code, options) {
|
|
812
|
+
const filenameHint = path.basename(options.path);
|
|
813
|
+
let moduleUrl = "";
|
|
814
|
+
try {
|
|
815
|
+
const randomKey = crypto.randomBytes(16).toString("hex");
|
|
816
|
+
const fname = `${filenameHint ? `${sanitize(filenameHint)}.` : ""}${randomKey}.mjs`;
|
|
817
|
+
const projectNodeModules = path.join(process.cwd(), "node_modules");
|
|
818
|
+
const outDir = path.join(projectNodeModules, ".unrun");
|
|
819
|
+
const outFile = path.join(outDir, fname);
|
|
820
|
+
if (!fs.existsSync(outFile)) try {
|
|
821
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
822
|
+
fs.writeFileSync(outFile, code, "utf8");
|
|
823
|
+
} catch {
|
|
824
|
+
const fallbackDir = path.join(tmpdir(), "unrun-cache");
|
|
825
|
+
const fallbackFile = path.join(fallbackDir, fname);
|
|
826
|
+
fs.mkdirSync(fallbackDir, { recursive: true });
|
|
827
|
+
fs.writeFileSync(fallbackFile, code, "utf8");
|
|
828
|
+
moduleUrl = pathToFileURL(fallbackFile).href;
|
|
829
|
+
}
|
|
830
|
+
moduleUrl = moduleUrl || pathToFileURL(outFile).href;
|
|
831
|
+
} catch {
|
|
832
|
+
moduleUrl = `data:text/javascript;base64,${Buffer$1.from(code).toString("base64")}`;
|
|
833
|
+
}
|
|
834
|
+
return moduleUrl;
|
|
835
|
+
}
|
|
836
|
+
//#endregion
|
|
837
|
+
//#region src/utils/module/load-module.ts
|
|
838
|
+
/**
|
|
839
|
+
* Import a JS module from code string.
|
|
840
|
+
* Write ESM code to a temp file (prefer project-local node_modules/.unrun) and import it.
|
|
841
|
+
* @param code - The JavaScript code to be imported as a module.
|
|
842
|
+
* @param options - Resolved options.
|
|
843
|
+
* @returns The imported module.
|
|
844
|
+
*/
|
|
845
|
+
async function loadModule(code, options) {
|
|
846
|
+
const moduleUrl = writeModule(code, options);
|
|
847
|
+
let _module;
|
|
848
|
+
try {
|
|
849
|
+
_module = await import(moduleUrl);
|
|
850
|
+
} finally {
|
|
851
|
+
cleanModule(moduleUrl, options);
|
|
852
|
+
}
|
|
853
|
+
return _module;
|
|
854
|
+
}
|
|
855
|
+
//#endregion
|
|
856
|
+
//#region src/index.ts
|
|
857
|
+
/**
|
|
858
|
+
* Loads a module with JIT transpilation based on the provided options.
|
|
859
|
+
*
|
|
860
|
+
* @param options - The options for loading the module.
|
|
861
|
+
* @returns A promise that resolves to the loaded module.
|
|
862
|
+
*/
|
|
863
|
+
async function unrun(options) {
|
|
864
|
+
const resolvedOptions = resolveOptions(options);
|
|
865
|
+
const output = await bundle(resolvedOptions);
|
|
866
|
+
let module;
|
|
867
|
+
try {
|
|
868
|
+
module = await loadModule(output.chunk.code, resolvedOptions);
|
|
869
|
+
} catch (error) {
|
|
870
|
+
throw new Error(`[unrun] Import failed (code length: ${output.chunk.code.length}): ${error.message}`, { cause: error });
|
|
871
|
+
}
|
|
872
|
+
return {
|
|
873
|
+
module: preset(resolvedOptions, module),
|
|
874
|
+
dependencies: output.dependencies
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* Loads a module with JIT transpilation based on the provided options.
|
|
879
|
+
* This function runs synchronously using a worker thread.
|
|
880
|
+
*
|
|
881
|
+
* @param options - The options for loading the module.
|
|
882
|
+
* @returns The loaded module.
|
|
883
|
+
*/
|
|
884
|
+
function unrunSync(options) {
|
|
885
|
+
const { createSyncFn } = __require("synckit");
|
|
886
|
+
return createSyncFn(__require.resolve("./sync/worker.mjs"), { tsRunner: "node" })(options);
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* Runs a given module with JIT transpilation based on the provided options.
|
|
890
|
+
* This function does not return the module, as it simply executes it.
|
|
891
|
+
* Corresponds to the CLI behavior.
|
|
892
|
+
*
|
|
893
|
+
* @param options - The options for running the module.
|
|
894
|
+
* @param args - Additional command-line arguments to pass to the module.
|
|
895
|
+
*/
|
|
896
|
+
async function unrunCli(options, args = []) {
|
|
897
|
+
const resolvedOptions = resolveOptions(options);
|
|
898
|
+
const output = await bundle(resolvedOptions);
|
|
899
|
+
const moduleUrl = writeModule(output.chunk.code, resolvedOptions);
|
|
900
|
+
let cliResult;
|
|
901
|
+
try {
|
|
902
|
+
cliResult = await execModule(moduleUrl, args);
|
|
903
|
+
} catch (error) {
|
|
904
|
+
throw new Error(`[unrun] Run failed (code length: ${output.chunk.code.length}): ${error.message}`, { cause: error });
|
|
905
|
+
}
|
|
906
|
+
cleanModule(moduleUrl, resolvedOptions);
|
|
907
|
+
return cliResult;
|
|
908
|
+
}
|
|
909
|
+
//#endregion
|
|
910
|
+
export { unrunCli as n, unrunSync as r, unrun as t };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { t as unrun } from "../src-DgjiW5nf.mjs";
|
|
2
|
+
import { runAsWorker } from "synckit";
|
|
3
|
+
//#region src/sync/worker.ts
|
|
4
|
+
function cloneForTransfer(value, seen = /* @__PURE__ */ new WeakMap()) {
|
|
5
|
+
if (typeof value === "function") throw new TypeError("[unrun] unrunSync cannot return functions");
|
|
6
|
+
if (value === null || typeof value !== "object") return value;
|
|
7
|
+
const objectValue = value;
|
|
8
|
+
if (seen.has(objectValue)) return seen.get(objectValue);
|
|
9
|
+
if (Array.isArray(value)) {
|
|
10
|
+
const clone = [];
|
|
11
|
+
seen.set(objectValue, clone);
|
|
12
|
+
for (const item of value) clone.push(cloneForTransfer(item, seen));
|
|
13
|
+
return clone;
|
|
14
|
+
}
|
|
15
|
+
if (isModuleNamespace(value)) {
|
|
16
|
+
const clone = Object.create(null);
|
|
17
|
+
seen.set(objectValue, clone);
|
|
18
|
+
for (const key of Object.keys(value)) {
|
|
19
|
+
const nestedValue = value[key];
|
|
20
|
+
clone[key] = cloneForTransfer(nestedValue, seen);
|
|
21
|
+
}
|
|
22
|
+
return clone;
|
|
23
|
+
}
|
|
24
|
+
if (typeof structuredClone === "function") try {
|
|
25
|
+
return structuredClone(value);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (!isDataCloneError(error)) throw error;
|
|
28
|
+
}
|
|
29
|
+
const clone = {};
|
|
30
|
+
seen.set(objectValue, clone);
|
|
31
|
+
for (const [key, child] of Object.entries(value)) clone[key] = cloneForTransfer(child, seen);
|
|
32
|
+
return clone;
|
|
33
|
+
}
|
|
34
|
+
function isModuleNamespace(value) {
|
|
35
|
+
if (!value || typeof value !== "object") return false;
|
|
36
|
+
return Object.prototype.toString.call(value) === "[object Module]";
|
|
37
|
+
}
|
|
38
|
+
function isDataCloneError(error) {
|
|
39
|
+
if (!error || typeof error !== "object") return false;
|
|
40
|
+
if (!("name" in error)) return false;
|
|
41
|
+
return error.name === "DataCloneError";
|
|
42
|
+
}
|
|
43
|
+
runAsWorker(async (...args) => {
|
|
44
|
+
const options = args[0];
|
|
45
|
+
return cloneForTransfer(await unrun(options));
|
|
46
|
+
});
|
|
47
|
+
//#endregion
|
|
48
|
+
export {};
|