@quiteer/vite 0.0.7 → 0.1.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/bin/qvite.mjs +74 -7
- package/dist/index.d.mts +12 -8
- package/dist/index.mjs +6 -5906
- package/package.json +4 -4
- package/dist/bin/context-Db5EuGKU-B3vpL0eS.mjs +0 -24
- package/dist/bin/dist-BmyFpZwL.mjs +0 -7
- package/dist/bin/dist-BniM_x9D.mjs +0 -5256
- package/dist/bin/dist-Bvgk2hb8.mjs +0 -187
- package/dist/bin/dist-CjNY_432.mjs +0 -473
- package/dist/bin/dist-DQNZhGEj.mjs +0 -10562
- package/dist/bin/esm-CQYKr9An.mjs +0 -1557
- package/dist/bin/experimental-index-DiVJ_oZg.mjs +0 -71
- package/dist/bin/resolver-DymnxKPB-UI_9xIg2.mjs +0 -16
- package/dist/bin/src-BwxUhqZU-Dr1MNcyS.mjs +0 -5046
- package/dist/bin/tsc-TmK__neM.mjs +0 -406
|
@@ -1,187 +0,0 @@
|
|
|
1
|
-
//#region ../../node_modules/.pnpm/birpc@2.7.0/node_modules/birpc/dist/index.mjs
|
|
2
|
-
const TYPE_REQUEST = "q";
|
|
3
|
-
const TYPE_RESPONSE = "s";
|
|
4
|
-
const DEFAULT_TIMEOUT = 6e4;
|
|
5
|
-
function defaultSerialize(i) {
|
|
6
|
-
return i;
|
|
7
|
-
}
|
|
8
|
-
const defaultDeserialize = defaultSerialize;
|
|
9
|
-
const { clearTimeout, setTimeout } = globalThis;
|
|
10
|
-
const random = Math.random.bind(Math);
|
|
11
|
-
function createBirpc(functions, options) {
|
|
12
|
-
const { post, on, off = () => {}, eventNames = [], serialize = defaultSerialize, deserialize = defaultDeserialize, resolver, bind = "rpc", timeout = DEFAULT_TIMEOUT } = options;
|
|
13
|
-
const rpcPromiseMap = /* @__PURE__ */ new Map();
|
|
14
|
-
let _promiseInit;
|
|
15
|
-
let closed = false;
|
|
16
|
-
const rpc = new Proxy({}, { get(_, method) {
|
|
17
|
-
if (method === "$functions") return functions;
|
|
18
|
-
if (method === "$close") return close;
|
|
19
|
-
if (method === "$rejectPendingCalls") return rejectPendingCalls;
|
|
20
|
-
if (method === "$closed") return closed;
|
|
21
|
-
if (method === "then" && !eventNames.includes("then") && !("then" in functions)) return void 0;
|
|
22
|
-
const sendEvent = async (...args) => {
|
|
23
|
-
await post(serialize({
|
|
24
|
-
m: method,
|
|
25
|
-
a: args,
|
|
26
|
-
t: TYPE_REQUEST
|
|
27
|
-
}));
|
|
28
|
-
};
|
|
29
|
-
if (eventNames.includes(method)) {
|
|
30
|
-
sendEvent.asEvent = sendEvent;
|
|
31
|
-
return sendEvent;
|
|
32
|
-
}
|
|
33
|
-
const sendCall = async (...args) => {
|
|
34
|
-
if (closed) throw new Error(`[birpc] rpc is closed, cannot call "${method}"`);
|
|
35
|
-
if (_promiseInit) try {
|
|
36
|
-
await _promiseInit;
|
|
37
|
-
} finally {
|
|
38
|
-
_promiseInit = void 0;
|
|
39
|
-
}
|
|
40
|
-
let { promise, resolve, reject } = createPromiseWithResolvers();
|
|
41
|
-
const id = nanoid();
|
|
42
|
-
let timeoutId;
|
|
43
|
-
const _req = {
|
|
44
|
-
m: method,
|
|
45
|
-
a: args,
|
|
46
|
-
i: id,
|
|
47
|
-
t: TYPE_REQUEST
|
|
48
|
-
};
|
|
49
|
-
async function handler(req = _req) {
|
|
50
|
-
if (timeout >= 0) {
|
|
51
|
-
timeoutId = setTimeout(() => {
|
|
52
|
-
try {
|
|
53
|
-
if (options.onTimeoutError?.(method, args) !== true) throw new Error(`[birpc] timeout on calling "${method}"`);
|
|
54
|
-
} catch (e) {
|
|
55
|
-
reject(e);
|
|
56
|
-
}
|
|
57
|
-
rpcPromiseMap.delete(id);
|
|
58
|
-
}, timeout);
|
|
59
|
-
if (typeof timeoutId === "object") timeoutId = timeoutId.unref?.();
|
|
60
|
-
}
|
|
61
|
-
rpcPromiseMap.set(id, {
|
|
62
|
-
resolve,
|
|
63
|
-
reject,
|
|
64
|
-
timeoutId,
|
|
65
|
-
method
|
|
66
|
-
});
|
|
67
|
-
await post(serialize(req));
|
|
68
|
-
return promise;
|
|
69
|
-
}
|
|
70
|
-
try {
|
|
71
|
-
if (options.onRequest) await options.onRequest(_req, handler, resolve);
|
|
72
|
-
else await handler();
|
|
73
|
-
} catch (e) {
|
|
74
|
-
clearTimeout(timeoutId);
|
|
75
|
-
rpcPromiseMap.delete(id);
|
|
76
|
-
if (options.onGeneralError?.(e) !== true) throw e;
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
return promise;
|
|
80
|
-
};
|
|
81
|
-
sendCall.asEvent = sendEvent;
|
|
82
|
-
return sendCall;
|
|
83
|
-
} });
|
|
84
|
-
function close(customError) {
|
|
85
|
-
closed = true;
|
|
86
|
-
rpcPromiseMap.forEach(({ reject, method }) => {
|
|
87
|
-
const error = /* @__PURE__ */ new Error(`[birpc] rpc is closed, cannot call "${method}"`);
|
|
88
|
-
if (customError) {
|
|
89
|
-
customError.cause ??= error;
|
|
90
|
-
return reject(customError);
|
|
91
|
-
}
|
|
92
|
-
reject(error);
|
|
93
|
-
});
|
|
94
|
-
rpcPromiseMap.clear();
|
|
95
|
-
off(onMessage);
|
|
96
|
-
}
|
|
97
|
-
function rejectPendingCalls(handler) {
|
|
98
|
-
const handlerResults = Array.from(rpcPromiseMap.values()).map(({ method, reject }) => {
|
|
99
|
-
if (!handler) return reject(/* @__PURE__ */ new Error(`[birpc]: rejected pending call "${method}".`));
|
|
100
|
-
return handler({
|
|
101
|
-
method,
|
|
102
|
-
reject
|
|
103
|
-
});
|
|
104
|
-
});
|
|
105
|
-
rpcPromiseMap.clear();
|
|
106
|
-
return handlerResults;
|
|
107
|
-
}
|
|
108
|
-
async function onMessage(data, ...extra) {
|
|
109
|
-
let msg;
|
|
110
|
-
try {
|
|
111
|
-
msg = deserialize(data);
|
|
112
|
-
} catch (e) {
|
|
113
|
-
if (options.onGeneralError?.(e) !== true) throw e;
|
|
114
|
-
return;
|
|
115
|
-
}
|
|
116
|
-
if (msg.t === TYPE_REQUEST) {
|
|
117
|
-
const { m: method, a: args } = msg;
|
|
118
|
-
let result, error;
|
|
119
|
-
const fn = await (resolver ? resolver(method, functions[method]) : functions[method]);
|
|
120
|
-
if (!fn) error = /* @__PURE__ */ new Error(`[birpc] function "${method}" not found`);
|
|
121
|
-
else try {
|
|
122
|
-
result = await fn.apply(bind === "rpc" ? rpc : functions, args);
|
|
123
|
-
} catch (e) {
|
|
124
|
-
error = e;
|
|
125
|
-
}
|
|
126
|
-
if (msg.i) {
|
|
127
|
-
if (error && options.onError) options.onError(error, method, args);
|
|
128
|
-
if (error && options.onFunctionError) {
|
|
129
|
-
if (options.onFunctionError(error, method, args) === true) return;
|
|
130
|
-
}
|
|
131
|
-
if (!error) try {
|
|
132
|
-
await post(serialize({
|
|
133
|
-
t: TYPE_RESPONSE,
|
|
134
|
-
i: msg.i,
|
|
135
|
-
r: result
|
|
136
|
-
}), ...extra);
|
|
137
|
-
return;
|
|
138
|
-
} catch (e) {
|
|
139
|
-
error = e;
|
|
140
|
-
if (options.onGeneralError?.(e, method, args) !== true) throw e;
|
|
141
|
-
}
|
|
142
|
-
try {
|
|
143
|
-
await post(serialize({
|
|
144
|
-
t: TYPE_RESPONSE,
|
|
145
|
-
i: msg.i,
|
|
146
|
-
e: error
|
|
147
|
-
}), ...extra);
|
|
148
|
-
} catch (e) {
|
|
149
|
-
if (options.onGeneralError?.(e, method, args) !== true) throw e;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
} else {
|
|
153
|
-
const { i: ack, r: result, e: error } = msg;
|
|
154
|
-
const promise = rpcPromiseMap.get(ack);
|
|
155
|
-
if (promise) {
|
|
156
|
-
clearTimeout(promise.timeoutId);
|
|
157
|
-
if (error) promise.reject(error);
|
|
158
|
-
else promise.resolve(result);
|
|
159
|
-
}
|
|
160
|
-
rpcPromiseMap.delete(ack);
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
_promiseInit = on(onMessage);
|
|
164
|
-
return rpc;
|
|
165
|
-
}
|
|
166
|
-
function createPromiseWithResolvers() {
|
|
167
|
-
let resolve;
|
|
168
|
-
let reject;
|
|
169
|
-
return {
|
|
170
|
-
promise: new Promise((res, rej) => {
|
|
171
|
-
resolve = res;
|
|
172
|
-
reject = rej;
|
|
173
|
-
}),
|
|
174
|
-
resolve,
|
|
175
|
-
reject
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
|
|
179
|
-
function nanoid(size = 21) {
|
|
180
|
-
let id = "";
|
|
181
|
-
let i = size;
|
|
182
|
-
while (i--) id += urlAlphabet[random() * 64 | 0];
|
|
183
|
-
return id;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
//#endregion
|
|
187
|
-
export { DEFAULT_TIMEOUT, createBirpc };
|
|
@@ -1,473 +0,0 @@
|
|
|
1
|
-
import { a as rolldown } from "./src-BwxUhqZU-Dr1MNcyS.mjs";
|
|
2
|
-
import "./dist-BmyFpZwL.mjs";
|
|
3
|
-
import { createRequire } from "node:module";
|
|
4
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
|
-
import process from "node:process";
|
|
6
|
-
import path from "node:path";
|
|
7
|
-
import { tmpdir } from "node:os";
|
|
8
|
-
import fs, { existsSync } from "node:fs";
|
|
9
|
-
import { spawn } from "node:child_process";
|
|
10
|
-
import { Buffer } from "node:buffer";
|
|
11
|
-
import crypto from "node:crypto";
|
|
12
|
-
|
|
13
|
-
//#region ../../node_modules/.pnpm/unrun@0.2.6_synckit@0.11.11/node_modules/unrun/dist/src-BW3bFBxp.mjs
|
|
14
|
-
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
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
|
-
/**
|
|
28
|
-
* Normalize a path-like input to a string path.
|
|
29
|
-
* @param pathLike The path-like input (string or URL).
|
|
30
|
-
* @returns The normalized string path.
|
|
31
|
-
*/
|
|
32
|
-
function normalizePath(pathLike) {
|
|
33
|
-
if (!pathLike) return "index.ts";
|
|
34
|
-
if (pathLike instanceof URL) {
|
|
35
|
-
if (pathLike.protocol === "file:") return fileURLToPath(pathLike);
|
|
36
|
-
return pathLike.href;
|
|
37
|
-
}
|
|
38
|
-
if (typeof pathLike === "string") {
|
|
39
|
-
if (!pathLike.startsWith("file:")) return pathLike;
|
|
40
|
-
try {
|
|
41
|
-
return fileURLToPath(pathLike);
|
|
42
|
-
} catch {
|
|
43
|
-
try {
|
|
44
|
-
return fileURLToPath(new URL(pathLike));
|
|
45
|
-
} catch {
|
|
46
|
-
return pathLike;
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
return String(pathLike);
|
|
51
|
-
}
|
|
52
|
-
function resolveOptions(options = {}) {
|
|
53
|
-
const resolvedOptions = {
|
|
54
|
-
path: path.resolve(process.cwd(), normalizePath(options.path)),
|
|
55
|
-
debug: options.debug || false,
|
|
56
|
-
preset: options.preset || "none",
|
|
57
|
-
inputOptions: options.inputOptions,
|
|
58
|
-
outputOptions: options.outputOptions
|
|
59
|
-
};
|
|
60
|
-
if (!fs.existsSync(resolvedOptions.path)) throw new Error(`[unrun] File not found: ${resolvedOptions.path}`);
|
|
61
|
-
if (!new Set([
|
|
62
|
-
"none",
|
|
63
|
-
"jiti",
|
|
64
|
-
"bundle-require"
|
|
65
|
-
]).has(resolvedOptions.preset)) throw new Error(`[unrun] Invalid preset "${resolvedOptions.preset}" (expected: none | jiti | bundle-require)`);
|
|
66
|
-
return resolvedOptions;
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Attach a util.inspect customizer to namespace-like module objects produced by rolldown helpers
|
|
70
|
-
* so console.log prints concrete values instead of [Getter], while preserving live bindings.
|
|
71
|
-
*
|
|
72
|
-
* Cleaner strategy: inject a tiny helper at the top of the chunk and minimally augment
|
|
73
|
-
* rolldown helpers (__export and __copyProps) right inside their definitions, before use.
|
|
74
|
-
*/
|
|
75
|
-
function createConsoleOutputCustomizer() {
|
|
76
|
-
return {
|
|
77
|
-
name: "unrun-console-output-customizer",
|
|
78
|
-
generateBundle: { handler(_, bundle$1) {
|
|
79
|
-
for (const chunk of Object.values(bundle$1)) {
|
|
80
|
-
if (chunk.type !== "chunk") continue;
|
|
81
|
-
if (!/__unrun__setInspect\b/.test(chunk.code)) {
|
|
82
|
-
const helper = [
|
|
83
|
-
"(function(){",
|
|
84
|
-
" function __unrun__fmt(names, getter, np){",
|
|
85
|
-
" var onlyDefault = names.length === 1 && names[0] === \"default\";",
|
|
86
|
-
" var o = np ? Object.create(null) : {};",
|
|
87
|
-
" for (var i = 0; i < names.length; i++) {",
|
|
88
|
-
" var n = names[i];",
|
|
89
|
-
" try { o[n] = getter(n) } catch {}",
|
|
90
|
-
" }",
|
|
91
|
-
" if (onlyDefault) {",
|
|
92
|
-
" try {",
|
|
93
|
-
" var s = JSON.stringify(o.default);",
|
|
94
|
-
" if (s !== undefined) {",
|
|
95
|
-
" s = s.replace(/\"([^\"]+)\":/g, \"$1: \").replace(/,/g, \", \").replace(/{/g, \"{ \").replace(/}/g, \" }\");",
|
|
96
|
-
" return \"[Module: null prototype] { default: \" + s + \" }\";",
|
|
97
|
-
" }",
|
|
98
|
-
" } catch {}",
|
|
99
|
-
" return \"[Module: null prototype] { default: \" + String(o.default) + \" }\";",
|
|
100
|
-
" }",
|
|
101
|
-
" return o;",
|
|
102
|
-
" }",
|
|
103
|
-
" function __unrun__setInspect(obj, names, getter, np){",
|
|
104
|
-
" try {",
|
|
105
|
-
" var __insp = Symbol.for('nodejs.util.inspect.custom')",
|
|
106
|
-
" Object.defineProperty(obj, __insp, {",
|
|
107
|
-
" value: function(){ return __unrun__fmt(names, getter, np) },",
|
|
108
|
-
" enumerable: false, configurable: true",
|
|
109
|
-
" })",
|
|
110
|
-
" } catch {}",
|
|
111
|
-
" return obj;",
|
|
112
|
-
" }",
|
|
113
|
-
" try { Object.defineProperty(globalThis, \"__unrun__setInspect\", { value: __unrun__setInspect, enumerable: false }) } catch {}",
|
|
114
|
-
"})();"
|
|
115
|
-
].join("\n");
|
|
116
|
-
if (chunk.code.startsWith("#!")) {
|
|
117
|
-
const nl = chunk.code.indexOf("\n");
|
|
118
|
-
if (nl !== -1) chunk.code = `${chunk.code.slice(0, nl + 1)}${helper}\n${chunk.code.slice(nl + 1)}`;
|
|
119
|
-
else chunk.code = `${helper}\n${chunk.code}`;
|
|
120
|
-
} else chunk.code = `${helper}\n${chunk.code}`;
|
|
121
|
-
}
|
|
122
|
-
chunk.code = chunk.code.replace(/var\s+__export\s*=\s*\(all\)\s*=>\s*\{([\s\S]*?)return\s+target;\s*\}/, (_m, body) => {
|
|
123
|
-
return `var __export = (all) => {\n${[
|
|
124
|
-
body,
|
|
125
|
-
" try {",
|
|
126
|
-
" var __names = Object.keys(all).filter(function(n){ return n !== \"__esModule\" })",
|
|
127
|
-
" __unrun__setInspect(target, __names, function(n){ return all[n]() }, false)",
|
|
128
|
-
" } catch {}",
|
|
129
|
-
" return target;"
|
|
130
|
-
].join("\n")}\n}`;
|
|
131
|
-
});
|
|
132
|
-
chunk.code = chunk.code.replace(/var\s+__copyProps\s*=\s*\(to,\s*from,\s*except,\s*desc\)\s*=>\s*\{([\s\S]*?)return\s+to;\s*\};/, (_m, body) => {
|
|
133
|
-
return `var __copyProps = (to, from, except, desc) => {\n${[
|
|
134
|
-
body,
|
|
135
|
-
" try {",
|
|
136
|
-
" var __names = Object.keys(to).filter(function(n){ return n !== \"__esModule\" })",
|
|
137
|
-
" __unrun__setInspect(to, __names, function(n){ return to[n] }, true)",
|
|
138
|
-
" } catch {}",
|
|
139
|
-
" return to;"
|
|
140
|
-
].join("\n")}\n};`;
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
} }
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Minimal JSON loader to mimic jiti/Node behavior expected by tests:
|
|
148
|
-
* - Default export is the parsed JSON object
|
|
149
|
-
* - Also add a self-reference `default` property on the object (so obj.default === obj)
|
|
150
|
-
* - Provide named exports for top-level properties
|
|
151
|
-
*/
|
|
152
|
-
function createJsonLoader() {
|
|
153
|
-
return {
|
|
154
|
-
name: "unrun-json-loader",
|
|
155
|
-
resolveId: { handler(source, importer) {
|
|
156
|
-
if (!source.endsWith(".json")) return null;
|
|
157
|
-
const basedir = importer ? path.dirname(importer) : process.cwd();
|
|
158
|
-
const resolved = path.resolve(basedir, source);
|
|
159
|
-
let isRequire = false;
|
|
160
|
-
try {
|
|
161
|
-
if (importer) {
|
|
162
|
-
const src = fs.readFileSync(importer, "utf8");
|
|
163
|
-
const escaped = source.replaceAll(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`);
|
|
164
|
-
const pattern = String.raw`\brequire\s*\(\s*['"]${escaped}['"]\s*\)`;
|
|
165
|
-
isRequire = new RegExp(pattern).test(src);
|
|
166
|
-
}
|
|
167
|
-
} catch {}
|
|
168
|
-
return { id: `${resolved}?unrun-json.${isRequire ? "cjs" : "mjs"}` };
|
|
169
|
-
} },
|
|
170
|
-
load: {
|
|
171
|
-
filter: { id: /\?unrun-json\.(?:mjs|cjs)$/ },
|
|
172
|
-
handler(id) {
|
|
173
|
-
try {
|
|
174
|
-
const realId = id.replace(/\?unrun-json\.(?:mjs|cjs)$/, "");
|
|
175
|
-
const src = fs.readFileSync(realId, "utf8");
|
|
176
|
-
const data = JSON.parse(src);
|
|
177
|
-
const jsonLiteral = JSON.stringify(data);
|
|
178
|
-
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` };
|
|
179
|
-
const named = Object.keys(data).filter((k) => /^[$A-Z_]\w*$/i.test(k)).map((k) => `export const ${k} = __data[${JSON.stringify(k)}]`).join("\n");
|
|
180
|
-
return { code: [
|
|
181
|
-
`const __data = ${jsonLiteral}`,
|
|
182
|
-
`try { Object.defineProperty(__data, 'default', { value: __data, enumerable: false, configurable: true }) } catch {}`,
|
|
183
|
-
named,
|
|
184
|
-
`export default __data`
|
|
185
|
-
].filter(Boolean).join("\n") };
|
|
186
|
-
} catch {
|
|
187
|
-
return null;
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
};
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Transforms code strings containing CommonJS wrappers to be async-friendly.
|
|
195
|
-
*
|
|
196
|
-
* Rolldown may wrap CommonJS modules in a `__commonJS` function that uses
|
|
197
|
-
* arrow functions. If the wrapped code contains top-level `await`, this can lead
|
|
198
|
-
* to syntax errors since the callback function won't be marked as `async`.
|
|
199
|
-
* This function scans for such patterns and modifies the arrow functions to
|
|
200
|
-
* be `async` if they contain `await` expressions.
|
|
201
|
-
*/
|
|
202
|
-
function createMakeCjsWrapperAsyncFriendlyPlugin() {
|
|
203
|
-
return {
|
|
204
|
-
name: "unrun-make-cjs-wrapper-async-friendly",
|
|
205
|
-
generateBundle: { handler(_outputOptions, bundle$1) {
|
|
206
|
-
for (const chunk of Object.values(bundle$1)) {
|
|
207
|
-
if (chunk.type !== "chunk") continue;
|
|
208
|
-
let code = chunk.code;
|
|
209
|
-
const marker = "__commonJS({";
|
|
210
|
-
if (!code.includes(marker)) return;
|
|
211
|
-
let pos = 0;
|
|
212
|
-
const arrowToken = "(() => {";
|
|
213
|
-
const asyncArrowToken = "(async () => {";
|
|
214
|
-
while (true) {
|
|
215
|
-
const markerIdx = code.indexOf(marker, pos);
|
|
216
|
-
if (markerIdx === -1) break;
|
|
217
|
-
const fnStart = code.indexOf(arrowToken, markerIdx);
|
|
218
|
-
if (fnStart === -1) {
|
|
219
|
-
pos = markerIdx + 12;
|
|
220
|
-
continue;
|
|
221
|
-
}
|
|
222
|
-
const bodyStart = fnStart + 8;
|
|
223
|
-
let i = bodyStart;
|
|
224
|
-
let depth = 1;
|
|
225
|
-
while (i < code.length && depth > 0) {
|
|
226
|
-
const ch = code[i++];
|
|
227
|
-
if (ch === "{") depth++;
|
|
228
|
-
else if (ch === "}") depth--;
|
|
229
|
-
}
|
|
230
|
-
if (depth !== 0) break;
|
|
231
|
-
const bodyEnd = i - 1;
|
|
232
|
-
const body = code.slice(bodyStart, bodyEnd);
|
|
233
|
-
if (/\bawait\b/.test(body) && code.slice(fnStart, fnStart + 14) !== asyncArrowToken) {
|
|
234
|
-
code = `${code.slice(0, fnStart + 1)}async ${code.slice(fnStart + 1)}`;
|
|
235
|
-
pos = fnStart + 1 + 6;
|
|
236
|
-
continue;
|
|
237
|
-
}
|
|
238
|
-
pos = bodyEnd;
|
|
239
|
-
}
|
|
240
|
-
if (code !== chunk.code) chunk.code = code;
|
|
241
|
-
}
|
|
242
|
-
} }
|
|
243
|
-
};
|
|
244
|
-
}
|
|
245
|
-
/**
|
|
246
|
-
* Fix require.resolve calls to use the correct base path.
|
|
247
|
-
* Replace __require.resolve("./relative") with proper resolution from original file location.
|
|
248
|
-
*/
|
|
249
|
-
function createRequireResolveFix(options) {
|
|
250
|
-
return {
|
|
251
|
-
name: "unrun-require-resolve-fix",
|
|
252
|
-
generateBundle: { handler(_, bundle$1) {
|
|
253
|
-
for (const chunk of Object.values(bundle$1)) if (chunk.type === "chunk") chunk.code = chunk.code.replaceAll(/__require\.resolve\(["']([^"']+)["']\)/g, (match, id) => {
|
|
254
|
-
if (id.startsWith("./") || id.startsWith("../")) try {
|
|
255
|
-
const baseDir = path.dirname(options.path);
|
|
256
|
-
for (const ext of [
|
|
257
|
-
"",
|
|
258
|
-
".ts",
|
|
259
|
-
".js",
|
|
260
|
-
".mts",
|
|
261
|
-
".mjs",
|
|
262
|
-
".cts",
|
|
263
|
-
".cjs"
|
|
264
|
-
]) {
|
|
265
|
-
const testPath = path.resolve(baseDir, id + ext);
|
|
266
|
-
if (fs.existsSync(testPath)) return JSON.stringify(testPath);
|
|
267
|
-
}
|
|
268
|
-
const resolvedPath = path.resolve(baseDir, id);
|
|
269
|
-
return JSON.stringify(resolvedPath);
|
|
270
|
-
} catch {
|
|
271
|
-
return match;
|
|
272
|
-
}
|
|
273
|
-
return match;
|
|
274
|
-
});
|
|
275
|
-
} }
|
|
276
|
-
};
|
|
277
|
-
}
|
|
278
|
-
/**
|
|
279
|
-
* Ensure typeof require in ESM stays undefined to match jiti behavior.
|
|
280
|
-
* Replaces typeof __require with typeof require to maintain compatibility.
|
|
281
|
-
*/
|
|
282
|
-
function createRequireTypeofFix() {
|
|
283
|
-
return {
|
|
284
|
-
name: "unrun-require-typeof-fix",
|
|
285
|
-
generateBundle: { handler(_, bundle$1) {
|
|
286
|
-
for (const chunk of Object.values(bundle$1)) if (chunk.type === "chunk") chunk.code = chunk.code.replaceAll(/\btypeof\s+__require\b/g, "typeof require");
|
|
287
|
-
} }
|
|
288
|
-
};
|
|
289
|
-
}
|
|
290
|
-
/**
|
|
291
|
-
* A rolldown plugin that injects source context shims:
|
|
292
|
-
* - Replaces import.meta.resolve calls with resolved file URLs
|
|
293
|
-
* - Injects per-module __filename/__dirname
|
|
294
|
-
* - Replaces import.meta.url with the source file URL
|
|
295
|
-
*/
|
|
296
|
-
function createSourceContextShimsPlugin() {
|
|
297
|
-
return {
|
|
298
|
-
name: "unrun-source-context-shims",
|
|
299
|
-
load: {
|
|
300
|
-
filter: { id: /\.(?:m?[jt]s|c?tsx?)(?:$|\?)/ },
|
|
301
|
-
handler(id) {
|
|
302
|
-
let code;
|
|
303
|
-
try {
|
|
304
|
-
code = fs.readFileSync(id, "utf8");
|
|
305
|
-
} catch {
|
|
306
|
-
return null;
|
|
307
|
-
}
|
|
308
|
-
let __MODIFIED_CODE__ = false;
|
|
309
|
-
if (code.includes("import.meta.resolve")) {
|
|
310
|
-
const replaced = code.replaceAll(/import\.meta\.resolve!?\s*\(\s*(["'])([^"']+)\1\s*\)/g, (_m, _q, spec) => {
|
|
311
|
-
const url = pathToFileURL(path.resolve(path.dirname(id), spec)).href;
|
|
312
|
-
return JSON.stringify(url);
|
|
313
|
-
});
|
|
314
|
-
if (replaced !== code) {
|
|
315
|
-
code = replaced;
|
|
316
|
-
__MODIFIED_CODE__ = true;
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
if (/__filename|__dirname|import\s*\.\s*meta\s*\.\s*url/.test(code)) {
|
|
320
|
-
const file = id;
|
|
321
|
-
const dir = path.dirname(id);
|
|
322
|
-
const url = pathToFileURL(id).href;
|
|
323
|
-
const prologue = `const __filename = ${JSON.stringify(file)}\nconst __dirname = ${JSON.stringify(dir)}\n`;
|
|
324
|
-
const protectedStrings = [];
|
|
325
|
-
let protectedCode = code.replaceAll(/(["'])[^"']*import\s*\.\s*meta\s*\.\s*url[^"']*\1\s*:/g, (match) => {
|
|
326
|
-
const placeholder = `__PROTECTED_STRING_${protectedStrings.length}__`;
|
|
327
|
-
protectedStrings.push(match);
|
|
328
|
-
return placeholder;
|
|
329
|
-
});
|
|
330
|
-
protectedCode = protectedCode.replaceAll(/\bimport\s*\.\s*meta\s*\.\s*url\b/g, JSON.stringify(url));
|
|
331
|
-
for (const [i, protectedString] of protectedStrings.entries()) protectedCode = protectedCode.replace(`__PROTECTED_STRING_${i}__`, protectedString);
|
|
332
|
-
code = prologue + protectedCode;
|
|
333
|
-
__MODIFIED_CODE__ = true;
|
|
334
|
-
}
|
|
335
|
-
return __MODIFIED_CODE__ ? { code } : null;
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
};
|
|
339
|
-
}
|
|
340
|
-
async function bundle(options) {
|
|
341
|
-
const resolvedTsconfigPath = path.resolve(process.cwd(), "tsconfig.json");
|
|
342
|
-
const tsconfig = existsSync(resolvedTsconfigPath) ? resolvedTsconfigPath : void 0;
|
|
343
|
-
const inputOptions = {
|
|
344
|
-
input: options.path,
|
|
345
|
-
platform: "node",
|
|
346
|
-
external: (id) => !id.startsWith(".") && !path.isAbsolute(id) && !id.startsWith("#"),
|
|
347
|
-
plugins: [
|
|
348
|
-
createMakeCjsWrapperAsyncFriendlyPlugin(),
|
|
349
|
-
createRequireResolveFix(options),
|
|
350
|
-
createSourceContextShimsPlugin(),
|
|
351
|
-
...options.preset === "jiti" ? [
|
|
352
|
-
createConsoleOutputCustomizer(),
|
|
353
|
-
createJsonLoader(),
|
|
354
|
-
createRequireTypeofFix()
|
|
355
|
-
] : []
|
|
356
|
-
],
|
|
357
|
-
transform: { define: {
|
|
358
|
-
__dirname: JSON.stringify(path.dirname(options.path)),
|
|
359
|
-
__filename: JSON.stringify(options.path),
|
|
360
|
-
"import.meta.url": JSON.stringify(pathToFileURL(options.path).href),
|
|
361
|
-
"import.meta.filename": JSON.stringify(options.path),
|
|
362
|
-
"import.meta.dirname": JSON.stringify(path.dirname(options.path)),
|
|
363
|
-
"import.meta.env": "process.env"
|
|
364
|
-
} },
|
|
365
|
-
...options.inputOptions
|
|
366
|
-
};
|
|
367
|
-
if (tsconfig) inputOptions.tsconfig = tsconfig;
|
|
368
|
-
const bundle$1 = await rolldown(inputOptions);
|
|
369
|
-
const outputOptions = {
|
|
370
|
-
format: "esm",
|
|
371
|
-
inlineDynamicImports: true,
|
|
372
|
-
keepNames: true,
|
|
373
|
-
...options.outputOptions
|
|
374
|
-
};
|
|
375
|
-
const rolldownOutput = await bundle$1.generate(outputOptions);
|
|
376
|
-
if (!rolldownOutput.output[0]) throw new Error("[unrun] No output chunk found");
|
|
377
|
-
const files = await bundle$1.watchFiles;
|
|
378
|
-
return {
|
|
379
|
-
chunk: rolldownOutput.output[0],
|
|
380
|
-
dependencies: files
|
|
381
|
-
};
|
|
382
|
-
}
|
|
383
|
-
/**
|
|
384
|
-
* Clean the module file at the given URL.
|
|
385
|
-
* Deletes the file if it exists.
|
|
386
|
-
* @param moduleUrl - The URL of the module file to be cleaned.
|
|
387
|
-
* @param options - Resolved options.
|
|
388
|
-
*/
|
|
389
|
-
function cleanModule(moduleUrl, options) {
|
|
390
|
-
if (options.debug) return;
|
|
391
|
-
try {
|
|
392
|
-
if (moduleUrl.startsWith("file://")) {
|
|
393
|
-
const filePath = new URL(moduleUrl);
|
|
394
|
-
fs.unlinkSync(filePath);
|
|
395
|
-
}
|
|
396
|
-
} catch (error) {
|
|
397
|
-
if (error.code !== "ENOENT") throw error;
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
function sanitize(name) {
|
|
401
|
-
return name.replaceAll(/[^\w.-]/g, "_");
|
|
402
|
-
}
|
|
403
|
-
/**
|
|
404
|
-
* Writes a module to the filesystem.
|
|
405
|
-
* @param code - The JavaScript code to be written as a module.
|
|
406
|
-
* @param options - Resolved options.
|
|
407
|
-
* @returns The file URL of the written module.
|
|
408
|
-
*/
|
|
409
|
-
function writeModule(code, options) {
|
|
410
|
-
const filenameHint = path.basename(options.path);
|
|
411
|
-
let moduleUrl = "";
|
|
412
|
-
try {
|
|
413
|
-
const randomKey = crypto.randomBytes(16).toString("hex");
|
|
414
|
-
const fname = `${filenameHint ? `${sanitize(filenameHint)}.` : ""}${randomKey}.mjs`;
|
|
415
|
-
const projectNodeModules = path.join(process.cwd(), "node_modules");
|
|
416
|
-
const outDir = path.join(projectNodeModules, ".unrun");
|
|
417
|
-
const outFile = path.join(outDir, fname);
|
|
418
|
-
if (!fs.existsSync(outFile)) try {
|
|
419
|
-
fs.mkdirSync(outDir, { recursive: true });
|
|
420
|
-
fs.writeFileSync(outFile, code, "utf8");
|
|
421
|
-
} catch {
|
|
422
|
-
const fallbackDir = path.join(tmpdir(), "unrun-cache");
|
|
423
|
-
const fallbackFile = path.join(fallbackDir, fname);
|
|
424
|
-
fs.mkdirSync(fallbackDir, { recursive: true });
|
|
425
|
-
fs.writeFileSync(fallbackFile, code, "utf8");
|
|
426
|
-
moduleUrl = pathToFileURL(fallbackFile).href;
|
|
427
|
-
}
|
|
428
|
-
moduleUrl = moduleUrl || pathToFileURL(outFile).href;
|
|
429
|
-
} catch {
|
|
430
|
-
moduleUrl = `data:text/javascript;base64,${Buffer.from(code).toString("base64")}`;
|
|
431
|
-
}
|
|
432
|
-
return moduleUrl;
|
|
433
|
-
}
|
|
434
|
-
/**
|
|
435
|
-
* Import a JS module from code string.
|
|
436
|
-
* Write ESM code to a temp file (prefer project-local node_modules/.unrun) and import it.
|
|
437
|
-
* @param code - The JavaScript code to be imported as a module.
|
|
438
|
-
* @param options - Resolved options.
|
|
439
|
-
* @returns The imported module.
|
|
440
|
-
*/
|
|
441
|
-
async function loadModule(code, options) {
|
|
442
|
-
const moduleUrl = writeModule(code, options);
|
|
443
|
-
let _module;
|
|
444
|
-
try {
|
|
445
|
-
_module = await import(moduleUrl);
|
|
446
|
-
} finally {
|
|
447
|
-
cleanModule(moduleUrl, options);
|
|
448
|
-
}
|
|
449
|
-
return _module;
|
|
450
|
-
}
|
|
451
|
-
/**
|
|
452
|
-
* Loads a module with JIT transpilation based on the provided options.
|
|
453
|
-
*
|
|
454
|
-
* @param options - The options for loading the module.
|
|
455
|
-
* @returns A promise that resolves to the loaded module.
|
|
456
|
-
*/
|
|
457
|
-
async function unrun(options) {
|
|
458
|
-
const resolvedOptions = resolveOptions(options);
|
|
459
|
-
const output = await bundle(resolvedOptions);
|
|
460
|
-
let module;
|
|
461
|
-
try {
|
|
462
|
-
module = await loadModule(output.chunk.code, resolvedOptions);
|
|
463
|
-
} catch (error) {
|
|
464
|
-
throw new Error(`[unrun] Import failed (code length: ${output.chunk.code.length}): ${error.message}`);
|
|
465
|
-
}
|
|
466
|
-
return {
|
|
467
|
-
module: preset(resolvedOptions, module),
|
|
468
|
-
dependencies: output.dependencies
|
|
469
|
-
};
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
//#endregion
|
|
473
|
-
export { unrun };
|