@vite-hub/sandbox 0.0.3 → 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/LICENSE +201 -0
- package/README.md +388 -22
- package/dist/cloudflare-DO0h3Ncf.js +281 -0
- package/dist/cloudflare-env-BBJaBbuQ.js +39 -0
- package/dist/crabbox-BFCdf41h.js +1106 -0
- package/dist/error-diagnostics-BSysPv-D.js +166 -0
- package/dist/error-diagnostics-dGQqfgLt.js +99 -0
- package/dist/file-listing-DECFTdSl.js +26 -0
- package/dist/file-lock-CxyVl4Cv.js +73 -0
- package/dist/index-CXej1Bt0.d.ts +519 -0
- package/dist/index.d.ts +2 -65
- package/dist/index.js +277 -1172
- package/dist/internal/cloudflare.d.ts +4 -0
- package/dist/internal/cloudflare.js +16 -0
- package/dist/internal/host-toolchain.d.ts +22 -0
- package/dist/internal/host-toolchain.js +97 -0
- package/dist/internal/vercel.d.ts +4 -0
- package/dist/internal/vercel.js +16 -0
- package/dist/module-types-BfyRBaiP.js +7 -0
- package/dist/module-types-Cis4hrF1.d.ts +95 -0
- package/dist/remote-1Jz2oUMK.js +247 -0
- package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
- package/dist/runtime-DHp6ImeP.js +32 -0
- package/dist/runtime-type-DrmrW5m5.js +42 -0
- package/dist/session-DD0S1PDC.js +337 -0
- package/dist/shell-quote-Q3u3plif.js +6 -0
- package/dist/ssh.d.ts +55 -0
- package/dist/ssh.js +219 -0
- package/dist/task/index.d.ts +67 -0
- package/dist/task/index.js +1523 -0
- package/dist/task/runtime/empty-registry.d.ts +6 -0
- package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
- package/dist/task/runtime/provider-loader.d.ts +20 -0
- package/dist/task/runtime/provider-loader.js +19 -0
- package/dist/task/runtime/providers/cloudflare.d.ts +28 -0
- package/dist/task/runtime/providers/cloudflare.js +26 -0
- package/dist/task/runtime/providers/vercel.d.ts +12 -0
- package/dist/{runtime → task/runtime}/providers/vercel.js +17 -14
- package/dist/task/runtime/state.d.ts +24 -0
- package/dist/task/runtime/state.js +73 -0
- package/dist/task/vite.d.ts +360 -0
- package/dist/task/vite.js +3643 -0
- package/dist/toolchain-BUVXtQ2m.js +527 -0
- package/dist/trusted-host-DNMJ-Oig.js +872 -0
- package/dist/vercel-Jtxa9TJx.js +279 -0
- package/package.json +103 -39
- package/dist/cloudflare-env-2NctU8i7.js +0 -12
- package/dist/module-types-DfXe133f.d.ts +0 -91
- package/dist/module-types-Dj1MFmHT.js +0 -7
- package/dist/provider-loader-hL7uHVWp.d.ts +0 -21
- package/dist/runtime/empty-registry.d.ts +0 -6
- package/dist/runtime/provider-loader.d.ts +0 -2
- package/dist/runtime/provider-loader.js +0 -15
- package/dist/runtime/providers/cloudflare.d.ts +0 -29
- package/dist/runtime/providers/cloudflare.js +0 -25
- package/dist/runtime/providers/vercel.d.ts +0 -112
- package/dist/runtime/state.d.ts +0 -17
- package/dist/runtime/state.js +0 -21
- package/dist/vite.d.ts +0 -24
- package/dist/vite.js +0 -2367
|
@@ -0,0 +1,3643 @@
|
|
|
1
|
+
import { t as sandboxTaskErrorDiagnostics } from "../error-diagnostics-dGQqfgLt.js";
|
|
2
|
+
import { t as getSandboxTaskFeatureProvider } from "../module-types-BfyRBaiP.js";
|
|
3
|
+
import { builtinModules, createRequire } from "node:module";
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { copyFile, glob, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import { basename, dirname, matchesGlob, parse, relative, resolve } from "node:path";
|
|
7
|
+
import { defineDiagnostics } from "nostics";
|
|
8
|
+
import { hostname, tmpdir } from "node:os";
|
|
9
|
+
import { basename as basename$1, dirname as dirname$1, isAbsolute as isAbsolute$1, join as join$1, normalize, relative as relative$1, resolve as resolve$1, sep as sep$1 } from "pathe";
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
11
|
+
import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
12
|
+
import { findDynamicImports, resolvePathSync } from "mlly";
|
|
13
|
+
import { resolveModule } from "local-pkg";
|
|
14
|
+
import { dirname as dirname$2, join as join$2, normalize as normalize$1 } from "node:path/posix";
|
|
15
|
+
import { parse as parse$1 } from "yaml";
|
|
16
|
+
import { setTimeout } from "node:timers/promises";
|
|
17
|
+
//#region ../internal/src/build/vite.ts
|
|
18
|
+
const projectRootDirectoryMarkers = [
|
|
19
|
+
["server", "agents"],
|
|
20
|
+
["server", "channels"],
|
|
21
|
+
["server", "connections"],
|
|
22
|
+
["server", "browsers"],
|
|
23
|
+
["server", "emails"],
|
|
24
|
+
["server", "schedules"],
|
|
25
|
+
["server", "workspaces"]
|
|
26
|
+
];
|
|
27
|
+
const projectRootFileMarkers = [
|
|
28
|
+
["package.json"],
|
|
29
|
+
["nuxt.config.ts"],
|
|
30
|
+
["nuxt.config.mts"],
|
|
31
|
+
["nuxt.config.js"],
|
|
32
|
+
["nuxt.config.mjs"]
|
|
33
|
+
];
|
|
34
|
+
function createNoExternalAddition(...packageNames) {
|
|
35
|
+
return (current) => {
|
|
36
|
+
if (current === true) return;
|
|
37
|
+
const values = Array.isArray(current) ? current : [current];
|
|
38
|
+
const missing = packageNames.filter((packageName) => !values.includes(packageName));
|
|
39
|
+
return missing.length ? missing : void 0;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function isServerEnvironment(name, config) {
|
|
43
|
+
return name === "ssr" || config.consumer === "server";
|
|
44
|
+
}
|
|
45
|
+
const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
|
|
46
|
+
function includesNitroVitePlugin(value) {
|
|
47
|
+
if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
|
|
48
|
+
if (!value || typeof value !== "object") return false;
|
|
49
|
+
return "name" in value && value.name === "nitro:main";
|
|
50
|
+
}
|
|
51
|
+
function hasNitroConfigContext(config) {
|
|
52
|
+
return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
|
|
53
|
+
}
|
|
54
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
55
|
+
const resolvedRoot = resolve(root);
|
|
56
|
+
const temporaryRoot = resolve(tmpdir());
|
|
57
|
+
const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
58
|
+
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
59
|
+
if (basename(resolvedRoot) === "app") {
|
|
60
|
+
const parent = dirname(resolvedRoot);
|
|
61
|
+
if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
|
|
62
|
+
"nuxt.config.ts",
|
|
63
|
+
"nuxt.config.mts",
|
|
64
|
+
"nuxt.config.js",
|
|
65
|
+
"nuxt.config.mjs"
|
|
66
|
+
]))) return parent;
|
|
67
|
+
}
|
|
68
|
+
let current = resolvedRoot;
|
|
69
|
+
while (true) {
|
|
70
|
+
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
71
|
+
if (hasProjectRootMarker(current)) return current;
|
|
72
|
+
const parent = dirname(current);
|
|
73
|
+
if (parent === current) return resolvedRoot;
|
|
74
|
+
current = parent;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
78
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
79
|
+
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error.code !== "ENOENT") throw error;
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
function hasProjectRootMarker(root) {
|
|
86
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
87
|
+
return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
|
|
88
|
+
}
|
|
89
|
+
function hasProjectRootFileMarker(root, markers) {
|
|
90
|
+
for (const marker of markers) {
|
|
91
|
+
const path = Array.isArray(marker) ? marker : [marker];
|
|
92
|
+
try {
|
|
93
|
+
if (statSync(resolve(root, ...path)).isFile()) return true;
|
|
94
|
+
} catch (error) {
|
|
95
|
+
if (error.code !== "ENOENT") throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
//#region ../internal/src/error-diagnostics.ts
|
|
102
|
+
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
103
|
+
const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
104
|
+
docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
|
|
105
|
+
codes: {
|
|
106
|
+
INTERNAL_R0012: dynamicError,
|
|
107
|
+
INTERNAL_R0013: dynamicError,
|
|
108
|
+
INTERNAL_R0014: {
|
|
109
|
+
why: ({ path }) => `Cannot read Provision State from "${path}".`,
|
|
110
|
+
fix: "Check file access and restore valid JSON while preserving existing resource IDs."
|
|
111
|
+
},
|
|
112
|
+
INTERNAL_R0020: {
|
|
113
|
+
fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
|
|
114
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
115
|
+
},
|
|
116
|
+
INTERNAL_R0021: {
|
|
117
|
+
fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
|
|
118
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
119
|
+
},
|
|
120
|
+
INTERNAL_R0022: {
|
|
121
|
+
fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
|
|
122
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
123
|
+
},
|
|
124
|
+
INTERNAL_R0024: {
|
|
125
|
+
fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app with credentials in VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.",
|
|
126
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
127
|
+
},
|
|
128
|
+
INTERNAL_R0023: {
|
|
129
|
+
fix: "Ask for access to the section of this operation.",
|
|
130
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
131
|
+
},
|
|
132
|
+
INTERNAL_B0001: dynamicError,
|
|
133
|
+
INTERNAL_B0002: dynamicError,
|
|
134
|
+
INTERNAL_B0003: dynamicError,
|
|
135
|
+
INTERNAL_B0004: dynamicError,
|
|
136
|
+
INTERNAL_B0005: dynamicError,
|
|
137
|
+
INTERNAL_B0006: dynamicError,
|
|
138
|
+
INTERNAL_B0007: dynamicError,
|
|
139
|
+
INTERNAL_B0008: dynamicError,
|
|
140
|
+
INTERNAL_B0009: dynamicError,
|
|
141
|
+
INTERNAL_B0010: dynamicError,
|
|
142
|
+
INTERNAL_B0011: dynamicError,
|
|
143
|
+
INTERNAL_B0012: dynamicError,
|
|
144
|
+
INTERNAL_B0013: dynamicError,
|
|
145
|
+
INTERNAL_B0014: dynamicError,
|
|
146
|
+
INTERNAL_B0015: dynamicError,
|
|
147
|
+
INTERNAL_B0016: dynamicError,
|
|
148
|
+
INTERNAL_B0017: dynamicError,
|
|
149
|
+
INTERNAL_B0018: dynamicError,
|
|
150
|
+
INTERNAL_B0019: dynamicError,
|
|
151
|
+
INTERNAL_B0020: dynamicError,
|
|
152
|
+
INTERNAL_B0021: dynamicError,
|
|
153
|
+
INTERNAL_B0022: dynamicError,
|
|
154
|
+
INTERNAL_B0023: dynamicError,
|
|
155
|
+
INTERNAL_B0024: dynamicError,
|
|
156
|
+
INTERNAL_B0025: dynamicError,
|
|
157
|
+
INTERNAL_B0026: dynamicError,
|
|
158
|
+
INTERNAL_B0027: dynamicError,
|
|
159
|
+
INTERNAL_B0028: dynamicError,
|
|
160
|
+
INTERNAL_B0029: dynamicError,
|
|
161
|
+
INTERNAL_B0030: dynamicError,
|
|
162
|
+
INTERNAL_B0031: dynamicError,
|
|
163
|
+
INTERNAL_B0032: dynamicError,
|
|
164
|
+
INTERNAL_B0033: dynamicError,
|
|
165
|
+
INTERNAL_B0034: dynamicError,
|
|
166
|
+
INTERNAL_B0035: dynamicError,
|
|
167
|
+
INTERNAL_B0036: dynamicError,
|
|
168
|
+
INTERNAL_B0037: dynamicError,
|
|
169
|
+
INTERNAL_B0038: dynamicError,
|
|
170
|
+
INTERNAL_B0039: dynamicError,
|
|
171
|
+
INTERNAL_B0040: dynamicError,
|
|
172
|
+
INTERNAL_B0041: dynamicError,
|
|
173
|
+
INTERNAL_B0042: dynamicError,
|
|
174
|
+
INTERNAL_B0043: dynamicError,
|
|
175
|
+
INTERNAL_B0044: dynamicError,
|
|
176
|
+
INTERNAL_B0045: dynamicError,
|
|
177
|
+
INTERNAL_B0046: dynamicError,
|
|
178
|
+
INTERNAL_B0047: dynamicError,
|
|
179
|
+
INTERNAL_B0048: {
|
|
180
|
+
fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
|
|
181
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
182
|
+
},
|
|
183
|
+
INTERNAL_B0049: {
|
|
184
|
+
fix: "Set `cli: { namespace, command }` on one of the two operations.",
|
|
185
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
186
|
+
},
|
|
187
|
+
INTERNAL_B0050: {
|
|
188
|
+
fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
|
|
189
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
190
|
+
},
|
|
191
|
+
INTERNAL_R0025: {
|
|
192
|
+
fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
|
|
193
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
194
|
+
},
|
|
195
|
+
INTERNAL_R0026: {
|
|
196
|
+
why: "The server parsed a destructive operation that the CLI did not confirm.",
|
|
197
|
+
fix: "Review the operation, then run it again with --yes to confirm the change."
|
|
198
|
+
},
|
|
199
|
+
INTERNAL_C0001: dynamicError,
|
|
200
|
+
INTERNAL_C0002: dynamicError,
|
|
201
|
+
INTERNAL_R0001: dynamicError,
|
|
202
|
+
INTERNAL_R0002: dynamicError,
|
|
203
|
+
INTERNAL_R0003: dynamicError,
|
|
204
|
+
INTERNAL_R0004: dynamicError,
|
|
205
|
+
INTERNAL_R0005: dynamicError,
|
|
206
|
+
INTERNAL_R0006: dynamicError,
|
|
207
|
+
INTERNAL_R0007: dynamicError,
|
|
208
|
+
INTERNAL_R0008: dynamicError,
|
|
209
|
+
INTERNAL_R0009: dynamicError,
|
|
210
|
+
INTERNAL_R0010: dynamicError,
|
|
211
|
+
INTERNAL_R0011: dynamicError
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
function deploymentPresetFromNitro(value) {
|
|
215
|
+
const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
|
|
216
|
+
if (!normalized) return;
|
|
217
|
+
if (normalized.startsWith("cloudflare")) return "cloudflare";
|
|
218
|
+
if (normalized.startsWith("deno")) return "deno";
|
|
219
|
+
if (normalized.startsWith("netlify")) return "netlify";
|
|
220
|
+
if (normalized === "node" || normalized.startsWith("node-")) return "node";
|
|
221
|
+
if (normalized.startsWith("vercel")) return "vercel";
|
|
222
|
+
}
|
|
223
|
+
//#endregion
|
|
224
|
+
//#region ../internal/src/hosting.ts
|
|
225
|
+
/**
|
|
226
|
+
* Returns the Nitro preset name that this build targets, as the developer wrote it.
|
|
227
|
+
* The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOSTING`.
|
|
228
|
+
* Empty values are skipped.
|
|
229
|
+
*/
|
|
230
|
+
function resolveHostPreset(input = {}) {
|
|
231
|
+
const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
|
|
232
|
+
const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
|
|
233
|
+
for (const value of [
|
|
234
|
+
nitroPreset,
|
|
235
|
+
input.hosting,
|
|
236
|
+
env.NITRO_PRESET,
|
|
237
|
+
env.SERVER_PRESET,
|
|
238
|
+
env.VITEHUB_HOSTING
|
|
239
|
+
]) if (typeof value === "string" && value.trim()) return value.trim();
|
|
240
|
+
}
|
|
241
|
+
function normalizeHosting(hosting) {
|
|
242
|
+
const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
|
|
243
|
+
if (normalized === "cloudflare") return "cloudflare-module";
|
|
244
|
+
return normalized;
|
|
245
|
+
}
|
|
246
|
+
/** Narrows a preset or host name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
|
|
247
|
+
function getHostingProvider(hosting) {
|
|
248
|
+
const preset = deploymentPresetFromNitro(hosting);
|
|
249
|
+
if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
|
|
250
|
+
}
|
|
251
|
+
function getSupportedHostingProvider(hosting, supportedProviders) {
|
|
252
|
+
const provider = getHostingProvider(hosting);
|
|
253
|
+
if (!provider || !supportedProviders.includes(provider)) return void 0;
|
|
254
|
+
return provider;
|
|
255
|
+
}
|
|
256
|
+
//#endregion
|
|
257
|
+
//#region ../internal/src/object.ts
|
|
258
|
+
function isPlainObject$1(value) {
|
|
259
|
+
if (value === null || Object(value) !== value || Array.isArray(value)) return false;
|
|
260
|
+
return typeof value === "object";
|
|
261
|
+
}
|
|
262
|
+
function isPlainRecord(value) {
|
|
263
|
+
if (!isPlainObject$1(value)) return false;
|
|
264
|
+
const prototype = Object.getPrototypeOf(value);
|
|
265
|
+
if (prototype === null) return true;
|
|
266
|
+
return Object.getPrototypeOf(prototype) === null && Object.hasOwn(prototype, "constructor") && prototype.constructor?.name === "Object";
|
|
267
|
+
}
|
|
268
|
+
//#endregion
|
|
269
|
+
//#region ../internal/src/build/paths.ts
|
|
270
|
+
function generatedDirSegments(productName) {
|
|
271
|
+
return [".vitehub", productName];
|
|
272
|
+
}
|
|
273
|
+
function ensureGeneratedDir(rootDir, productName) {
|
|
274
|
+
return resolve$1(rootDir, ...generatedDirSegments(productName));
|
|
275
|
+
}
|
|
276
|
+
function createImportPath(fromFile, targetFile) {
|
|
277
|
+
const fromDir = realpathIfExists(dirname$1(fromFile));
|
|
278
|
+
const target = realpathIfExists(targetFile);
|
|
279
|
+
const importPath = relative$1(fromDir, target);
|
|
280
|
+
return importPath.startsWith(".") ? importPath : `./${importPath}`;
|
|
281
|
+
}
|
|
282
|
+
function realpathIfExists(path) {
|
|
283
|
+
try {
|
|
284
|
+
return realpathSync.native(path);
|
|
285
|
+
} catch {
|
|
286
|
+
return resolve$1(path);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
//#endregion
|
|
290
|
+
//#region ../internal/src/definition-catalog.ts
|
|
291
|
+
const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
|
|
292
|
+
const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
|
|
293
|
+
const ignoredDirs = /* @__PURE__ */ new Set([
|
|
294
|
+
"node_modules",
|
|
295
|
+
"dist",
|
|
296
|
+
".output",
|
|
297
|
+
".nuxt",
|
|
298
|
+
".vercel",
|
|
299
|
+
".git",
|
|
300
|
+
".vitehub"
|
|
301
|
+
]);
|
|
302
|
+
function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
|
|
303
|
+
return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
|
|
304
|
+
}
|
|
305
|
+
function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
|
|
306
|
+
return {
|
|
307
|
+
...options,
|
|
308
|
+
kind: "suffix",
|
|
309
|
+
normalizeName,
|
|
310
|
+
pattern,
|
|
311
|
+
roots,
|
|
312
|
+
source
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
function readDirEntries(root) {
|
|
316
|
+
try {
|
|
317
|
+
return readdirSync(root, { withFileTypes: true });
|
|
318
|
+
} catch (error) {
|
|
319
|
+
if (error.code === "ENOENT") return [];
|
|
320
|
+
throw error;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
function isGitRepositoryDirectory(directory) {
|
|
324
|
+
return existsSync(resolve$1(directory, ".git"));
|
|
325
|
+
}
|
|
326
|
+
function listMatchingFiles(root, predicate, options = {}) {
|
|
327
|
+
const files = [];
|
|
328
|
+
for (const entry of readDirEntries(root)) {
|
|
329
|
+
const absolute = resolve$1(root, entry.name);
|
|
330
|
+
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
331
|
+
if (isGitRepositoryDirectory(absolute)) continue;
|
|
332
|
+
if (entry.name.startsWith(".")) continue;
|
|
333
|
+
if (ignoredDirs.has(entry.name)) continue;
|
|
334
|
+
files.push(...listMatchingFiles(absolute, predicate, options));
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
if (entry.name.startsWith(".") && !options.includeHidden) continue;
|
|
338
|
+
if (entry.isFile() && predicate(entry.name)) files.push(absolute);
|
|
339
|
+
}
|
|
340
|
+
return files.sort();
|
|
341
|
+
}
|
|
342
|
+
function listSourceFiles(root, options = {}) {
|
|
343
|
+
return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
|
|
344
|
+
}
|
|
345
|
+
function normalizePathDefinitionName(rootDir, file) {
|
|
346
|
+
return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
|
|
347
|
+
}
|
|
348
|
+
function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
|
|
349
|
+
const normalized = relative$1(rootDir, file).replace(pattern, "");
|
|
350
|
+
if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
|
|
351
|
+
return normalized;
|
|
352
|
+
}
|
|
353
|
+
function sortDefinitions(definitions) {
|
|
354
|
+
return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
355
|
+
}
|
|
356
|
+
function registerDefinition(definitions, definition, sourceLabel) {
|
|
357
|
+
const existing = definitions.get(definition.name);
|
|
358
|
+
if (existing) throw internalErrorDiagnostics.INTERNAL_C0001({ message: `Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}` });
|
|
359
|
+
definitions.set(definition.name, definition);
|
|
360
|
+
}
|
|
361
|
+
function mergeDefinitions(feature, ...sources) {
|
|
362
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
363
|
+
for (const source of sources) {
|
|
364
|
+
if (!source) continue;
|
|
365
|
+
for (const definition of source) {
|
|
366
|
+
const existing = definitions.get(definition.name);
|
|
367
|
+
if (existing && existing.handler !== definition.handler) throw internalErrorDiagnostics.INTERNAL_C0002({ message: `Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})` });
|
|
368
|
+
if (!existing) definitions.set(definition.name, definition);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return sortDefinitions(definitions);
|
|
372
|
+
}
|
|
373
|
+
function createDefinition(source, file, name) {
|
|
374
|
+
if (source.createDefinition) return source.createDefinition({
|
|
375
|
+
file,
|
|
376
|
+
name
|
|
377
|
+
});
|
|
378
|
+
return {
|
|
379
|
+
handler: file,
|
|
380
|
+
name,
|
|
381
|
+
source: source.source
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
function scanSuffixDefinitions(feature, source) {
|
|
385
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
386
|
+
for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => {
|
|
387
|
+
source.pattern.lastIndex = 0;
|
|
388
|
+
return source.pattern.test(name);
|
|
389
|
+
}, { includeHidden: source.includeHidden })) {
|
|
390
|
+
const name = source.normalizeName(root, file);
|
|
391
|
+
if (!name) continue;
|
|
392
|
+
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
393
|
+
}
|
|
394
|
+
return sortDefinitions(definitions);
|
|
395
|
+
}
|
|
396
|
+
function scanDirectoryDefinitions(feature, source) {
|
|
397
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
398
|
+
for (const scanDir of source.scanDirs) {
|
|
399
|
+
const directory = resolve$1(scanDir, source.subdir);
|
|
400
|
+
for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
|
|
401
|
+
const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
|
|
402
|
+
if (!name) continue;
|
|
403
|
+
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return sortDefinitions(definitions);
|
|
407
|
+
}
|
|
408
|
+
function discoverDefinitions(feature, sources) {
|
|
409
|
+
return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
|
|
410
|
+
}
|
|
411
|
+
async function writeFileIfChanged(file, contents) {
|
|
412
|
+
if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
|
|
413
|
+
await mkdir(resolve$1(file, ".."), { recursive: true });
|
|
414
|
+
await writeFile(file, contents, "utf8");
|
|
415
|
+
}
|
|
416
|
+
//#endregion
|
|
417
|
+
//#region src/task/internal/shared/cloudflare-wrangler.ts
|
|
418
|
+
function compareNumericStrings(left, right) {
|
|
419
|
+
return left.localeCompare(right, void 0, { numeric: true });
|
|
420
|
+
}
|
|
421
|
+
function isSameKVNamespace(left, right) {
|
|
422
|
+
return left.binding === right.binding && left.id === right.id && left.preview_id === right.preview_id && left.experimental_remote === right.experimental_remote;
|
|
423
|
+
}
|
|
424
|
+
function isSameContainer(left, right) {
|
|
425
|
+
return left.class_name === right.class_name && left.image === right.image && left.image_build_context === right.image_build_context && left.instance_type === right.instance_type && left.max_instances === right.max_instances && left.name === right.name;
|
|
426
|
+
}
|
|
427
|
+
function isSameDurableObjectBinding(left, right) {
|
|
428
|
+
return left.name === right.name && left.class_name === right.class_name && left.script_name === right.script_name && left.environment === right.environment;
|
|
429
|
+
}
|
|
430
|
+
function isSameWorkerLoader(left, right) {
|
|
431
|
+
return left.binding === right.binding;
|
|
432
|
+
}
|
|
433
|
+
function isSameAnalyticsEngineDataset(left, right) {
|
|
434
|
+
return left.binding === right.binding && left.dataset === right.dataset;
|
|
435
|
+
}
|
|
436
|
+
function isSameWorkflow(left, right) {
|
|
437
|
+
return left.binding === right.binding && left.name === right.name && left.class_name === right.class_name;
|
|
438
|
+
}
|
|
439
|
+
function dedupeByKey(entries, getKey, equals, conflictLabel) {
|
|
440
|
+
if (!entries?.length) return void 0;
|
|
441
|
+
const unique = /* @__PURE__ */ new Map();
|
|
442
|
+
for (const entry of entries) {
|
|
443
|
+
const key = getKey(entry);
|
|
444
|
+
const existing = unique.get(key);
|
|
445
|
+
if (!existing) {
|
|
446
|
+
unique.set(key, entry);
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
if (!equals(existing, entry)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0045({ message: `[vitehub] Conflicting Cloudflare ${conflictLabel} "${key}".` });
|
|
450
|
+
}
|
|
451
|
+
return [...unique.values()];
|
|
452
|
+
}
|
|
453
|
+
function mergeMigrations(migrations) {
|
|
454
|
+
if (!migrations?.length) return void 0;
|
|
455
|
+
const byTag = /* @__PURE__ */ new Map();
|
|
456
|
+
for (const migration of migrations) {
|
|
457
|
+
const existing = byTag.get(migration.tag);
|
|
458
|
+
if (!existing) {
|
|
459
|
+
byTag.set(migration.tag, migration);
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
const mergeStrings = (left, right) => {
|
|
463
|
+
const values = /* @__PURE__ */ new Set([...left || [], ...right || []]);
|
|
464
|
+
return values.size ? [...values] : void 0;
|
|
465
|
+
};
|
|
466
|
+
const mergeObjects = (left, right) => {
|
|
467
|
+
const values = /* @__PURE__ */ new Map();
|
|
468
|
+
for (const value of [...left || [], ...right || []]) values.set(JSON.stringify(value), value);
|
|
469
|
+
return values.size ? [...values.values()] : void 0;
|
|
470
|
+
};
|
|
471
|
+
const deletedClasses = mergeStrings(existing.deleted_classes, migration.deleted_classes);
|
|
472
|
+
const newClasses = mergeStrings(existing.new_classes, migration.new_classes);
|
|
473
|
+
const newSqliteClasses = mergeStrings(existing.new_sqlite_classes, migration.new_sqlite_classes);
|
|
474
|
+
const renamedClasses = mergeObjects(existing.renamed_classes, migration.renamed_classes);
|
|
475
|
+
const transferredClasses = mergeObjects(existing.transferred_classes, migration.transferred_classes);
|
|
476
|
+
byTag.set(migration.tag, {
|
|
477
|
+
...existing,
|
|
478
|
+
...deletedClasses ? { deleted_classes: deletedClasses } : {},
|
|
479
|
+
...newClasses ? { new_classes: newClasses } : {},
|
|
480
|
+
...newSqliteClasses ? { new_sqlite_classes: newSqliteClasses } : {},
|
|
481
|
+
...renamedClasses ? { renamed_classes: renamedClasses } : {},
|
|
482
|
+
...transferredClasses ? { transferred_classes: transferredClasses } : {}
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
return [...byTag.values()];
|
|
486
|
+
}
|
|
487
|
+
function validateDurableObjectMigrations(wrangler) {
|
|
488
|
+
const bindings = wrangler.durable_objects?.bindings;
|
|
489
|
+
if (!bindings?.length) return;
|
|
490
|
+
const declaredClasses = /* @__PURE__ */ new Set();
|
|
491
|
+
for (const migration of wrangler.migrations || []) {
|
|
492
|
+
for (const className of [...migration.new_sqlite_classes || [], ...migration.new_classes || []]) declaredClasses.add(className);
|
|
493
|
+
for (const entry of migration.renamed_classes || []) {
|
|
494
|
+
declaredClasses.delete(entry.from);
|
|
495
|
+
declaredClasses.add(entry.to);
|
|
496
|
+
}
|
|
497
|
+
for (const className of migration.deleted_classes || []) declaredClasses.delete(className);
|
|
498
|
+
for (const entry of migration.transferred_classes || []) declaredClasses.add(entry.to);
|
|
499
|
+
}
|
|
500
|
+
const missingClasses = [...new Set(bindings.filter((binding) => !binding.script_name).map((binding) => binding.class_name))].filter((className) => !declaredClasses.has(className)).sort(compareNumericStrings);
|
|
501
|
+
if (missingClasses.length) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0046({ message: `[vitehub] Missing Cloudflare durable object migration entries for: ${missingClasses.join(", ")}.` });
|
|
502
|
+
}
|
|
503
|
+
function finalizeCloudflareWranglerConfig(target) {
|
|
504
|
+
const wrangler = target.cloudflare?.wrangler;
|
|
505
|
+
if (!wrangler) return;
|
|
506
|
+
wrangler.kv_namespaces = dedupeByKey(wrangler.kv_namespaces, (namespace) => namespace.binding, isSameKVNamespace, "KV namespace binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
|
|
507
|
+
wrangler.containers = dedupeByKey(wrangler.containers, (container) => container.class_name, isSameContainer, "container")?.sort((left, right) => compareNumericStrings(left.class_name, right.class_name));
|
|
508
|
+
wrangler.worker_loaders = dedupeByKey(wrangler.worker_loaders, (loader) => loader.binding, isSameWorkerLoader, "worker loader binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
|
|
509
|
+
wrangler.analytics_engine_datasets = dedupeByKey(wrangler.analytics_engine_datasets, (dataset) => dataset.binding, isSameAnalyticsEngineDataset, "analytics engine dataset binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
|
|
510
|
+
wrangler.durable_objects ||= {};
|
|
511
|
+
wrangler.durable_objects.bindings = dedupeByKey(wrangler.durable_objects.bindings, (binding) => binding.name, isSameDurableObjectBinding, "durable object binding")?.sort((left, right) => compareNumericStrings(left.name, right.name));
|
|
512
|
+
wrangler.workflows = dedupeByKey(wrangler.workflows, (workflow) => workflow.binding, isSameWorkflow, "workflow binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
|
|
513
|
+
wrangler.migrations = mergeMigrations(wrangler.migrations);
|
|
514
|
+
validateDurableObjectMigrations(wrangler);
|
|
515
|
+
}
|
|
516
|
+
//#endregion
|
|
517
|
+
//#region src/task/cloudflare.ts
|
|
518
|
+
const defaultCloudflareSandboxBinding = "SANDBOX";
|
|
519
|
+
const defaultCloudflareSandboxClassName = "Sandbox";
|
|
520
|
+
const defaultCloudflareSandboxMaxInstances = 12;
|
|
521
|
+
const require$1 = createRequire(import.meta.url);
|
|
522
|
+
function resolveCloudflareSandboxEntrypoint() {
|
|
523
|
+
try {
|
|
524
|
+
return require$1.resolve("@cloudflare/sandbox");
|
|
525
|
+
} catch {
|
|
526
|
+
throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0003({ message: "[vitehub] The Cloudflare Sandbox provider requires @cloudflare/sandbox. Install a supported version before building." });
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
function resolveCloudflareSandboxVersion() {
|
|
530
|
+
const entry = resolveCloudflareSandboxEntrypoint();
|
|
531
|
+
const pkg = require$1(join$1(entry, "..", "..", "package.json"));
|
|
532
|
+
if (typeof pkg?.version !== "string") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0004({ message: "[vitehub] Could not resolve the installed @cloudflare/sandbox version." });
|
|
533
|
+
return pkg.version;
|
|
534
|
+
}
|
|
535
|
+
function resolveCloudflareSandboxEntrypointOptions(options = {}) {
|
|
536
|
+
if (options.className === "ContainerProxy") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0005({ message: "[vitehub] Cloudflare Sandbox className \"ContainerProxy\" is reserved by @cloudflare/sandbox. Configure a different className." });
|
|
537
|
+
return {
|
|
538
|
+
binding: options.binding || "SANDBOX",
|
|
539
|
+
className: options.className || "Sandbox",
|
|
540
|
+
migrationTag: options.migrationTag || "v1",
|
|
541
|
+
name: options.name || void 0
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
function mergeRollupExternal(value, addition) {
|
|
545
|
+
if (typeof value === "undefined") return [addition];
|
|
546
|
+
if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
|
|
547
|
+
if (typeof value === "string" || value instanceof RegExp) return [value, addition];
|
|
548
|
+
if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
|
|
549
|
+
return value;
|
|
550
|
+
}
|
|
551
|
+
function configureCloudflareSandbox(target, options = {}) {
|
|
552
|
+
const { binding, className, migrationTag, name } = resolveCloudflareSandboxEntrypointOptions(options);
|
|
553
|
+
if (typeof target.cloudflare?.wrangler?.exports !== "undefined") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0006({ message: "[vitehub] Cloudflare Sandbox cannot compose legacy migrations with an existing Wrangler exports configuration. Remove exports or configure the Sandbox Durable Object explicitly." });
|
|
554
|
+
const existingMigrations = target.cloudflare?.wrangler?.migrations;
|
|
555
|
+
if (!existingMigrations?.some((entry) => entry.new_sqlite_classes?.includes(className)) && existingMigrations?.some((entry) => entry.tag === migrationTag)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0007({ message: `[vitehub] Cloudflare migration tag ${JSON.stringify(migrationTag)} is already in use. Configure a unique sandbox migrationTag.` });
|
|
556
|
+
if ((target.cloudflare?.wrangler?.durable_objects?.bindings)?.some((entry) => entry.name === binding && entry.class_name !== className)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0008({ message: `[vitehub] Cloudflare Durable Object binding ${JSON.stringify(binding)} is already in use. Configure a unique sandbox binding.` });
|
|
557
|
+
target.cloudflare ||= {};
|
|
558
|
+
target.cloudflare.wrangler ||= {};
|
|
559
|
+
target.cloudflare.wrangler.containers ||= [];
|
|
560
|
+
target.cloudflare.wrangler.durable_objects ||= {};
|
|
561
|
+
target.cloudflare.wrangler.durable_objects.bindings ||= [];
|
|
562
|
+
target.cloudflare.wrangler.migrations ||= [];
|
|
563
|
+
const containers = target.cloudflare.wrangler.containers;
|
|
564
|
+
const image = "./Dockerfile";
|
|
565
|
+
if (!containers.some((entry) => entry.class_name === className)) containers.push({
|
|
566
|
+
class_name: className,
|
|
567
|
+
image,
|
|
568
|
+
instance_type: "lite",
|
|
569
|
+
max_instances: defaultCloudflareSandboxMaxInstances,
|
|
570
|
+
...name ? { name } : {}
|
|
571
|
+
});
|
|
572
|
+
else {
|
|
573
|
+
const container = containers.find((entry) => entry.class_name === className);
|
|
574
|
+
container.image ??= image;
|
|
575
|
+
if (typeof container.max_instances !== "number") container.max_instances = defaultCloudflareSandboxMaxInstances;
|
|
576
|
+
if (name) container.name ??= name;
|
|
577
|
+
}
|
|
578
|
+
const bindings = target.cloudflare.wrangler.durable_objects.bindings;
|
|
579
|
+
if (!bindings.some((entry) => entry.name === binding && entry.class_name === className)) bindings.push({
|
|
580
|
+
name: binding,
|
|
581
|
+
class_name: className
|
|
582
|
+
});
|
|
583
|
+
const migrations = target.cloudflare.wrangler.migrations;
|
|
584
|
+
if (!migrations.some((entry) => Array.isArray(entry.new_sqlite_classes) && entry.new_sqlite_classes.includes(className))) migrations.push({
|
|
585
|
+
tag: migrationTag,
|
|
586
|
+
new_sqlite_classes: [className]
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
function createCloudflareSandboxRollupPlugin(options = {}) {
|
|
590
|
+
const { className } = resolveCloudflareSandboxEntrypointOptions(options);
|
|
591
|
+
const cloudflareSandboxEntrypoint = resolveCloudflareSandboxEntrypoint();
|
|
592
|
+
const moduleId = "virtual:vitehub-sandbox-task-cloudflare-exports";
|
|
593
|
+
const resolvedModuleId = "\0virtual:vitehub-sandbox-task-cloudflare-exports";
|
|
594
|
+
return {
|
|
595
|
+
name: "vitehub-sandbox-task-cloudflare-exports",
|
|
596
|
+
buildStart() {
|
|
597
|
+
this.emitFile({
|
|
598
|
+
type: "chunk",
|
|
599
|
+
id: moduleId,
|
|
600
|
+
fileName: "sandbox-task-cloudflare-exports.mjs"
|
|
601
|
+
});
|
|
602
|
+
},
|
|
603
|
+
resolveId(id) {
|
|
604
|
+
if (id === moduleId) return resolvedModuleId;
|
|
605
|
+
if (id === "@cloudflare/sandbox") return cloudflareSandboxEntrypoint;
|
|
606
|
+
},
|
|
607
|
+
load(id) {
|
|
608
|
+
if (id === resolvedModuleId) return [
|
|
609
|
+
`import { Sandbox as CloudflareSandbox } from '@cloudflare/sandbox'`,
|
|
610
|
+
`export { ContainerProxy } from '@cloudflare/sandbox'`,
|
|
611
|
+
``,
|
|
612
|
+
`export class ${className} extends CloudflareSandbox {}`,
|
|
613
|
+
``
|
|
614
|
+
].join("\n");
|
|
615
|
+
},
|
|
616
|
+
renderChunk(code, chunk) {
|
|
617
|
+
if (!chunk.isEntry) return null;
|
|
618
|
+
const exportedNames = new Set(chunk.exports);
|
|
619
|
+
const missingExports = [className, "ContainerProxy"].filter((name) => !exportedNames.has(name));
|
|
620
|
+
if (!missingExports.length) return null;
|
|
621
|
+
const exportsPath = relative$1(dirname$1(chunk.fileName), "sandbox-task-cloudflare-exports.mjs").replace(/\\/g, "/");
|
|
622
|
+
const importPath = exportsPath.startsWith(".") ? exportsPath : `./${exportsPath}`;
|
|
623
|
+
return {
|
|
624
|
+
code: `${code}\nexport { ${missingExports.join(", ")} } from ${JSON.stringify(importPath)}\n`,
|
|
625
|
+
map: null
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
function installCloudflareSandboxEntrypoint(target, options = {}) {
|
|
631
|
+
const { className } = resolveCloudflareSandboxEntrypointOptions(options);
|
|
632
|
+
target.rollupConfig ||= {};
|
|
633
|
+
const plugins = Array.isArray(target.rollupConfig.plugins) ? target.rollupConfig.plugins : target.rollupConfig.plugins ? [target.rollupConfig.plugins] : [];
|
|
634
|
+
target.rollupConfig.plugins = plugins;
|
|
635
|
+
if (plugins.some((plugin) => typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === `vitehub-sandbox-task-cloudflare-exports:${className}`)) return;
|
|
636
|
+
const plugin = createCloudflareSandboxRollupPlugin({ className });
|
|
637
|
+
plugin.name = `vitehub-sandbox-task-cloudflare-exports:${className}`;
|
|
638
|
+
plugins.push(plugin);
|
|
639
|
+
}
|
|
640
|
+
async function writeCloudflareSandboxDockerfile(serverDir) {
|
|
641
|
+
const dockerfilePath = join$1(serverDir, "Dockerfile");
|
|
642
|
+
await writeFileIfChanged(dockerfilePath, [
|
|
643
|
+
`FROM docker.io/cloudflare/sandbox:${resolveCloudflareSandboxVersion()}`,
|
|
644
|
+
"RUN npm install --global corepack@0.34.5 && corepack enable pnpm yarn",
|
|
645
|
+
""
|
|
646
|
+
].join("\n"));
|
|
647
|
+
return dockerfilePath;
|
|
648
|
+
}
|
|
649
|
+
function relativeWranglerPath(from, to) {
|
|
650
|
+
const path = relative$1(from, to).replace(/\\/g, "/");
|
|
651
|
+
return path.startsWith(".") ? path : `./${path}`;
|
|
652
|
+
}
|
|
653
|
+
async function configureCloudflareSandboxNitro(targetValue, rootDir, options = {}, finalizeWrangler = true) {
|
|
654
|
+
const target = targetValue || {};
|
|
655
|
+
const serverDir = resolve$1(rootDir, target.output?.serverDir || ".output/server");
|
|
656
|
+
const resolvedOptions = resolveCloudflareSandboxEntrypointOptions(options);
|
|
657
|
+
const existingImage = (target.cloudflare?.wrangler?.containers?.find((entry) => entry.class_name === resolvedOptions.className))?.image?.replace(/\\/g, "/");
|
|
658
|
+
configureCloudflareSandbox(target, resolvedOptions);
|
|
659
|
+
const container = target.cloudflare.wrangler.containers.find((entry) => entry.class_name === resolvedOptions.className);
|
|
660
|
+
if (typeof existingImage !== "string" || existingImage.endsWith("/.vitehub/sandbox-task/Dockerfile")) {
|
|
661
|
+
container.image = relativeWranglerPath(serverDir, await writeCloudflareSandboxDockerfile(resolve$1(rootDir, ".vitehub/sandbox-task")));
|
|
662
|
+
container.image_build_context = relativeWranglerPath(serverDir, rootDir);
|
|
663
|
+
}
|
|
664
|
+
const wrangler = target.cloudflare.wrangler;
|
|
665
|
+
wrangler.compatibility_flags = Array.isArray(wrangler.compatibility_flags) ? [...wrangler.compatibility_flags] : [];
|
|
666
|
+
if (!wrangler.compatibility_flags.includes("nodejs_compat")) wrangler.compatibility_flags.push("nodejs_compat");
|
|
667
|
+
target.rollupConfig ||= {};
|
|
668
|
+
target.rollupConfig.external = mergeRollupExternal(target.rollupConfig.external, "cloudflare:workers");
|
|
669
|
+
installCloudflareSandboxEntrypoint(target, resolvedOptions);
|
|
670
|
+
if (finalizeWrangler) finalizeCloudflareWranglerConfig(target);
|
|
671
|
+
return target;
|
|
672
|
+
}
|
|
673
|
+
//#endregion
|
|
674
|
+
//#region src/task/internal/shared/discovered-definition/bundler.ts
|
|
675
|
+
const builtinModuleSet$2 = /* @__PURE__ */ new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
676
|
+
function resolveDefinitionLoader(options) {
|
|
677
|
+
let loader = options.loader;
|
|
678
|
+
if (!loader) {
|
|
679
|
+
const f = options.filename;
|
|
680
|
+
if (f.endsWith(".tsx")) loader = "tsx";
|
|
681
|
+
else if (f.endsWith(".jsx")) loader = "jsx";
|
|
682
|
+
else if (f.endsWith(".js") || f.endsWith(".mjs") || f.endsWith(".cjs")) loader = "js";
|
|
683
|
+
else loader = "ts";
|
|
684
|
+
}
|
|
685
|
+
return loader;
|
|
686
|
+
}
|
|
687
|
+
function isJsxDefinitionLoader(options) {
|
|
688
|
+
const loader = resolveDefinitionLoader(options);
|
|
689
|
+
return loader === "tsx" || loader === "jsx";
|
|
690
|
+
}
|
|
691
|
+
function usesRuntimeModuleResolution(contents) {
|
|
692
|
+
return findDynamicImports(contents).some((imported) => !imported.expression.startsWith("\"")) || /\bimport\.meta\.resolve\s*\(/.test(contents) || /\bcreateRequire\b/.test(contents);
|
|
693
|
+
}
|
|
694
|
+
async function bundleDiscoveredDefinitionModule(options) {
|
|
695
|
+
const { build } = await import("esbuild");
|
|
696
|
+
const output = (await build({
|
|
697
|
+
alias: options.alias,
|
|
698
|
+
stdin: {
|
|
699
|
+
contents: options.source,
|
|
700
|
+
loader: resolveDefinitionLoader(options),
|
|
701
|
+
resolveDir: dirname$1(options.filename),
|
|
702
|
+
sourcefile: options.filename
|
|
703
|
+
},
|
|
704
|
+
bundle: true,
|
|
705
|
+
write: false,
|
|
706
|
+
format: "esm",
|
|
707
|
+
platform: "node",
|
|
708
|
+
target: "es2022",
|
|
709
|
+
logLevel: "silent",
|
|
710
|
+
jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
|
|
711
|
+
jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
|
|
712
|
+
packages: options.packages === "external" ? "external" : void 0,
|
|
713
|
+
external: [...builtinModuleSet$2, ...options.external || []],
|
|
714
|
+
plugins: options.plugins
|
|
715
|
+
})).outputFiles?.[0]?.text;
|
|
716
|
+
if (!output) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0047({ message: `[vitehub] Failed to bundle discovered definition "${options.filename}".` });
|
|
717
|
+
return output;
|
|
718
|
+
}
|
|
719
|
+
async function bundleDiscoveredDefinitionModuleGraph(options) {
|
|
720
|
+
const outdir = resolve$1(dirname$1(options.filename), ".vitehub-discovered-definition");
|
|
721
|
+
const { build } = await import("esbuild");
|
|
722
|
+
const result = await build({
|
|
723
|
+
alias: options.alias,
|
|
724
|
+
stdin: {
|
|
725
|
+
contents: options.source,
|
|
726
|
+
loader: resolveDefinitionLoader(options),
|
|
727
|
+
resolveDir: dirname$1(options.filename),
|
|
728
|
+
sourcefile: options.filename
|
|
729
|
+
},
|
|
730
|
+
bundle: true,
|
|
731
|
+
splitting: true,
|
|
732
|
+
entryNames: "definition",
|
|
733
|
+
chunkNames: "chunks/[name]-[hash]",
|
|
734
|
+
outdir,
|
|
735
|
+
write: false,
|
|
736
|
+
format: "esm",
|
|
737
|
+
platform: "node",
|
|
738
|
+
target: "es2022",
|
|
739
|
+
metafile: true,
|
|
740
|
+
logLevel: "silent",
|
|
741
|
+
jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
|
|
742
|
+
jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
|
|
743
|
+
packages: options.packages === "external" ? "external" : void 0,
|
|
744
|
+
external: [...builtinModuleSet$2, ...options.external || []],
|
|
745
|
+
plugins: options.plugins
|
|
746
|
+
});
|
|
747
|
+
const modules = Object.fromEntries((result.outputFiles || []).map((outputFile) => {
|
|
748
|
+
return [relative$1(outdir, outputFile.path), outputFile.text];
|
|
749
|
+
}));
|
|
750
|
+
if (!modules["definition.js"]) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0048({ message: `[vitehub] Failed to bundle discovered definition graph "${options.filename}".` });
|
|
751
|
+
return {
|
|
752
|
+
entry: "definition.js",
|
|
753
|
+
externalImports: [...new Set(Object.values(result.metafile.outputs).flatMap((output) => output.imports).filter((imported) => imported.external).map((imported) => imported.path))].sort(),
|
|
754
|
+
hasRuntimeModuleResolution: Object.values(modules).some(usesRuntimeModuleResolution),
|
|
755
|
+
modules
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
//#endregion
|
|
759
|
+
//#region src/task/internal/typescript.ts
|
|
760
|
+
const require = createRequire(import.meta.url);
|
|
761
|
+
function loadTypeScript() {
|
|
762
|
+
try {
|
|
763
|
+
return require("typescript");
|
|
764
|
+
} catch (error) {
|
|
765
|
+
if (error.code !== "MODULE_NOT_FOUND") throw error;
|
|
766
|
+
throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0013({ message: "[vitehub] Sandbox Tasks read their definitions with TypeScript. Install `typescript` in the app." });
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
//#endregion
|
|
770
|
+
//#region src/task/internal/shared/discovered-definition/ast.ts
|
|
771
|
+
const filesystemModuleSpecifiers = /* @__PURE__ */ new Set([
|
|
772
|
+
"child_process",
|
|
773
|
+
"fs",
|
|
774
|
+
"fs/promises",
|
|
775
|
+
"node:child_process",
|
|
776
|
+
"node:fs",
|
|
777
|
+
"node:fs/promises",
|
|
778
|
+
"node:sqlite",
|
|
779
|
+
"node:worker_threads",
|
|
780
|
+
"worker_threads"
|
|
781
|
+
]);
|
|
782
|
+
const pathModuleSpecifiers = /* @__PURE__ */ new Set([
|
|
783
|
+
"node:path",
|
|
784
|
+
"node:path/posix",
|
|
785
|
+
"path",
|
|
786
|
+
"path/posix"
|
|
787
|
+
]);
|
|
788
|
+
function resolveImportLocalName(entry) {
|
|
789
|
+
return entry.as || entry.name;
|
|
790
|
+
}
|
|
791
|
+
function getScriptKind(id) {
|
|
792
|
+
const typescript = loadTypeScript();
|
|
793
|
+
const scriptKind = typescript.ScriptKind;
|
|
794
|
+
if (id.endsWith(".tsx")) return typescript.ScriptKind.TSX;
|
|
795
|
+
if (id.endsWith(".jsx")) return typescript.ScriptKind.JSX;
|
|
796
|
+
if (id.endsWith(".mts")) return scriptKind.MTS ?? typescript.ScriptKind.TS;
|
|
797
|
+
if (id.endsWith(".cts")) return scriptKind.CTS ?? typescript.ScriptKind.TS;
|
|
798
|
+
if (id.endsWith(".mjs")) return typescript.ScriptKind.JS;
|
|
799
|
+
if (id.endsWith(".cjs")) return typescript.ScriptKind.JS;
|
|
800
|
+
if (id.endsWith(".js")) return typescript.ScriptKind.JS;
|
|
801
|
+
return typescript.ScriptKind.TS;
|
|
802
|
+
}
|
|
803
|
+
function createSourceFile(id, source) {
|
|
804
|
+
const typescript = loadTypeScript();
|
|
805
|
+
return typescript.createSourceFile(id, source, typescript.ScriptTarget.Latest, true, getScriptKind(id));
|
|
806
|
+
}
|
|
807
|
+
function collectRuntimeModuleSpecifiers(source, id) {
|
|
808
|
+
const typescript = loadTypeScript();
|
|
809
|
+
const sourceFile = createSourceFile(id, source);
|
|
810
|
+
const specifiers = [];
|
|
811
|
+
let hasNonLiteralDynamicImport = false;
|
|
812
|
+
function addSpecifier(node) {
|
|
813
|
+
if (node && typescript.isStringLiteralLike(node)) specifiers.push({
|
|
814
|
+
node,
|
|
815
|
+
specifier: node.text
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
function visit(node) {
|
|
819
|
+
if (typescript.isImportDeclaration(node)) {
|
|
820
|
+
const clause = node.importClause;
|
|
821
|
+
const bindings = clause?.namedBindings;
|
|
822
|
+
if (!clause || !clause.isTypeOnly && (Boolean(clause.name) || !bindings || typescript.isNamespaceImport(bindings) || bindings.elements.length === 0 || bindings.elements.some((element) => !element.isTypeOnly))) addSpecifier(node.moduleSpecifier);
|
|
823
|
+
} else if (typescript.isExportDeclaration(node)) {
|
|
824
|
+
const clause = node.exportClause;
|
|
825
|
+
if (!node.isTypeOnly && (!clause || typescript.isNamespaceExport(clause) || clause.elements.length === 0 || clause.elements.some((element) => !element.isTypeOnly))) addSpecifier(node.moduleSpecifier);
|
|
826
|
+
} else if (typescript.isCallExpression(node) && node.expression.kind === typescript.SyntaxKind.ImportKeyword) {
|
|
827
|
+
const argument = node.arguments[0];
|
|
828
|
+
if (argument && typescript.isStringLiteralLike(argument)) addSpecifier(argument);
|
|
829
|
+
else hasNonLiteralDynamicImport = true;
|
|
830
|
+
}
|
|
831
|
+
typescript.forEachChild(node, visit);
|
|
832
|
+
}
|
|
833
|
+
visit(sourceFile);
|
|
834
|
+
return {
|
|
835
|
+
hasNonLiteralDynamicImport,
|
|
836
|
+
sourceFile,
|
|
837
|
+
specifiers
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
function findRuntimeModuleSpecifiers(source, id) {
|
|
841
|
+
return collectRuntimeModuleSpecifiers(source, id).specifiers.map((entry) => entry.specifier);
|
|
842
|
+
}
|
|
843
|
+
function hasNonLiteralDynamicImport(source, id) {
|
|
844
|
+
return collectRuntimeModuleSpecifiers(source, id).hasNonLiteralDynamicImport;
|
|
845
|
+
}
|
|
846
|
+
function findFilesystemPathReferences(source, id) {
|
|
847
|
+
const typescript = loadTypeScript();
|
|
848
|
+
const sourceFile = createSourceFile(id, source);
|
|
849
|
+
const directBindings = /* @__PURE__ */ new Set();
|
|
850
|
+
const directBindingOperations = /* @__PURE__ */ new Map();
|
|
851
|
+
const namespaceBindings = /* @__PURE__ */ new Set();
|
|
852
|
+
const pathFunctionBindings = /* @__PURE__ */ new Set();
|
|
853
|
+
const pathNamespaceBindings = /* @__PURE__ */ new Set();
|
|
854
|
+
const requireBindings = /* @__PURE__ */ new Set(["require"]);
|
|
855
|
+
const createRequireBindings = /* @__PURE__ */ new Set();
|
|
856
|
+
const variableInitializers = /* @__PURE__ */ new Map();
|
|
857
|
+
const ambiguousVariables = /* @__PURE__ */ new Set();
|
|
858
|
+
const references = [];
|
|
859
|
+
function filesystemRequireSpecifier(expression) {
|
|
860
|
+
if (expression && (typescript.isPropertyAccessExpression(expression) || typescript.isElementAccessExpression(expression))) return filesystemRequireSpecifier(expression.expression);
|
|
861
|
+
const loader = expression && typescript.isCallExpression(expression) ? expression.expression : void 0;
|
|
862
|
+
const isFilesystemLoader = loader && (typescript.isIdentifier(loader) && requireBindings.has(loader.text) || typescript.isPropertyAccessExpression(loader) && typescript.isIdentifier(loader.expression) && loader.expression.text === "process" && loader.name.text === "getBuiltinModule");
|
|
863
|
+
if (!expression || !typescript.isCallExpression(expression) || !isFilesystemLoader) return;
|
|
864
|
+
const [specifier] = expression.arguments;
|
|
865
|
+
return specifier && typescript.isStringLiteralLike(specifier) && filesystemModuleSpecifiers.has(specifier.text) ? specifier.text : void 0;
|
|
866
|
+
}
|
|
867
|
+
function addCommonJSBinding(name) {
|
|
868
|
+
if (typescript.isIdentifier(name)) {
|
|
869
|
+
directBindings.add(name.text);
|
|
870
|
+
namespaceBindings.add(name.text);
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
for (const element of name.elements) if (!typescript.isOmittedExpression(element)) addCommonJSBinding(element.name);
|
|
874
|
+
}
|
|
875
|
+
for (const statement of sourceFile.statements) {
|
|
876
|
+
if (typescript.isImportDeclaration(statement) && typescript.isStringLiteralLike(statement.moduleSpecifier) && (statement.moduleSpecifier.text === "node:module" || statement.moduleSpecifier.text === "module") && !statement.importClause?.isTypeOnly) {
|
|
877
|
+
const bindings = statement.importClause?.namedBindings;
|
|
878
|
+
if (bindings && typescript.isNamedImports(bindings)) {
|
|
879
|
+
for (const binding of bindings.elements) if (!binding.isTypeOnly && (binding.propertyName?.text ?? binding.name.text) === "createRequire") createRequireBindings.add(binding.name.text);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
if (typescript.isImportEqualsDeclaration(statement) && !statement.isTypeOnly && typescript.isExternalModuleReference(statement.moduleReference) && statement.moduleReference.expression && typescript.isStringLiteralLike(statement.moduleReference.expression) && filesystemModuleSpecifiers.has(statement.moduleReference.expression.text)) {
|
|
883
|
+
namespaceBindings.add(statement.name.text);
|
|
884
|
+
continue;
|
|
885
|
+
}
|
|
886
|
+
if (!typescript.isImportDeclaration(statement) || !typescript.isStringLiteralLike(statement.moduleSpecifier) || !filesystemModuleSpecifiers.has(statement.moduleSpecifier.text) || statement.importClause?.isTypeOnly) continue;
|
|
887
|
+
const clause = statement.importClause;
|
|
888
|
+
if (clause?.name) namespaceBindings.add(clause.name.text);
|
|
889
|
+
const bindings = clause?.namedBindings;
|
|
890
|
+
if (bindings && typescript.isNamespaceImport(bindings)) namespaceBindings.add(bindings.name.text);
|
|
891
|
+
else if (bindings && typescript.isNamedImports(bindings)) {
|
|
892
|
+
for (const binding of bindings.elements) if (!binding.isTypeOnly) {
|
|
893
|
+
directBindings.add(binding.name.text);
|
|
894
|
+
directBindingOperations.set(binding.name.text, binding.propertyName?.text ?? binding.name.text);
|
|
895
|
+
namespaceBindings.add(binding.name.text);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
for (const statement of sourceFile.statements) {
|
|
900
|
+
if (!typescript.isImportDeclaration(statement) || !typescript.isStringLiteralLike(statement.moduleSpecifier) || !pathModuleSpecifiers.has(statement.moduleSpecifier.text) || statement.importClause?.isTypeOnly) continue;
|
|
901
|
+
const clause = statement.importClause;
|
|
902
|
+
if (clause?.name) pathNamespaceBindings.add(clause.name.text);
|
|
903
|
+
const bindings = clause?.namedBindings;
|
|
904
|
+
if (bindings && typescript.isNamespaceImport(bindings)) pathNamespaceBindings.add(bindings.name.text);
|
|
905
|
+
else if (bindings && typescript.isNamedImports(bindings)) for (const binding of bindings.elements) {
|
|
906
|
+
const importedName = binding.propertyName?.text ?? binding.name.text;
|
|
907
|
+
if (!binding.isTypeOnly && (importedName === "join" || importedName === "resolve")) pathFunctionBindings.add(binding.name.text);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
function collectCommonJSBindings(node) {
|
|
911
|
+
if (typescript.isVariableDeclaration(node)) {
|
|
912
|
+
if (typescript.isIdentifier(node.name) && node.initializer && typescript.isCallExpression(node.initializer) && typescript.isIdentifier(node.initializer.expression) && createRequireBindings.has(node.initializer.expression.text)) requireBindings.add(node.name.text);
|
|
913
|
+
if (node.initializer && typescript.isIdentifier(node.name) && typescript.isVariableDeclarationList(node.parent) && node.parent.flags & typescript.NodeFlags.Const) {
|
|
914
|
+
if (variableInitializers.has(node.name.text)) {
|
|
915
|
+
variableInitializers.delete(node.name.text);
|
|
916
|
+
ambiguousVariables.add(node.name.text);
|
|
917
|
+
} else if (!ambiguousVariables.has(node.name.text)) variableInitializers.set(node.name.text, node.initializer);
|
|
918
|
+
}
|
|
919
|
+
if (filesystemRequireSpecifier(node.initializer)) addCommonJSBinding(node.name);
|
|
920
|
+
}
|
|
921
|
+
typescript.forEachChild(node, collectCommonJSBindings);
|
|
922
|
+
}
|
|
923
|
+
collectCommonJSBindings(sourceFile);
|
|
924
|
+
function filesystemOperation(expression) {
|
|
925
|
+
if (typescript.isIdentifier(expression)) return directBindingOperations.get(expression.text) ?? (directBindings.has(expression.text) ? expression.text : void 0);
|
|
926
|
+
const root = propertyAccessRoot(expression);
|
|
927
|
+
if (typescript.isIdentifier(root.current) && namespaceBindings.has(root.current.text)) return root.properties.at(-1);
|
|
928
|
+
if (filesystemRequireSpecifier(expression)) return root.properties.at(-1);
|
|
929
|
+
}
|
|
930
|
+
function derivedFilesystemOperation(expression) {
|
|
931
|
+
const value = unwrapExpression(expression);
|
|
932
|
+
const directOperation = filesystemOperation(value);
|
|
933
|
+
if (directOperation) return directOperation;
|
|
934
|
+
if (!typescript.isCallExpression(value) || filesystemOperation(value.expression)) return;
|
|
935
|
+
const operations = new Set(value.arguments.map(derivedFilesystemOperation).filter((operation) => Boolean(operation)));
|
|
936
|
+
if (operations.size === 1) return [...operations][0];
|
|
937
|
+
return operations.size ? "wrapped-filesystem-operation" : void 0;
|
|
938
|
+
}
|
|
939
|
+
let foundWrappedBinding = true;
|
|
940
|
+
while (foundWrappedBinding) {
|
|
941
|
+
foundWrappedBinding = false;
|
|
942
|
+
for (const [name, initializer] of variableInitializers) {
|
|
943
|
+
if (directBindings.has(name)) continue;
|
|
944
|
+
const operation = derivedFilesystemOperation(initializer);
|
|
945
|
+
if (!operation) continue;
|
|
946
|
+
directBindings.add(name);
|
|
947
|
+
directBindingOperations.set(name, operation);
|
|
948
|
+
foundWrappedBinding = true;
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
function isPathFunction(expression) {
|
|
952
|
+
if (typescript.isIdentifier(expression)) return pathFunctionBindings.has(expression.text);
|
|
953
|
+
const root = propertyAccessRoot(expression);
|
|
954
|
+
return typescript.isIdentifier(root.current) && pathNamespaceBindings.has(root.current.text) && ["join", "resolve"].includes(root.properties.at(-1) || "");
|
|
955
|
+
}
|
|
956
|
+
function unwrapExpression(expression) {
|
|
957
|
+
if (typescript.isAwaitExpression(expression) || typescript.isParenthesizedExpression(expression) || typescript.isAsExpression(expression) || typescript.isTypeAssertionExpression(expression) || typescript.isNonNullExpression(expression) || typescript.isSatisfiesExpression(expression)) return unwrapExpression(expression.expression);
|
|
958
|
+
return expression;
|
|
959
|
+
}
|
|
960
|
+
function isTrackedFilesystemBindingUse(node) {
|
|
961
|
+
if (typescript.isImportSpecifier(node.parent) || typescript.isImportClause(node.parent) || typescript.isNamespaceImport(node.parent) || typescript.isImportEqualsDeclaration(node.parent)) return true;
|
|
962
|
+
let invokedExpression = node;
|
|
963
|
+
while ((typescript.isPropertyAccessExpression(invokedExpression.parent) || typescript.isElementAccessExpression(invokedExpression.parent)) && invokedExpression.parent.expression === invokedExpression) invokedExpression = invokedExpression.parent;
|
|
964
|
+
if ((typescript.isCallExpression(invokedExpression.parent) || typescript.isNewExpression(invokedExpression.parent)) && invokedExpression.parent.expression === invokedExpression && filesystemOperation(invokedExpression)) return true;
|
|
965
|
+
let current = node;
|
|
966
|
+
while (current.parent && !typescript.isVariableDeclaration(current.parent)) current = current.parent;
|
|
967
|
+
if (!current.parent || !typescript.isVariableDeclaration(current.parent) || current.parent.initializer !== current || !typescript.isIdentifier(current.parent.name)) return false;
|
|
968
|
+
return directBindings.has(current.parent.name.text) && Boolean(derivedFilesystemOperation(current.parent.initializer));
|
|
969
|
+
}
|
|
970
|
+
function resolveFilesystemPath(argument, seen = /* @__PURE__ */ new Set()) {
|
|
971
|
+
if (!argument) return;
|
|
972
|
+
const expression = unwrapExpression(argument);
|
|
973
|
+
if (typescript.isStringLiteralLike(expression)) return {
|
|
974
|
+
path: expression.text,
|
|
975
|
+
relativeTo: "working-directory"
|
|
976
|
+
};
|
|
977
|
+
if (typescript.isIdentifier(expression)) {
|
|
978
|
+
if (seen.has(expression.text)) return;
|
|
979
|
+
const initializer = variableInitializers.get(expression.text);
|
|
980
|
+
if (!initializer) return;
|
|
981
|
+
return resolveFilesystemPath(initializer, new Set(seen).add(expression.text));
|
|
982
|
+
}
|
|
983
|
+
if (typescript.isNewExpression(expression) && typescript.isIdentifier(expression.expression) && expression.expression.text === "URL") {
|
|
984
|
+
const [path, base] = expression.arguments || [];
|
|
985
|
+
if (path && typescript.isStringLiteralLike(path) && base && typescript.isPropertyAccessExpression(base) && base.name.text === "url" && typescript.isMetaProperty(base.expression) && base.expression.keywordToken === typescript.SyntaxKind.ImportKeyword) return {
|
|
986
|
+
path: path.text,
|
|
987
|
+
relativeTo: "module"
|
|
988
|
+
};
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
if (!typescript.isCallExpression(expression)) return;
|
|
992
|
+
if (filesystemOperation(expression.expression) === "mkdtemp") return "runtime";
|
|
993
|
+
if (!isPathFunction(expression.expression)) return;
|
|
994
|
+
const paths = expression.arguments.map((value) => resolveFilesystemPath(value, seen));
|
|
995
|
+
if (!paths.length) return;
|
|
996
|
+
const resolvedPaths = [];
|
|
997
|
+
for (const path of paths) {
|
|
998
|
+
if (path === "runtime") return "runtime";
|
|
999
|
+
if (!path || path.relativeTo !== "working-directory" || path.path === void 0) return;
|
|
1000
|
+
resolvedPaths.push(path);
|
|
1001
|
+
}
|
|
1002
|
+
return {
|
|
1003
|
+
path: join$1(...resolvedPaths.map((path) => path.path)),
|
|
1004
|
+
relativeTo: "working-directory"
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
function visit(node) {
|
|
1008
|
+
if (typescript.isIdentifier(node) && (directBindings.has(node.text) || namespaceBindings.has(node.text)) && !isTrackedFilesystemBindingUse(node)) references.push({ relativeTo: "working-directory" });
|
|
1009
|
+
if (typescript.isCallExpression(node) && node.expression.kind === typescript.SyntaxKind.ImportKeyword && node.arguments[0] && typescript.isStringLiteralLike(node.arguments[0]) && filesystemModuleSpecifiers.has(node.arguments[0].text)) references.push({ relativeTo: "working-directory" });
|
|
1010
|
+
if (typescript.isCallExpression(node) || typescript.isNewExpression(node)) {
|
|
1011
|
+
const operation = filesystemOperation(node.expression);
|
|
1012
|
+
if (operation) {
|
|
1013
|
+
const hasChildProcessArguments = [
|
|
1014
|
+
"execFile",
|
|
1015
|
+
"execFileSync",
|
|
1016
|
+
"fork",
|
|
1017
|
+
"spawn",
|
|
1018
|
+
"spawnSync"
|
|
1019
|
+
].includes(operation) && Boolean(node.arguments && node.arguments.length > 1);
|
|
1020
|
+
const reference = operation === "exec" || operation === "execSync" ? void 0 : resolveFilesystemPath(node.arguments?.[0]);
|
|
1021
|
+
if (operation !== "mkdtemp" && reference !== "runtime") references.push(hasChildProcessArguments ? { relativeTo: "working-directory" } : reference ?? { relativeTo: "working-directory" });
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
typescript.forEachChild(node, visit);
|
|
1025
|
+
}
|
|
1026
|
+
visit(sourceFile);
|
|
1027
|
+
return references;
|
|
1028
|
+
}
|
|
1029
|
+
function propertyAccessRoot(expression) {
|
|
1030
|
+
const typescript = loadTypeScript();
|
|
1031
|
+
const properties = [];
|
|
1032
|
+
let current = expression;
|
|
1033
|
+
while (typescript.isPropertyAccessExpression(current) || typescript.isElementAccessExpression(current)) {
|
|
1034
|
+
if (typescript.isPropertyAccessExpression(current)) {
|
|
1035
|
+
properties.unshift(current.name.text);
|
|
1036
|
+
current = current.expression;
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
const argument = current.argumentExpression;
|
|
1040
|
+
properties.unshift(argument && typescript.isStringLiteralLike(argument) ? argument.text : "*");
|
|
1041
|
+
current = current.expression;
|
|
1042
|
+
}
|
|
1043
|
+
return {
|
|
1044
|
+
current,
|
|
1045
|
+
properties
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
function findCommonJSImportEqualsSpecifiers(source, id) {
|
|
1049
|
+
const typescript = loadTypeScript();
|
|
1050
|
+
const sourceFile = createSourceFile(id, source);
|
|
1051
|
+
const specifiers = [];
|
|
1052
|
+
function visit(node) {
|
|
1053
|
+
if (typescript.isImportEqualsDeclaration(node) && !node.isTypeOnly && typescript.isExternalModuleReference(node.moduleReference)) {
|
|
1054
|
+
const expression = node.moduleReference.expression;
|
|
1055
|
+
specifiers.push({
|
|
1056
|
+
path: id,
|
|
1057
|
+
specifier: expression && typescript.isStringLiteralLike(expression) ? expression.text : void 0,
|
|
1058
|
+
syntax: "import-equals"
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
typescript.forEachChild(node, visit);
|
|
1062
|
+
}
|
|
1063
|
+
visit(sourceFile);
|
|
1064
|
+
return specifiers;
|
|
1065
|
+
}
|
|
1066
|
+
function isExecutableIdentifierReference(node) {
|
|
1067
|
+
const typescript = loadTypeScript();
|
|
1068
|
+
const parent = node.parent;
|
|
1069
|
+
if (typescript.isImportClause(parent) || typescript.isImportSpecifier(parent) || typescript.isNamespaceImport(parent) || typescript.isNamespaceExport(parent)) return false;
|
|
1070
|
+
if (typescript.isExportSpecifier(parent)) {
|
|
1071
|
+
if (parent.parent.parent.moduleSpecifier) return false;
|
|
1072
|
+
return parent.propertyName ? parent.propertyName === node : parent.name === node;
|
|
1073
|
+
}
|
|
1074
|
+
if (typescript.isBindingElement(parent) && (parent.name === node || parent.propertyName === node)) return false;
|
|
1075
|
+
if (typescript.isPropertyAccessExpression(parent) && parent.name === node) return false;
|
|
1076
|
+
if (typescript.isLabeledStatement(parent) || typescript.isBreakStatement(parent) || typescript.isContinueStatement(parent)) return false;
|
|
1077
|
+
if (!typescript.isShorthandPropertyAssignment(parent) && "name" in parent && parent.name === node) return false;
|
|
1078
|
+
return !("propertyName" in parent) || parent.propertyName !== node;
|
|
1079
|
+
}
|
|
1080
|
+
function findExecutableCommonJSModuleSpecifiers(sources) {
|
|
1081
|
+
const typescript = loadTypeScript();
|
|
1082
|
+
const executableSources = new Map([...sources].map(([path, source]) => [`/${path.replace(/^[/]+/, "")}`, source]));
|
|
1083
|
+
const options = {
|
|
1084
|
+
allowJs: true,
|
|
1085
|
+
checkJs: false,
|
|
1086
|
+
module: typescript.ModuleKind.ESNext,
|
|
1087
|
+
moduleDetection: typescript.ModuleDetectionKind.Force,
|
|
1088
|
+
noLib: true,
|
|
1089
|
+
noResolve: true,
|
|
1090
|
+
target: typescript.ScriptTarget.ES2022,
|
|
1091
|
+
types: []
|
|
1092
|
+
};
|
|
1093
|
+
const sourceFiles = /* @__PURE__ */ new Map();
|
|
1094
|
+
const program = typescript.createProgram({
|
|
1095
|
+
host: {
|
|
1096
|
+
fileExists: (fileName) => executableSources.has(fileName),
|
|
1097
|
+
getCanonicalFileName: (fileName) => fileName,
|
|
1098
|
+
getCurrentDirectory: () => "/",
|
|
1099
|
+
getDefaultLibFileName: () => "",
|
|
1100
|
+
getNewLine: () => "\n",
|
|
1101
|
+
getSourceFile(fileName, languageVersion) {
|
|
1102
|
+
const source = executableSources.get(fileName);
|
|
1103
|
+
if (source === void 0) return void 0;
|
|
1104
|
+
let sourceFile = sourceFiles.get(fileName);
|
|
1105
|
+
if (!sourceFile) {
|
|
1106
|
+
sourceFile = typescript.createSourceFile(fileName, source, languageVersion, true, typescript.ScriptKind.JS);
|
|
1107
|
+
sourceFiles.set(fileName, sourceFile);
|
|
1108
|
+
}
|
|
1109
|
+
return sourceFile;
|
|
1110
|
+
},
|
|
1111
|
+
readFile: (fileName) => executableSources.get(fileName),
|
|
1112
|
+
useCaseSensitiveFileNames: () => true,
|
|
1113
|
+
writeFile: () => {}
|
|
1114
|
+
},
|
|
1115
|
+
options,
|
|
1116
|
+
rootNames: [...executableSources.keys()]
|
|
1117
|
+
});
|
|
1118
|
+
const checker = program.getTypeChecker();
|
|
1119
|
+
const specifiers = [];
|
|
1120
|
+
function isRuntimeBindingDeclaration(node) {
|
|
1121
|
+
return typescript.isBindingElement(node) || typescript.isClassDeclaration(node) || typescript.isClassExpression(node) || typescript.isFunctionDeclaration(node) || typescript.isFunctionExpression(node) || typescript.isImportClause(node) || typescript.isImportSpecifier(node) || typescript.isNamespaceImport(node) || typescript.isParameter(node) || typescript.isVariableDeclaration(node);
|
|
1122
|
+
}
|
|
1123
|
+
function isBound(node) {
|
|
1124
|
+
return (typescript.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node))?.declarations?.some(isRuntimeBindingDeclaration) ?? false;
|
|
1125
|
+
}
|
|
1126
|
+
function visit(sourceFile, node) {
|
|
1127
|
+
if (typescript.isCallExpression(node) && typescript.isIdentifier(node.expression) && node.expression.text === "require" && !isBound(node.expression)) {
|
|
1128
|
+
const argument = node.arguments[0];
|
|
1129
|
+
specifiers.push({
|
|
1130
|
+
path: sourceFile.fileName.slice(1),
|
|
1131
|
+
specifier: argument && typescript.isStringLiteralLike(argument) ? argument.text : void 0,
|
|
1132
|
+
syntax: "require"
|
|
1133
|
+
});
|
|
1134
|
+
} else if (typescript.isPropertyAccessExpression(node) || typescript.isElementAccessExpression(node)) {
|
|
1135
|
+
const { current, properties } = propertyAccessRoot(node);
|
|
1136
|
+
if (typescript.isIdentifier(current) && current.text === "require" && !isBound(current)) specifiers.push({
|
|
1137
|
+
path: sourceFile.fileName.slice(1),
|
|
1138
|
+
specifier: properties.join("."),
|
|
1139
|
+
syntax: "require-property"
|
|
1140
|
+
});
|
|
1141
|
+
} else if (typescript.isBinaryExpression(node) && node.operatorToken.kind >= typescript.SyntaxKind.FirstAssignment && node.operatorToken.kind <= typescript.SyntaxKind.LastAssignment) {
|
|
1142
|
+
const { current, properties } = propertyAccessRoot(node.left);
|
|
1143
|
+
if (typescript.isIdentifier(current) && current.text === "module" && !isBound(current) && properties[0] === "exports") specifiers.push({
|
|
1144
|
+
path: sourceFile.fileName.slice(1),
|
|
1145
|
+
syntax: "module-exports-assignment"
|
|
1146
|
+
});
|
|
1147
|
+
else if (typescript.isIdentifier(current) && current.text === "exports" && !isBound(current) && properties.length) specifiers.push({
|
|
1148
|
+
path: sourceFile.fileName.slice(1),
|
|
1149
|
+
syntax: "exports-assignment"
|
|
1150
|
+
});
|
|
1151
|
+
} else if (typescript.isIdentifier(node) && (node.text === "module" || node.text === "exports") && isExecutableIdentifierReference(node) && !isBound(node)) specifiers.push({
|
|
1152
|
+
path: sourceFile.fileName.slice(1),
|
|
1153
|
+
syntax: node.text === "module" ? "module-reference" : "exports-reference"
|
|
1154
|
+
});
|
|
1155
|
+
typescript.forEachChild(node, (child) => visit(sourceFile, child));
|
|
1156
|
+
}
|
|
1157
|
+
for (const sourceFile of program.getSourceFiles()) visit(sourceFile, sourceFile);
|
|
1158
|
+
return specifiers;
|
|
1159
|
+
}
|
|
1160
|
+
function rewriteRuntimeRelativeModuleSpecifiers(source, id, rewrite) {
|
|
1161
|
+
const { sourceFile, specifiers } = collectRuntimeModuleSpecifiers(source, id);
|
|
1162
|
+
const edits = [];
|
|
1163
|
+
for (const { node, specifier } of specifiers) {
|
|
1164
|
+
if (!/^\.\.?\//.test(specifier)) continue;
|
|
1165
|
+
const replacement = rewrite(specifier);
|
|
1166
|
+
if (replacement !== specifier) edits.push({
|
|
1167
|
+
start: node.getStart(sourceFile),
|
|
1168
|
+
end: node.getEnd(),
|
|
1169
|
+
replacement: JSON.stringify(replacement)
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
return edits.sort((left, right) => right.start - left.start).reduce((contents, edit) => `${contents.slice(0, edit.start)}${edit.replacement}${contents.slice(edit.end)}`, source);
|
|
1173
|
+
}
|
|
1174
|
+
function collectExplicitImportNames(sourceFile) {
|
|
1175
|
+
const typescript = loadTypeScript();
|
|
1176
|
+
const names = /* @__PURE__ */ new Set();
|
|
1177
|
+
for (const statement of sourceFile.statements) {
|
|
1178
|
+
if (!typescript.isImportDeclaration(statement)) continue;
|
|
1179
|
+
const clause = statement.importClause;
|
|
1180
|
+
if (!clause) continue;
|
|
1181
|
+
if (clause.name) names.add(clause.name.text);
|
|
1182
|
+
const bindings = clause.namedBindings;
|
|
1183
|
+
if (!bindings) continue;
|
|
1184
|
+
if (typescript.isNamespaceImport(bindings)) {
|
|
1185
|
+
names.add(bindings.name.text);
|
|
1186
|
+
continue;
|
|
1187
|
+
}
|
|
1188
|
+
for (const element of bindings.elements) names.add(element.name.text);
|
|
1189
|
+
}
|
|
1190
|
+
return names;
|
|
1191
|
+
}
|
|
1192
|
+
function collectDeclaredTypeNames(sourceFile) {
|
|
1193
|
+
const typescript = loadTypeScript();
|
|
1194
|
+
const names = /* @__PURE__ */ new Set();
|
|
1195
|
+
function visit(node) {
|
|
1196
|
+
if ((typescript.isInterfaceDeclaration(node) || typescript.isTypeAliasDeclaration(node) || typescript.isClassDeclaration(node) || typescript.isEnumDeclaration(node)) && node.name) names.add(node.name.text);
|
|
1197
|
+
if ((typescript.isFunctionDeclaration(node) || typescript.isClassDeclaration(node) || typescript.isInterfaceDeclaration(node) || typescript.isMethodDeclaration(node) || typescript.isArrowFunction(node) || typescript.isFunctionExpression(node) || typescript.isTypeAliasDeclaration(node)) && node.typeParameters) for (const parameter of node.typeParameters) names.add(parameter.name.text);
|
|
1198
|
+
typescript.forEachChild(node, visit);
|
|
1199
|
+
}
|
|
1200
|
+
visit(sourceFile);
|
|
1201
|
+
return names;
|
|
1202
|
+
}
|
|
1203
|
+
function collectTypeReferenceNames(sourceFile) {
|
|
1204
|
+
const typescript = loadTypeScript();
|
|
1205
|
+
const names = /* @__PURE__ */ new Set();
|
|
1206
|
+
function addEntityName(name) {
|
|
1207
|
+
if (typescript.isIdentifier(name)) names.add(name.text);
|
|
1208
|
+
}
|
|
1209
|
+
function visit(node) {
|
|
1210
|
+
if (typescript.isImportTypeNode(node) || typescript.isTypeQueryNode(node)) return;
|
|
1211
|
+
if (typescript.isTypeReferenceNode(node)) {
|
|
1212
|
+
addEntityName(node.typeName);
|
|
1213
|
+
node.typeArguments?.forEach((argument) => visit(argument));
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
if (typescript.isExpressionWithTypeArguments(node)) {
|
|
1217
|
+
if (typescript.isIdentifier(node.expression)) names.add(node.expression.text);
|
|
1218
|
+
node.typeArguments?.forEach((argument) => visit(argument));
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
typescript.forEachChild(node, visit);
|
|
1222
|
+
}
|
|
1223
|
+
visit(sourceFile);
|
|
1224
|
+
return names;
|
|
1225
|
+
}
|
|
1226
|
+
function groupTypeImports(imports) {
|
|
1227
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
1228
|
+
for (const entry of imports) {
|
|
1229
|
+
const from = entry.typeFrom || entry.from;
|
|
1230
|
+
const entries = grouped.get(from);
|
|
1231
|
+
if (entries) {
|
|
1232
|
+
entries.push(entry);
|
|
1233
|
+
continue;
|
|
1234
|
+
}
|
|
1235
|
+
grouped.set(from, [entry]);
|
|
1236
|
+
}
|
|
1237
|
+
return grouped;
|
|
1238
|
+
}
|
|
1239
|
+
function stringifyTypeImport(entry) {
|
|
1240
|
+
const localName = resolveImportLocalName(entry);
|
|
1241
|
+
if (localName === entry.name) return entry.name;
|
|
1242
|
+
return `${entry.name} as ${localName}`;
|
|
1243
|
+
}
|
|
1244
|
+
function injectTypeImports(source, imports, id) {
|
|
1245
|
+
const typescript = loadTypeScript();
|
|
1246
|
+
if (!imports.length) return source;
|
|
1247
|
+
const importStatements = createSourceFile(id, source).statements.filter(typescript.isImportDeclaration);
|
|
1248
|
+
const groupedImports = groupTypeImports(imports);
|
|
1249
|
+
const block = Array.from(groupedImports.entries()).map(([from, entries]) => `import type { ${entries.map(stringifyTypeImport).join(", ")} } from ${JSON.stringify(from)}`).join("\n");
|
|
1250
|
+
if (!block) return source;
|
|
1251
|
+
const insertAt = importStatements.at(-1)?.end ?? (source.startsWith("#!") ? source.indexOf("\n") + 1 : 0);
|
|
1252
|
+
const prefix = source.slice(0, insertAt);
|
|
1253
|
+
const suffix = source.slice(insertAt);
|
|
1254
|
+
const needsLeadingNewline = insertAt > 0 && !prefix.endsWith("\n");
|
|
1255
|
+
const needsTrailingNewline = suffix.length > 0 && !suffix.startsWith("\n");
|
|
1256
|
+
return `${prefix}${needsLeadingNewline ? "\n" : ""}${block}${needsTrailingNewline ? "\n" : ""}${suffix}`;
|
|
1257
|
+
}
|
|
1258
|
+
async function injectTypeImportsFromUnimport(source, id, imports) {
|
|
1259
|
+
const sourceFile = createSourceFile(id, source);
|
|
1260
|
+
const explicitImports = collectExplicitImportNames(sourceFile);
|
|
1261
|
+
const declaredTypes = collectDeclaredTypeNames(sourceFile);
|
|
1262
|
+
const usedTypes = collectTypeReferenceNames(sourceFile);
|
|
1263
|
+
const pendingImports = [];
|
|
1264
|
+
for (const entry of imports) {
|
|
1265
|
+
if (!entry.type || entry.disabled) continue;
|
|
1266
|
+
const localName = resolveImportLocalName(entry);
|
|
1267
|
+
if (!usedTypes.has(localName)) continue;
|
|
1268
|
+
if (explicitImports.has(localName) || declaredTypes.has(localName)) continue;
|
|
1269
|
+
pendingImports.push(entry);
|
|
1270
|
+
explicitImports.add(localName);
|
|
1271
|
+
}
|
|
1272
|
+
return injectTypeImports(source, pendingImports, id);
|
|
1273
|
+
}
|
|
1274
|
+
//#endregion
|
|
1275
|
+
//#region src/task/internal/shared/server-imports.ts
|
|
1276
|
+
function isServerAutoImportEnabled(imports) {
|
|
1277
|
+
return imports !== false && imports?.autoImport !== false;
|
|
1278
|
+
}
|
|
1279
|
+
//#endregion
|
|
1280
|
+
//#region src/task/internal/shared/discovered-definition.ts
|
|
1281
|
+
function normalizeDir(rootDir, dir) {
|
|
1282
|
+
if (typeof dir === "string") return isAbsolute$1(dir) ? dir : resolve$1(rootDir, dir);
|
|
1283
|
+
return {
|
|
1284
|
+
...dir,
|
|
1285
|
+
glob: isAbsolute$1(dir.glob) ? dir.glob : resolve$1(rootDir, dir.glob)
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
function normalizePresetImport(from, entry) {
|
|
1289
|
+
if (typeof entry === "string") return {
|
|
1290
|
+
from,
|
|
1291
|
+
name: entry
|
|
1292
|
+
};
|
|
1293
|
+
return {
|
|
1294
|
+
from,
|
|
1295
|
+
name: entry.name,
|
|
1296
|
+
...entry.as ? { as: entry.as } : {},
|
|
1297
|
+
...entry.type ? { type: true } : {}
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
function normalizeServerImport(entry) {
|
|
1301
|
+
return {
|
|
1302
|
+
from: entry.from,
|
|
1303
|
+
name: entry.name,
|
|
1304
|
+
...entry.as ? { as: entry.as } : {},
|
|
1305
|
+
...entry.type ? { type: true } : {}
|
|
1306
|
+
};
|
|
1307
|
+
}
|
|
1308
|
+
function resolveDefaultImportDirs(rootDir, scanRoots) {
|
|
1309
|
+
return scanRoots.flatMap((scanRoot) => [normalizeDir(rootDir, join$1(scanRoot, "server/utils/**/*")), normalizeDir(rootDir, join$1(scanRoot, "shared/types/**/*"))]);
|
|
1310
|
+
}
|
|
1311
|
+
function isInlinePreset(value) {
|
|
1312
|
+
return !!value && typeof value === "object" && typeof value.from === "string" && Array.isArray(value.imports);
|
|
1313
|
+
}
|
|
1314
|
+
function isPresetImport(value) {
|
|
1315
|
+
return !!value && typeof value === "object" && typeof value.name === "string";
|
|
1316
|
+
}
|
|
1317
|
+
function normalizePresetImports(presets = []) {
|
|
1318
|
+
const normalized = [];
|
|
1319
|
+
function collect(from, entry) {
|
|
1320
|
+
if (typeof entry === "string") {
|
|
1321
|
+
normalized.push(normalizePresetImport(from, entry));
|
|
1322
|
+
return;
|
|
1323
|
+
}
|
|
1324
|
+
if (isInlinePreset(entry)) {
|
|
1325
|
+
for (const nested of entry.imports) collect(entry.from, nested);
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
if (isPresetImport(entry)) normalized.push(normalizePresetImport(from, entry));
|
|
1329
|
+
}
|
|
1330
|
+
for (const preset of presets) {
|
|
1331
|
+
if (!isInlinePreset(preset)) continue;
|
|
1332
|
+
for (const entry of preset.imports) collect(preset.from, entry);
|
|
1333
|
+
}
|
|
1334
|
+
return normalized;
|
|
1335
|
+
}
|
|
1336
|
+
async function createInitializedUnimport(options) {
|
|
1337
|
+
const serverImports = options.serverImports !== false ? options.serverImports : void 0;
|
|
1338
|
+
const imports = [...normalizePresetImports(serverImports?.presets), ...(options.featureImports || []).map(normalizeServerImport)];
|
|
1339
|
+
const dirs = [...resolveDefaultImportDirs(options.rootDir, options.scanRoots), ...(serverImports?.dirs || []).map((dir) => normalizeDir(options.rootDir, dir))];
|
|
1340
|
+
const { createUnimport } = await import("unimport");
|
|
1341
|
+
const unimport = createUnimport({
|
|
1342
|
+
imports,
|
|
1343
|
+
dirs
|
|
1344
|
+
});
|
|
1345
|
+
await unimport.init();
|
|
1346
|
+
return unimport;
|
|
1347
|
+
}
|
|
1348
|
+
async function createDiscoveredDefinitionCompiler(options = {}) {
|
|
1349
|
+
const resolvedOptions = {
|
|
1350
|
+
rootDir: options.rootDir || process.cwd(),
|
|
1351
|
+
scanRoots: options.scanRoots || [],
|
|
1352
|
+
serverImports: options.serverImports,
|
|
1353
|
+
featureImports: options.featureImports || []
|
|
1354
|
+
};
|
|
1355
|
+
if (!isServerAutoImportEnabled(resolvedOptions.serverImports)) return {
|
|
1356
|
+
enabled: false,
|
|
1357
|
+
async injectSource(source) {
|
|
1358
|
+
return source;
|
|
1359
|
+
},
|
|
1360
|
+
async readSource(id) {
|
|
1361
|
+
return await readFile(id, "utf8");
|
|
1362
|
+
},
|
|
1363
|
+
async bundleModule(bundleOptions) {
|
|
1364
|
+
return await bundleDiscoveredDefinitionModule(bundleOptions);
|
|
1365
|
+
}
|
|
1366
|
+
};
|
|
1367
|
+
const unimport = await createInitializedUnimport(resolvedOptions);
|
|
1368
|
+
const injectSource = async (source, id) => {
|
|
1369
|
+
return await injectTypeImportsFromUnimport((await unimport.injectImports(source, id)).code, id, await unimport.getImports());
|
|
1370
|
+
};
|
|
1371
|
+
return {
|
|
1372
|
+
enabled: true,
|
|
1373
|
+
injectSource,
|
|
1374
|
+
async readSource(id) {
|
|
1375
|
+
return await injectSource(await readFile(id, "utf8"), id);
|
|
1376
|
+
},
|
|
1377
|
+
async bundleModule(bundleOptions) {
|
|
1378
|
+
return await bundleDiscoveredDefinitionModule(bundleOptions);
|
|
1379
|
+
}
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
//#endregion
|
|
1383
|
+
//#region src/task/internal/shared/feature-definitions.ts
|
|
1384
|
+
function toTemplateSafeName(name) {
|
|
1385
|
+
return name.replace(/[^a-z0-9/_:-]/gi, "_").replace(/\//g, "__").replace(/:/g, "__");
|
|
1386
|
+
}
|
|
1387
|
+
//#endregion
|
|
1388
|
+
//#region src/task/internal/shared/file-import-specifier.ts
|
|
1389
|
+
function createFileImportSpecifier(file, platform = process.platform) {
|
|
1390
|
+
return pathToFileURL(file, { windows: platform === "win32" }).href;
|
|
1391
|
+
}
|
|
1392
|
+
//#endregion
|
|
1393
|
+
//#region src/task/internal/shared/module-resolve.ts
|
|
1394
|
+
function normalizePaths(paths) {
|
|
1395
|
+
if (paths?.length) return paths;
|
|
1396
|
+
if (typeof process !== "undefined") return [process.cwd()];
|
|
1397
|
+
return [];
|
|
1398
|
+
}
|
|
1399
|
+
function tryResolveFromRuntime(id) {
|
|
1400
|
+
const requireResolver = globalThis.require?.resolve;
|
|
1401
|
+
if (typeof requireResolver !== "function") return void 0;
|
|
1402
|
+
try {
|
|
1403
|
+
return requireResolver(id);
|
|
1404
|
+
} catch {
|
|
1405
|
+
return false;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
function tryResolveModule(id, options = {}) {
|
|
1409
|
+
const paths = normalizePaths(options.paths);
|
|
1410
|
+
const runtimeResolved = tryResolveFromRuntime(id);
|
|
1411
|
+
if (runtimeResolved === false) return [sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0050({ message: `Unable to resolve module "${id}" using the active runtime resolver` }), void 0];
|
|
1412
|
+
if (runtimeResolved) return [null, runtimeResolved];
|
|
1413
|
+
const resolved = resolveModule(id, { paths });
|
|
1414
|
+
if (resolved) return [null, resolved];
|
|
1415
|
+
for (const url of paths) try {
|
|
1416
|
+
return [null, resolvePathSync(id, { url })];
|
|
1417
|
+
} catch {
|
|
1418
|
+
continue;
|
|
1419
|
+
}
|
|
1420
|
+
return [sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0051({ message: paths.length > 0 ? `Unable to resolve module "${id}" from ${paths.join(", ")}` : `Unable to resolve module "${id}" without explicit resolution paths` }), void 0];
|
|
1421
|
+
}
|
|
1422
|
+
//#endregion
|
|
1423
|
+
//#region src/task/internal/shared/feature-runtime-path.ts
|
|
1424
|
+
function resolveExistingModulePath(path) {
|
|
1425
|
+
if (existsSync(path)) return path;
|
|
1426
|
+
for (const extension of [
|
|
1427
|
+
".ts",
|
|
1428
|
+
".mts",
|
|
1429
|
+
".js",
|
|
1430
|
+
".mjs"
|
|
1431
|
+
]) {
|
|
1432
|
+
const withExtension = `${path}${extension}`;
|
|
1433
|
+
if (existsSync(withExtension)) return withExtension;
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
function resolveFeatureRuntimePath(importMetaUrl, packageId, sourceRelativePath, distRelativePath) {
|
|
1437
|
+
const importerPath = fileURLToPath(importMetaUrl);
|
|
1438
|
+
const importerDir = dirname$1(importerPath);
|
|
1439
|
+
const sourcePath = resolve$1(importerDir, sourceRelativePath);
|
|
1440
|
+
const importerUsesDist = importerDir.split(sep$1).includes("dist");
|
|
1441
|
+
const targetsSourceTree = /(?:^|\/)\.\.\/src(?:\/|$)|^\.\/*src(?:\/|$)/.test(sourceRelativePath);
|
|
1442
|
+
const resolvedSourcePath = resolveExistingModulePath(sourcePath);
|
|
1443
|
+
if ((!importerUsesDist || !targetsSourceTree) && resolvedSourcePath) return resolvedSourcePath;
|
|
1444
|
+
const [packageJsonError, packageJsonPath] = tryResolveModule(`${packageId}/package.json`);
|
|
1445
|
+
if (!packageJsonError) {
|
|
1446
|
+
const packageRoot = dirname$1(packageJsonPath);
|
|
1447
|
+
const resolvedPackageSourcePath = resolveExistingModulePath(join$1(packageRoot, "src", sourceRelativePath.replace(/^(\.\.\/)+src\//, "").replace(/^\.\//, "")));
|
|
1448
|
+
if ((!importerUsesDist || !targetsSourceTree) && resolvedPackageSourcePath) return resolvedPackageSourcePath;
|
|
1449
|
+
return join$1(dirname$1(packageJsonPath), "dist", distRelativePath);
|
|
1450
|
+
}
|
|
1451
|
+
const [packageError, packagePath] = tryResolveModule(packageId);
|
|
1452
|
+
if (!packageError) return join$1(dirname$1(packagePath), distRelativePath);
|
|
1453
|
+
return sourcePath;
|
|
1454
|
+
}
|
|
1455
|
+
//#endregion
|
|
1456
|
+
//#region src/task/project.ts
|
|
1457
|
+
const sandboxTaskProjectSourceFiles = /* @__PURE__ */ new WeakMap();
|
|
1458
|
+
function getSandboxTaskProjectSourceFiles(project) {
|
|
1459
|
+
return sandboxTaskProjectSourceFiles.get(project) || [];
|
|
1460
|
+
}
|
|
1461
|
+
const maxTimeout = 2147483647;
|
|
1462
|
+
const lockfiles = [
|
|
1463
|
+
{
|
|
1464
|
+
file: "pnpm-lock.yaml",
|
|
1465
|
+
manager: "pnpm"
|
|
1466
|
+
},
|
|
1467
|
+
{
|
|
1468
|
+
file: "package-lock.json",
|
|
1469
|
+
manager: "npm"
|
|
1470
|
+
},
|
|
1471
|
+
{
|
|
1472
|
+
file: "yarn.lock",
|
|
1473
|
+
manager: "yarn"
|
|
1474
|
+
},
|
|
1475
|
+
{
|
|
1476
|
+
file: "bun.lock",
|
|
1477
|
+
manager: "bun"
|
|
1478
|
+
}
|
|
1479
|
+
];
|
|
1480
|
+
const projectFileExcludes = [
|
|
1481
|
+
"node_modules/**",
|
|
1482
|
+
".git/**",
|
|
1483
|
+
"**/.env",
|
|
1484
|
+
"**/.env.*",
|
|
1485
|
+
"**/.npmrc",
|
|
1486
|
+
"bun.lockb"
|
|
1487
|
+
];
|
|
1488
|
+
function isInside(root, path) {
|
|
1489
|
+
const next = relative(root, path);
|
|
1490
|
+
return next === "" || !next.startsWith("..") && !next.startsWith("/");
|
|
1491
|
+
}
|
|
1492
|
+
async function isFile(path, root) {
|
|
1493
|
+
if (!await stat(path).then((value) => value.isFile(), () => false)) return false;
|
|
1494
|
+
if (!isInside(root, await realpath(path))) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0055({ message: `[vitehub] Sandbox project file escapes its scan root: ${path}` });
|
|
1495
|
+
return true;
|
|
1496
|
+
}
|
|
1497
|
+
function ancestors(start, root) {
|
|
1498
|
+
const paths = [];
|
|
1499
|
+
let current = start;
|
|
1500
|
+
while (isInside(root, current)) {
|
|
1501
|
+
paths.push(current);
|
|
1502
|
+
if (current === root) break;
|
|
1503
|
+
const parent = dirname(current);
|
|
1504
|
+
if (parent === current) break;
|
|
1505
|
+
current = parent;
|
|
1506
|
+
}
|
|
1507
|
+
return paths;
|
|
1508
|
+
}
|
|
1509
|
+
function packageManagerFromField(value) {
|
|
1510
|
+
if (typeof value !== "string") return void 0;
|
|
1511
|
+
const name = value.split("@", 1)[0];
|
|
1512
|
+
return name === "pnpm" || name === "npm" || name === "yarn" || name === "bun" ? name : void 0;
|
|
1513
|
+
}
|
|
1514
|
+
function packageManagerMajor(value) {
|
|
1515
|
+
if (typeof value !== "string") return void 0;
|
|
1516
|
+
const version = value.slice(value.indexOf("@") + 1);
|
|
1517
|
+
const major = Number.parseInt(version, 10);
|
|
1518
|
+
return Number.isFinite(major) ? major : void 0;
|
|
1519
|
+
}
|
|
1520
|
+
function installArgs(manager, hasLockfile, declaredMajor) {
|
|
1521
|
+
if (manager === "npm") return hasLockfile ? ["ci"] : ["install"];
|
|
1522
|
+
if (manager === "yarn") return hasLockfile ? ["install", declaredMajor === 1 ? "--frozen-lockfile" : "--immutable"] : ["install"];
|
|
1523
|
+
return hasLockfile ? ["install", "--frozen-lockfile"] : ["install"];
|
|
1524
|
+
}
|
|
1525
|
+
function parseManifest(source, path) {
|
|
1526
|
+
try {
|
|
1527
|
+
return JSON.parse(source);
|
|
1528
|
+
} catch (error) {
|
|
1529
|
+
throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0056({
|
|
1530
|
+
message: `[vitehub] Sandbox package manifest is invalid JSON: ${path}`,
|
|
1531
|
+
cause: error
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
function isPlainObject(value) {
|
|
1536
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
1537
|
+
}
|
|
1538
|
+
function parseSandboxTaskProjectOptions(manifest, path) {
|
|
1539
|
+
if (typeof manifest.vitehub === "undefined") return void 0;
|
|
1540
|
+
if (!isPlainObject(manifest.vitehub)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0057({ message: `[vitehub] Sandbox package manifest "vitehub" must be an object: ${path}` });
|
|
1541
|
+
const sandbox = manifest.vitehub.sandboxTask;
|
|
1542
|
+
if (typeof sandbox === "undefined") return void 0;
|
|
1543
|
+
if (!isPlainObject(sandbox)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0058({ message: `[vitehub] Sandbox package manifest "vitehub.sandboxTask" must be an object: ${path}` });
|
|
1544
|
+
const unsupported = Object.keys(sandbox).filter((key) => key !== "timeout");
|
|
1545
|
+
if (unsupported.length) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0059({ message: `[vitehub] Sandbox package manifest "vitehub.sandboxTask" has unsupported keys: ${unsupported.join(", ")}.` });
|
|
1546
|
+
const timeout = sandbox.timeout;
|
|
1547
|
+
if (timeout === void 0) return void 0;
|
|
1548
|
+
const numericTimeout = Number(timeout);
|
|
1549
|
+
if (numericTimeout !== timeout || !Number.isInteger(numericTimeout) || numericTimeout <= 0 || numericTimeout > maxTimeout) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0060({ message: `[vitehub] Sandbox package manifest "vitehub.sandboxTask.timeout" must be a positive integer no greater than ${maxTimeout}.` });
|
|
1550
|
+
return { timeout: numericTimeout };
|
|
1551
|
+
}
|
|
1552
|
+
function pnpmPatchPaths(manifest) {
|
|
1553
|
+
if (!isPlainObject(manifest.pnpm) || !isPlainObject(manifest.pnpm.patchedDependencies)) return [];
|
|
1554
|
+
return Object.values(manifest.pnpm.patchedDependencies).filter((value) => typeof value === "string");
|
|
1555
|
+
}
|
|
1556
|
+
function parsePnpmWorkspacePatchPaths(source) {
|
|
1557
|
+
const workspace = parse$1(source);
|
|
1558
|
+
const patchedDependencies = isPlainObject(workspace) ? Reflect.get(workspace, "patchedDependencies") : void 0;
|
|
1559
|
+
if (!isPlainObject(patchedDependencies)) return [];
|
|
1560
|
+
return Object.values(patchedDependencies).filter((value) => value === String(value)).map(String);
|
|
1561
|
+
}
|
|
1562
|
+
function parsePnpmWorkspacePackages(source) {
|
|
1563
|
+
const patterns = [];
|
|
1564
|
+
let packagesIndent;
|
|
1565
|
+
for (const line of source.split(/\r?\n/)) {
|
|
1566
|
+
if (packagesIndent === void 0) {
|
|
1567
|
+
const inline = /^\s*packages\s*:\s*\[(.*)\]\s*(?:#.*)?$/.exec(line);
|
|
1568
|
+
if (inline) return inline[1].split(",").map((value) => value.trim().replace(/^(['"])(.*)\1$/, "$2")).filter(Boolean);
|
|
1569
|
+
const match = /^(\s*)packages\s*:\s*(?:#.*)?$/.exec(line);
|
|
1570
|
+
if (match) packagesIndent = match[1].length;
|
|
1571
|
+
continue;
|
|
1572
|
+
}
|
|
1573
|
+
if (!line.trim() || /^\s*#/.test(line)) continue;
|
|
1574
|
+
if ((/^\s*/.exec(line)?.[0].length || 0) <= packagesIndent) break;
|
|
1575
|
+
const item = /^\s*-\s*(.+?)\s*$/.exec(line)?.[1];
|
|
1576
|
+
if (!item) continue;
|
|
1577
|
+
const value = item.replace(/\s+#.*$/, "").trim().replace(/^(['"])(.*)\1$/, "$2");
|
|
1578
|
+
if (value) patterns.push(value.replaceAll("\\", "/").replace(/\/$/, ""));
|
|
1579
|
+
}
|
|
1580
|
+
return patterns;
|
|
1581
|
+
}
|
|
1582
|
+
function isWorkspacePackage(path, patterns) {
|
|
1583
|
+
return patterns.filter((pattern) => !pattern.startsWith("!")).some((pattern) => matchesGlob(path, pattern)) && !patterns.filter((pattern) => pattern.startsWith("!")).some((pattern) => matchesGlob(path, pattern.slice(1)));
|
|
1584
|
+
}
|
|
1585
|
+
async function findPnpmWorkspaceRoot(packageRoot, root) {
|
|
1586
|
+
for (const directory of ancestors(packageRoot, root)) {
|
|
1587
|
+
const file = resolve(directory, "pnpm-workspace.yaml");
|
|
1588
|
+
if (!await isFile(file, root)) continue;
|
|
1589
|
+
const source = await readFile(file, "utf8");
|
|
1590
|
+
const packagePath = relative(directory, packageRoot).replaceAll("\\", "/") || ".";
|
|
1591
|
+
if (directory === packageRoot || isWorkspacePackage(packagePath, parsePnpmWorkspacePackages(source))) return {
|
|
1592
|
+
directory,
|
|
1593
|
+
file,
|
|
1594
|
+
source
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
async function addProjectFile(files, installRoot, path, scanRoot) {
|
|
1599
|
+
if (!await isFile(path, scanRoot)) return;
|
|
1600
|
+
const mode = (await stat(path)).mode & 511;
|
|
1601
|
+
files[relative(installRoot, path).replaceAll("\\", "/")] = {
|
|
1602
|
+
contents: (await readFile(path)).toString("base64"),
|
|
1603
|
+
encoding: "base64",
|
|
1604
|
+
...mode & 73 ? { mode } : {}
|
|
1605
|
+
};
|
|
1606
|
+
}
|
|
1607
|
+
function workspaceDependencyNames(manifest) {
|
|
1608
|
+
const sections = [
|
|
1609
|
+
manifest.dependencies,
|
|
1610
|
+
manifest.devDependencies,
|
|
1611
|
+
manifest.optionalDependencies,
|
|
1612
|
+
manifest.peerDependencies
|
|
1613
|
+
];
|
|
1614
|
+
return [...new Set(sections.flatMap((section) => Object.entries(section || {})).filter(([, specifier]) => specifier.startsWith("workspace:")).map(([name]) => name))];
|
|
1615
|
+
}
|
|
1616
|
+
async function addPnpmWorkspaceDependencies(files, workspaceRoot, scanRoot, patterns, selectedManifest) {
|
|
1617
|
+
const packages = /* @__PURE__ */ new Map();
|
|
1618
|
+
for (const pattern of patterns.filter((pattern) => !pattern.startsWith("!"))) for await (const match of glob(`${pattern}/package.json`, {
|
|
1619
|
+
cwd: workspaceRoot,
|
|
1620
|
+
exclude: ["**/node_modules/**", "**/.git/**"]
|
|
1621
|
+
})) {
|
|
1622
|
+
const manifestPath = resolve(workspaceRoot, match);
|
|
1623
|
+
if (!await isFile(manifestPath, scanRoot)) continue;
|
|
1624
|
+
if (!isWorkspacePackage(relative(workspaceRoot, dirname(manifestPath)).replaceAll("\\", "/") || ".", patterns)) continue;
|
|
1625
|
+
const manifest = parseManifest(await readFile(manifestPath, "utf8"), manifestPath);
|
|
1626
|
+
if (manifest.name) packages.set(manifest.name, {
|
|
1627
|
+
manifest,
|
|
1628
|
+
root: dirname(manifestPath)
|
|
1629
|
+
});
|
|
1630
|
+
}
|
|
1631
|
+
const pending = workspaceDependencyNames(selectedManifest);
|
|
1632
|
+
const included = /* @__PURE__ */ new Set();
|
|
1633
|
+
while (pending.length) {
|
|
1634
|
+
const name = pending.shift();
|
|
1635
|
+
if (included.has(name)) continue;
|
|
1636
|
+
const dependency = packages.get(name);
|
|
1637
|
+
if (!dependency) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0061({ message: `[vitehub] Sandbox package references missing pnpm workspace dependency "${name}".` });
|
|
1638
|
+
included.add(name);
|
|
1639
|
+
pending.push(...workspaceDependencyNames(dependency.manifest));
|
|
1640
|
+
for await (const match of glob("**/*", {
|
|
1641
|
+
cwd: dependency.root,
|
|
1642
|
+
exclude: projectFileExcludes
|
|
1643
|
+
})) await addProjectFile(files, workspaceRoot, resolve(dependency.root, match), scanRoot);
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
async function resolveSandboxTaskProject(definitionFile, scanRoot, options = {}) {
|
|
1647
|
+
const root = await realpath(resolve(scanRoot));
|
|
1648
|
+
const definition = await realpath(resolve(definitionFile));
|
|
1649
|
+
if (!isInside(root, definition)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0062({ message: `[vitehub] Sandbox Task Definition is outside its scan root: ${definitionFile}` });
|
|
1650
|
+
const packageRoot = await firstDirectoryWithFile(ancestors(dirname(definition), root), "package.json", root);
|
|
1651
|
+
if (!packageRoot) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0063({ message: `[vitehub] Sandbox Task Definition "${definitionFile}" requires a package.json between its directory and "${root}".` });
|
|
1652
|
+
const manifestPath = resolve(packageRoot, "package.json");
|
|
1653
|
+
const manifest = parseManifest(await readFile(manifestPath, "utf8"), manifestPath);
|
|
1654
|
+
const sandboxTaskOptions = options.readSandboxTaskOptions ? parseSandboxTaskProjectOptions(manifest, manifestPath) : void 0;
|
|
1655
|
+
const declaredManager = packageManagerFromField(manifest.packageManager);
|
|
1656
|
+
const declaredMajor = packageManagerMajor(manifest.packageManager);
|
|
1657
|
+
const workspace = declaredManager && declaredManager !== "pnpm" ? void 0 : await findPnpmWorkspaceRoot(packageRoot, root);
|
|
1658
|
+
const installRoot = workspace?.directory || packageRoot;
|
|
1659
|
+
const packageLock = await findLockfile([installRoot], root, workspace ? "pnpm" : declaredManager);
|
|
1660
|
+
const manager = declaredManager || packageLock?.manager || (workspace ? "pnpm" : "npm");
|
|
1661
|
+
const lock = packageLock?.manager === manager ? packageLock : void 0;
|
|
1662
|
+
const lockfileMajor = manager === "yarn" && lock && declaredMajor === void 0 ? (await readFile(lock.path, "utf8")).includes("__metadata:") ? 2 : 1 : void 0;
|
|
1663
|
+
const files = {};
|
|
1664
|
+
for await (const match of glob("**/*", {
|
|
1665
|
+
cwd: packageRoot,
|
|
1666
|
+
exclude: projectFileExcludes
|
|
1667
|
+
})) await addProjectFile(files, installRoot, resolve(packageRoot, match), root);
|
|
1668
|
+
if (installRoot !== packageRoot) await addProjectFile(files, installRoot, resolve(installRoot, "package.json"), root);
|
|
1669
|
+
if (workspace) {
|
|
1670
|
+
await addProjectFile(files, installRoot, workspace.file, root);
|
|
1671
|
+
await addPnpmWorkspaceDependencies(files, installRoot, root, parsePnpmWorkspacePackages(workspace.source), manifest);
|
|
1672
|
+
}
|
|
1673
|
+
const installManifestPath = resolve(installRoot, "package.json");
|
|
1674
|
+
const installManifest = installRoot === packageRoot ? manifest : await isFile(installManifestPath, root) ? parseManifest(await readFile(installManifestPath, "utf8"), installManifestPath) : void 0;
|
|
1675
|
+
for (const patchPath of pnpmPatchPaths(installManifest || {})) {
|
|
1676
|
+
if (!isInside(installRoot, resolve(installRoot, patchPath))) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0064({ message: `[vitehub] Sandbox pnpm patch must stay inside its install root: ${patchPath}` });
|
|
1677
|
+
await addProjectFile(files, installRoot, resolve(installRoot, patchPath), root);
|
|
1678
|
+
}
|
|
1679
|
+
if (workspace) for (const patchPath of parsePnpmWorkspacePatchPaths(workspace.source)) {
|
|
1680
|
+
if (!isInside(installRoot, resolve(installRoot, patchPath))) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0065({ message: `[vitehub] Sandbox pnpm patch must stay inside its install root: ${patchPath}` });
|
|
1681
|
+
await addProjectFile(files, installRoot, resolve(installRoot, patchPath), root);
|
|
1682
|
+
}
|
|
1683
|
+
if (lock) await addProjectFile(files, installRoot, lock.path, root);
|
|
1684
|
+
const packagePath = relative(installRoot, packageRoot).replaceAll("\\", "/") || ".";
|
|
1685
|
+
const identity = JSON.stringify({
|
|
1686
|
+
files,
|
|
1687
|
+
manager,
|
|
1688
|
+
packagePath
|
|
1689
|
+
});
|
|
1690
|
+
const project = {
|
|
1691
|
+
digest: createHash("sha256").update(identity).digest("hex"),
|
|
1692
|
+
files,
|
|
1693
|
+
install: {
|
|
1694
|
+
args: installArgs(manager, Boolean(lock), declaredManager === manager ? declaredMajor : lockfileMajor),
|
|
1695
|
+
command: manager,
|
|
1696
|
+
cwd: "."
|
|
1697
|
+
},
|
|
1698
|
+
...sandboxTaskOptions ? { options: sandboxTaskOptions } : {},
|
|
1699
|
+
packagePath
|
|
1700
|
+
};
|
|
1701
|
+
sandboxTaskProjectSourceFiles.set(project, Object.keys(files).map((path) => resolve(installRoot, path)));
|
|
1702
|
+
return project;
|
|
1703
|
+
}
|
|
1704
|
+
async function firstDirectoryWithFile(directories, file, root) {
|
|
1705
|
+
for (const directory of directories) if (await isFile(resolve(directory, file), root)) return directory;
|
|
1706
|
+
}
|
|
1707
|
+
async function findLockfile(directories, root, manager) {
|
|
1708
|
+
const candidates = manager ? lockfiles.filter((lock) => lock.manager === manager) : lockfiles;
|
|
1709
|
+
for (const directory of directories) for (const candidate of candidates) {
|
|
1710
|
+
const path = resolve(directory, candidate.file);
|
|
1711
|
+
if (await isFile(path, root)) return {
|
|
1712
|
+
directory,
|
|
1713
|
+
manager: candidate.manager,
|
|
1714
|
+
path
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
//#endregion
|
|
1719
|
+
//#region src/task/internal/package-entry.ts
|
|
1720
|
+
const runtimeExportConditions = /* @__PURE__ */ new Set([
|
|
1721
|
+
"default",
|
|
1722
|
+
"import",
|
|
1723
|
+
"module-sync",
|
|
1724
|
+
"node",
|
|
1725
|
+
"node-addons"
|
|
1726
|
+
]);
|
|
1727
|
+
function isExecutableTypeScriptModule(path) {
|
|
1728
|
+
return /\.(?:ts|mts)$/.test(path) && !/\.d\.(?:ts|mts)$/.test(path);
|
|
1729
|
+
}
|
|
1730
|
+
function executablePackageModulePath(path) {
|
|
1731
|
+
const suffixIndex = path.search(/[?#]/);
|
|
1732
|
+
const modulePath = suffixIndex === -1 ? path : path.slice(0, suffixIndex);
|
|
1733
|
+
const suffix = suffixIndex === -1 ? "" : path.slice(suffixIndex);
|
|
1734
|
+
return isExecutableTypeScriptModule(modulePath) ? `${modulePath}.mjs${suffix}` : path;
|
|
1735
|
+
}
|
|
1736
|
+
function projectFileSource(project, path) {
|
|
1737
|
+
const file = project.files[path];
|
|
1738
|
+
if (!file) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0015({ message: `[vitehub] Sandbox package project is missing required file: ${path}` });
|
|
1739
|
+
return Buffer.from(file.contents, file.encoding).toString();
|
|
1740
|
+
}
|
|
1741
|
+
function parseRuntimeManifest(project, path) {
|
|
1742
|
+
try {
|
|
1743
|
+
return JSON.parse(projectFileSource(project, path));
|
|
1744
|
+
} catch (error) {
|
|
1745
|
+
throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0016({
|
|
1746
|
+
message: `[vitehub] Sandbox package manifest is invalid JSON: ${path}`,
|
|
1747
|
+
cause: error
|
|
1748
|
+
});
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
function selectedPackageManifest(project) {
|
|
1752
|
+
const path = project.packagePath === "." ? "package.json" : `${project.packagePath}/package.json`;
|
|
1753
|
+
const manifest = parseRuntimeManifest(project, path);
|
|
1754
|
+
if (manifest.type !== "module") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0017({ message: `[vitehub] Sandbox package manifest "${path}" must set "type" to "module". Canonical Sandbox package entrypoints are ESM.` });
|
|
1755
|
+
return manifest;
|
|
1756
|
+
}
|
|
1757
|
+
function declaredWorkspaceDependencyNames(manifest) {
|
|
1758
|
+
return [...new Set([
|
|
1759
|
+
manifest.dependencies,
|
|
1760
|
+
manifest.devDependencies,
|
|
1761
|
+
manifest.optionalDependencies,
|
|
1762
|
+
manifest.peerDependencies
|
|
1763
|
+
].flatMap((section) => Object.entries(section || {})).filter(([, specifier]) => specifier.startsWith("workspace:")).map(([name]) => name))];
|
|
1764
|
+
}
|
|
1765
|
+
function runtimeExportTargets(value, patternMatch, allowPackageTarget = false) {
|
|
1766
|
+
if (typeof value === "string") {
|
|
1767
|
+
const target = patternMatch === void 0 ? value : value.replaceAll("*", patternMatch);
|
|
1768
|
+
return target.startsWith("./") || allowPackageTarget ? [target] : [];
|
|
1769
|
+
}
|
|
1770
|
+
if (Array.isArray(value)) {
|
|
1771
|
+
for (const target of value) {
|
|
1772
|
+
const targets = runtimeExportTargets(target, patternMatch, allowPackageTarget);
|
|
1773
|
+
if (targets.length) return targets;
|
|
1774
|
+
}
|
|
1775
|
+
return [];
|
|
1776
|
+
}
|
|
1777
|
+
if (!value || typeof value !== "object") return [];
|
|
1778
|
+
for (const [condition, target] of Object.entries(value)) if (runtimeExportConditions.has(condition)) {
|
|
1779
|
+
const targets = runtimeExportTargets(target, patternMatch, allowPackageTarget);
|
|
1780
|
+
if (targets.length) return targets;
|
|
1781
|
+
}
|
|
1782
|
+
return [];
|
|
1783
|
+
}
|
|
1784
|
+
function runtimeTargetsForPackageSpecifier(manifest, packageName, specifier) {
|
|
1785
|
+
if (manifest.exports !== void 0) {
|
|
1786
|
+
let selected = manifest.exports;
|
|
1787
|
+
let patternMatch;
|
|
1788
|
+
if (selected && typeof selected === "object" && !Array.isArray(selected)) {
|
|
1789
|
+
const entries = selected;
|
|
1790
|
+
if (Object.keys(entries).some((key) => key.startsWith("."))) {
|
|
1791
|
+
const subpath = specifier === packageName ? "." : `.${specifier.slice(packageName.length)}`;
|
|
1792
|
+
if (Object.hasOwn(entries, subpath)) selected = entries[subpath];
|
|
1793
|
+
else {
|
|
1794
|
+
const pattern = Object.keys(entries).filter((key) => {
|
|
1795
|
+
const star = key.indexOf("*");
|
|
1796
|
+
if (star === -1) return false;
|
|
1797
|
+
return subpath.startsWith(key.slice(0, star)) && subpath.endsWith(key.slice(star + 1));
|
|
1798
|
+
}).sort((left, right) => {
|
|
1799
|
+
const leftStar = left.indexOf("*");
|
|
1800
|
+
return right.indexOf("*") - leftStar || right.length - left.length;
|
|
1801
|
+
})[0];
|
|
1802
|
+
if (pattern) {
|
|
1803
|
+
const star = pattern.indexOf("*");
|
|
1804
|
+
patternMatch = subpath.slice(star, subpath.length - (pattern.length - star - 1));
|
|
1805
|
+
selected = entries[pattern];
|
|
1806
|
+
} else selected = void 0;
|
|
1807
|
+
}
|
|
1808
|
+
} else if (specifier !== packageName) selected = void 0;
|
|
1809
|
+
} else if (specifier !== packageName) selected = void 0;
|
|
1810
|
+
return runtimeExportTargets(selected, patternMatch);
|
|
1811
|
+
}
|
|
1812
|
+
if (specifier !== packageName) return [`.${specifier.slice(packageName.length)}`];
|
|
1813
|
+
return typeof manifest.main === "string" ? [manifest.main] : ["./index.js"];
|
|
1814
|
+
}
|
|
1815
|
+
function runtimeTargetsForPackageImport(manifest, specifier) {
|
|
1816
|
+
if (!manifest.imports || typeof manifest.imports !== "object" || Array.isArray(manifest.imports)) return [];
|
|
1817
|
+
const entries = manifest.imports;
|
|
1818
|
+
let selected = entries[specifier];
|
|
1819
|
+
let patternMatch;
|
|
1820
|
+
if (selected === void 0) {
|
|
1821
|
+
const pattern = Object.keys(entries).filter((key) => {
|
|
1822
|
+
const star = key.indexOf("*");
|
|
1823
|
+
if (star === -1) return false;
|
|
1824
|
+
return specifier.startsWith(key.slice(0, star)) && specifier.endsWith(key.slice(star + 1));
|
|
1825
|
+
}).sort((left, right) => {
|
|
1826
|
+
const leftStar = left.indexOf("*");
|
|
1827
|
+
return right.indexOf("*") - leftStar || right.length - left.length;
|
|
1828
|
+
})[0];
|
|
1829
|
+
if (!pattern) return [];
|
|
1830
|
+
const star = pattern.indexOf("*");
|
|
1831
|
+
patternMatch = specifier.slice(star, specifier.length - (pattern.length - star - 1));
|
|
1832
|
+
selected = entries[pattern];
|
|
1833
|
+
}
|
|
1834
|
+
return runtimeExportTargets(selected, patternMatch, true);
|
|
1835
|
+
}
|
|
1836
|
+
function isTypeScriptRuntimeTarget(path) {
|
|
1837
|
+
const target = path.replace(/[?#].*$/, "");
|
|
1838
|
+
return /\.[cm]?tsx?$/.test(target) && !/\.d\.[cm]?ts$/.test(target);
|
|
1839
|
+
}
|
|
1840
|
+
function validateWorkspaceJavaScriptGraph(project, packageName, manifest, manifestPath, targets) {
|
|
1841
|
+
const pending = targets.filter((target) => /\.(?:js|mjs)$/.test(target.replace(/[?#].*$/, ""))).map((target) => normalize$1(join$2(dirname$2(manifestPath), target.replace(/[?#].*$/, ""))));
|
|
1842
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1843
|
+
const runtimePackages = /* @__PURE__ */ new Set();
|
|
1844
|
+
while (pending.length) {
|
|
1845
|
+
const path = pending.shift();
|
|
1846
|
+
if (visited.has(path) || !Object.hasOwn(project.files, path)) continue;
|
|
1847
|
+
visited.add(path);
|
|
1848
|
+
const source = projectFileSource(project, path);
|
|
1849
|
+
for (const specifier of findRuntimeModuleSpecifiers(source, path)) {
|
|
1850
|
+
if (specifier.startsWith("#")) {
|
|
1851
|
+
for (const aliasTarget of runtimeTargetsForPackageImport(manifest, specifier)) {
|
|
1852
|
+
if (!/^\.\.?\//.test(aliasTarget)) {
|
|
1853
|
+
runtimePackages.add(aliasTarget);
|
|
1854
|
+
continue;
|
|
1855
|
+
}
|
|
1856
|
+
const target = normalize$1(join$2(dirname$2(manifestPath), aliasTarget.replace(/[?#].*$/, "")));
|
|
1857
|
+
if (isTypeScriptRuntimeTarget(target)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0018({ message: `[vitehub] Sandbox workspace dependency "${packageName}" exposes TypeScript runtime target "${aliasTarget}" through package import "${specifier}". Build dependencies to JavaScript before Sandbox execution.` });
|
|
1858
|
+
if (/\.(?:js|mjs)$/.test(target)) pending.push(target);
|
|
1859
|
+
}
|
|
1860
|
+
continue;
|
|
1861
|
+
}
|
|
1862
|
+
if (!/^\.\.?\//.test(specifier)) {
|
|
1863
|
+
if (!specifier.startsWith("node:")) runtimePackages.add(specifier);
|
|
1864
|
+
continue;
|
|
1865
|
+
}
|
|
1866
|
+
const target = normalize$1(join$2(dirname$2(path), specifier.replace(/[?#].*$/, "")));
|
|
1867
|
+
if (isTypeScriptRuntimeTarget(target)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0019({ message: `[vitehub] Sandbox workspace dependency "${packageName}" exposes TypeScript runtime target "${specifier}" from "${path}". Build dependencies to JavaScript before Sandbox execution.` });
|
|
1868
|
+
if (/\.(?:js|mjs)$/.test(target)) pending.push(target);
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
return runtimePackages;
|
|
1872
|
+
}
|
|
1873
|
+
function validateWorkspaceRuntimeExports(project, runtimePackages, declaredWorkspacePackages) {
|
|
1874
|
+
const pending = [...runtimePackages];
|
|
1875
|
+
if (!pending.length) return;
|
|
1876
|
+
const workspacePackages = new Set(declaredWorkspacePackages);
|
|
1877
|
+
if (!workspacePackages.size) return;
|
|
1878
|
+
const workspaceFile = project.files["pnpm-workspace.yaml"];
|
|
1879
|
+
if (!workspaceFile) return;
|
|
1880
|
+
const workspacePatterns = parsePnpmWorkspacePackages(Buffer.from(workspaceFile.contents, workspaceFile.encoding).toString());
|
|
1881
|
+
const manifests = /* @__PURE__ */ new Map();
|
|
1882
|
+
for (const path of Object.keys(project.files).filter((path) => path === "package.json" || path.endsWith("/package.json") && isWorkspacePackage(dirname$2(path), workspacePatterns))) {
|
|
1883
|
+
let manifest;
|
|
1884
|
+
try {
|
|
1885
|
+
const value = JSON.parse(projectFileSource(project, path));
|
|
1886
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) continue;
|
|
1887
|
+
manifest = value;
|
|
1888
|
+
} catch {
|
|
1889
|
+
continue;
|
|
1890
|
+
}
|
|
1891
|
+
if (typeof manifest.name === "string") manifests.set(manifest.name, {
|
|
1892
|
+
manifest,
|
|
1893
|
+
path
|
|
1894
|
+
});
|
|
1895
|
+
}
|
|
1896
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1897
|
+
while (pending.length) {
|
|
1898
|
+
const specifier = pending.shift();
|
|
1899
|
+
if (visited.has(specifier)) continue;
|
|
1900
|
+
visited.add(specifier);
|
|
1901
|
+
const packageName = barePackageName(specifier);
|
|
1902
|
+
if (!workspacePackages.has(packageName)) continue;
|
|
1903
|
+
const dependency = manifests.get(packageName);
|
|
1904
|
+
if (!dependency) continue;
|
|
1905
|
+
const targets = runtimeTargetsForPackageSpecifier(dependency.manifest, packageName, specifier);
|
|
1906
|
+
const target = targets.find(isTypeScriptRuntimeTarget);
|
|
1907
|
+
if (target) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0020({ message: `[vitehub] Sandbox workspace dependency "${packageName}" exposes TypeScript runtime target "${target}" in "${dependency.path}". Build dependencies to JavaScript before Sandbox execution.` });
|
|
1908
|
+
const runtimePackageEdges = validateWorkspaceJavaScriptGraph(project, packageName, dependency.manifest, dependency.path, targets);
|
|
1909
|
+
for (const name of declaredWorkspaceDependencyNames(dependency.manifest)) workspacePackages.add(name);
|
|
1910
|
+
pending.push(...runtimePackageEdges);
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
function isInsideSelectedPackage(project, path) {
|
|
1914
|
+
if (project.packagePath === ".") return path !== ".." && !path.startsWith("../");
|
|
1915
|
+
return path.startsWith(`${project.packagePath}/`);
|
|
1916
|
+
}
|
|
1917
|
+
function removeTypeOnlyModuleDeclarations(context) {
|
|
1918
|
+
const typescript = loadTypeScript();
|
|
1919
|
+
return (sourceFile) => context.factory.updateSourceFile(sourceFile, sourceFile.statements.filter((statement) => {
|
|
1920
|
+
if (typescript.isImportDeclaration(statement)) {
|
|
1921
|
+
const clause = statement.importClause;
|
|
1922
|
+
const bindings = clause?.namedBindings;
|
|
1923
|
+
return !(clause && !clause.name && bindings && typescript.isNamedImports(bindings) && bindings.elements.length > 0 && bindings.elements.every((element) => element.isTypeOnly));
|
|
1924
|
+
}
|
|
1925
|
+
if (typescript.isExportDeclaration(statement)) {
|
|
1926
|
+
const clause = statement.exportClause;
|
|
1927
|
+
return !(clause && typescript.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly));
|
|
1928
|
+
}
|
|
1929
|
+
return true;
|
|
1930
|
+
}));
|
|
1931
|
+
}
|
|
1932
|
+
function transpilePackageModule(source, path) {
|
|
1933
|
+
const typescript = loadTypeScript();
|
|
1934
|
+
const result = typescript.transpileModule(source, {
|
|
1935
|
+
compilerOptions: {
|
|
1936
|
+
module: typescript.ModuleKind.ESNext,
|
|
1937
|
+
target: typescript.ScriptTarget.ES2022,
|
|
1938
|
+
verbatimModuleSyntax: true
|
|
1939
|
+
},
|
|
1940
|
+
fileName: path,
|
|
1941
|
+
reportDiagnostics: true,
|
|
1942
|
+
transformers: { before: [removeTypeOnlyModuleDeclarations] }
|
|
1943
|
+
});
|
|
1944
|
+
const errors = result.diagnostics?.filter((diagnostic) => diagnostic.category === typescript.DiagnosticCategory.Error) || [];
|
|
1945
|
+
if (errors.length) {
|
|
1946
|
+
const details = errors.map((diagnostic) => typescript.flattenDiagnosticMessageText(diagnostic.messageText, "\n")).join("\n");
|
|
1947
|
+
throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0021({ message: `[vitehub] Sandbox package module "${path}" could not be transpiled:\n${details}` });
|
|
1948
|
+
}
|
|
1949
|
+
return result.outputText;
|
|
1950
|
+
}
|
|
1951
|
+
function barePackageName(specifier) {
|
|
1952
|
+
const [scopeOrName, name] = specifier.split("/");
|
|
1953
|
+
return scopeOrName.startsWith("@") && name ? `${scopeOrName}/${name}` : scopeOrName;
|
|
1954
|
+
}
|
|
1955
|
+
function isUnsupportedExternalModuleSpecifier(specifier) {
|
|
1956
|
+
return specifier.startsWith("/") || specifier.startsWith("\\") || /^[A-Za-z][A-Za-z\d+.-]*:/.test(specifier) && !specifier.startsWith("node:");
|
|
1957
|
+
}
|
|
1958
|
+
function throwCommonJSSyntax(path, commonJS) {
|
|
1959
|
+
const syntax = {
|
|
1960
|
+
"exports-assignment": "exports assignment",
|
|
1961
|
+
"exports-reference": "exports reference",
|
|
1962
|
+
"import-equals": "import = require()",
|
|
1963
|
+
"module-exports-assignment": "module.exports assignment",
|
|
1964
|
+
"module-reference": "module reference",
|
|
1965
|
+
require: "require()",
|
|
1966
|
+
"require-property": commonJS.specifier ? `require.${commonJS.specifier}` : "require property access"
|
|
1967
|
+
}[commonJS.syntax];
|
|
1968
|
+
const target = commonJS.specifier && commonJS.syntax !== "require-property" ? ` for "${commonJS.specifier}"` : "";
|
|
1969
|
+
throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0022({ message: `[vitehub] Sandbox package module "${path}" uses CommonJS ${syntax}${target}. Canonical Sandbox package entrypoints are ESM; use import or export syntax.` });
|
|
1970
|
+
}
|
|
1971
|
+
function validatePackageModuleSpecifiers(project, entry, packageName) {
|
|
1972
|
+
const pending = [entry];
|
|
1973
|
+
const runtimePackages = /* @__PURE__ */ new Set();
|
|
1974
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1975
|
+
while (pending.length) {
|
|
1976
|
+
const path = pending.shift();
|
|
1977
|
+
if (visited.has(path)) continue;
|
|
1978
|
+
visited.add(path);
|
|
1979
|
+
const source = projectFileSource(project, path);
|
|
1980
|
+
if (hasNonLiteralDynamicImport(source, path)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0023({ message: `[vitehub] Sandbox package module "${path}" uses a non-literal dynamic import. Canonical Sandbox package entrypoints require literal import() specifiers.` });
|
|
1981
|
+
const importEquals = findCommonJSImportEqualsSpecifiers(source, path)[0];
|
|
1982
|
+
if (importEquals) throwCommonJSSyntax(path, importEquals);
|
|
1983
|
+
const moduleSpecifiers = findRuntimeModuleSpecifiers(source, path);
|
|
1984
|
+
for (const specifier of moduleSpecifiers) {
|
|
1985
|
+
if (specifier.startsWith("#")) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0024({ message: `[vitehub] Sandbox package module "${path}" imports package alias "${specifier}". Use an explicit relative ESM import for local Sandbox source.` });
|
|
1986
|
+
if (packageName && (specifier === packageName || specifier.startsWith(`${packageName}/`))) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0025({ message: `[vitehub] Sandbox package module "${path}" self-imports "${specifier}". Use an explicit relative ESM import for local Sandbox source.` });
|
|
1987
|
+
if (isUnsupportedExternalModuleSpecifier(specifier)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0026({ message: `[vitehub] Sandbox package module "${path}" imports absolute or URL module "${specifier}". Use a relative module inside the package or a runtime-ready package dependency.` });
|
|
1988
|
+
if (!/^\.\.?\//.test(specifier) && !specifier.startsWith("node:")) runtimePackages.add(specifier);
|
|
1989
|
+
}
|
|
1990
|
+
for (const specifier of moduleSpecifiers.filter((specifier) => /^\.\.?\//.test(specifier))) {
|
|
1991
|
+
const target = normalize$1(join$2(dirname$2(path), specifier.replace(/[?#].*$/, "")));
|
|
1992
|
+
if (!isInsideSelectedPackage(project, target)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0027({ message: `[vitehub] Sandbox package module "${path}" imports "${specifier}" outside its package. Declare runtime-ready JavaScript as a package dependency instead.` });
|
|
1993
|
+
if (!Object.hasOwn(project.files, target)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0028({ message: `[vitehub] Sandbox package module "${path}" imports "${specifier}", which is not an executable package file. Use an explicit extension that resolves to a package file.` });
|
|
1994
|
+
if (/\.(?:cjs|cts)$/.test(target)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0029({ message: `[vitehub] Sandbox package module "${path}" imports CommonJS module "${specifier}". Canonical Sandbox package source must use ESM JavaScript or TypeScript modules.` });
|
|
1995
|
+
if (/\.[cm]?[jt]sx$/.test(target)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0030({ message: `[vitehub] Sandbox package module "${path}" imports JSX module "${specifier}". Canonical Sandbox package source does not compile JSX.` });
|
|
1996
|
+
if (/\.d\.[cm]?ts$/.test(target)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0031({ message: `[vitehub] Sandbox package module "${path}" imports declaration file "${specifier}" at runtime. Use an import type declaration instead.` });
|
|
1997
|
+
if (/\.(?:js|mjs|ts|mts)$/.test(target)) pending.push(target);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
return {
|
|
2001
|
+
modulePaths: visited,
|
|
2002
|
+
runtimePackages
|
|
2003
|
+
};
|
|
2004
|
+
}
|
|
2005
|
+
function prepareExecutablePackageProject(project, entry) {
|
|
2006
|
+
const manifest = selectedPackageManifest(project);
|
|
2007
|
+
const { modulePaths, runtimePackages } = validatePackageModuleSpecifiers(project, entry, typeof manifest.name === "string" ? manifest.name : void 0);
|
|
2008
|
+
validateWorkspaceRuntimeExports(project, runtimePackages, declaredWorkspaceDependencyNames(manifest));
|
|
2009
|
+
const generatedFiles = {};
|
|
2010
|
+
const executableSources = /* @__PURE__ */ new Map();
|
|
2011
|
+
const originalPaths = /* @__PURE__ */ new Map();
|
|
2012
|
+
const files = { ...project.files };
|
|
2013
|
+
for (const path of modulePaths) {
|
|
2014
|
+
const file = project.files[path];
|
|
2015
|
+
const source = Buffer.from(file.contents, file.encoding).toString();
|
|
2016
|
+
const rewritten = rewriteRuntimeRelativeModuleSpecifiers(source, path, executablePackageModulePath);
|
|
2017
|
+
if (isExecutableTypeScriptModule(path)) {
|
|
2018
|
+
const executablePath = executablePackageModulePath(path);
|
|
2019
|
+
if (Object.hasOwn(project.files, executablePath)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0032({ message: `[vitehub] Sandbox package module "${path}" conflicts with generated executable "${executablePath}". Rename the existing file.` });
|
|
2020
|
+
const executableSource = transpilePackageModule(rewritten, path);
|
|
2021
|
+
executableSources.set(executablePath, executableSource);
|
|
2022
|
+
originalPaths.set(executablePath, path);
|
|
2023
|
+
generatedFiles[executablePath] = {
|
|
2024
|
+
contents: Buffer.from(executableSource).toString("base64"),
|
|
2025
|
+
encoding: "base64"
|
|
2026
|
+
};
|
|
2027
|
+
} else {
|
|
2028
|
+
executableSources.set(path, rewritten);
|
|
2029
|
+
originalPaths.set(path, path);
|
|
2030
|
+
if (rewritten !== source) generatedFiles[path] = {
|
|
2031
|
+
...file,
|
|
2032
|
+
contents: Buffer.from(rewritten).toString("base64")
|
|
2033
|
+
};
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
const commonJS = findExecutableCommonJSModuleSpecifiers(executableSources)[0];
|
|
2037
|
+
if (commonJS) throwCommonJSSyntax(originalPaths.get(commonJS.path) || commonJS.path, commonJS);
|
|
2038
|
+
if (!Object.keys(generatedFiles).length) return {
|
|
2039
|
+
entry,
|
|
2040
|
+
project
|
|
2041
|
+
};
|
|
2042
|
+
Object.assign(files, generatedFiles);
|
|
2043
|
+
const digest = createHash("sha256").update(JSON.stringify({
|
|
2044
|
+
generatedFiles,
|
|
2045
|
+
project: project.digest
|
|
2046
|
+
})).digest("hex");
|
|
2047
|
+
return {
|
|
2048
|
+
entry: executablePackageModulePath(entry),
|
|
2049
|
+
project: {
|
|
2050
|
+
...project,
|
|
2051
|
+
digest,
|
|
2052
|
+
files
|
|
2053
|
+
}
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
//#endregion
|
|
2057
|
+
//#region src/task/bundle.ts
|
|
2058
|
+
const SHIM_NAMESPACE = "vitehub-sandbox-task-runtime-shim";
|
|
2059
|
+
const builtinModuleSet$1 = /* @__PURE__ */ new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
2060
|
+
function isRelativeFilesystemPath(path) {
|
|
2061
|
+
return !!path && !/^[/\\]/.test(path) && !/^[A-Za-z]:[/\\]/.test(path) && !/^[A-Za-z][A-Za-z\d+.-]*:/.test(path);
|
|
2062
|
+
}
|
|
2063
|
+
function findDefinitionProjectPath(file, project) {
|
|
2064
|
+
const normalizedFile = normalize(file.replaceAll("\\", "/"));
|
|
2065
|
+
return Object.keys(project.files).filter((path) => normalizedFile.endsWith(`/${normalize(path)}`)).sort((left, right) => right.length - left.length)[0];
|
|
2066
|
+
}
|
|
2067
|
+
function containsProjectPath(projectPaths, path) {
|
|
2068
|
+
if (path.startsWith("../")) return false;
|
|
2069
|
+
if (!path || path === ".") return projectPaths.size > 0;
|
|
2070
|
+
return projectPaths.has(path) || [...projectPaths].some((projectPath) => projectPath.startsWith(`${path}/`));
|
|
2071
|
+
}
|
|
2072
|
+
function hasProjectAssetReference(modules, file, project, source) {
|
|
2073
|
+
const projectPaths = new Set(Object.keys(project.files).map((path) => normalize(path)));
|
|
2074
|
+
const packagePath = project.packagePath === "." ? "" : normalize(project.packagePath);
|
|
2075
|
+
const definitionPath = findDefinitionProjectPath(file, project);
|
|
2076
|
+
return [[file, source], ...Object.entries(modules)].some(([modulePath, contents]) => {
|
|
2077
|
+
return findFilesystemPathReferences(contents, modulePath).some((reference) => {
|
|
2078
|
+
if (reference.path === void 0) return true;
|
|
2079
|
+
if (!isRelativeFilesystemPath(reference.path)) return false;
|
|
2080
|
+
const relativePath = normalize(reference.path.replaceAll("\\", "/"));
|
|
2081
|
+
if (reference.relativeTo === "working-directory") {
|
|
2082
|
+
const projectPath = normalize(join$1(packagePath, relativePath));
|
|
2083
|
+
return containsProjectPath(projectPaths, projectPath);
|
|
2084
|
+
}
|
|
2085
|
+
if (definitionPath) {
|
|
2086
|
+
const projectPath = normalize(join$1(dirname$1(definitionPath), relativePath));
|
|
2087
|
+
if (containsProjectPath(projectPaths, projectPath)) return true;
|
|
2088
|
+
}
|
|
2089
|
+
const suffix = relativePath.replace(/^(?:\.\.\/)+/, "").replace(/^\.\//, "");
|
|
2090
|
+
return !!suffix && [...projectPaths].some((path) => path === suffix || path.endsWith(`/${suffix}`) || path.startsWith(`${suffix}/`) || path.includes(`/${suffix}/`));
|
|
2091
|
+
});
|
|
2092
|
+
});
|
|
2093
|
+
}
|
|
2094
|
+
async function bundleSandboxTaskDefinition(source, file, options = {}) {
|
|
2095
|
+
if (options.includeProject === true && !options.project) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0001({ message: `[vitehub] Sandbox Task Definition ${file} declares project: true but no project was resolved.` });
|
|
2096
|
+
const project = options.includeProject === false ? void 0 : options.project;
|
|
2097
|
+
if (options.execution === "module" && project) {
|
|
2098
|
+
const executable = prepareExecutablePackageProject(project, `${project.packagePath === "." ? "" : `${project.packagePath}/`}${basename$1(file)}`);
|
|
2099
|
+
return {
|
|
2100
|
+
entry: executable.entry,
|
|
2101
|
+
execution: "module",
|
|
2102
|
+
modules: {},
|
|
2103
|
+
project: executable.project
|
|
2104
|
+
};
|
|
2105
|
+
}
|
|
2106
|
+
const { externalImports, hasRuntimeModuleResolution, ...bundle } = await bundleDiscoveredDefinitionModuleGraph({
|
|
2107
|
+
alias: options.alias,
|
|
2108
|
+
filename: file,
|
|
2109
|
+
packages: project ? "external" : "bundle",
|
|
2110
|
+
source,
|
|
2111
|
+
plugins: [{
|
|
2112
|
+
name: SHIM_NAMESPACE,
|
|
2113
|
+
setup(pluginBuild) {
|
|
2114
|
+
pluginBuild.onResolve({ filter: /^@vite-hub\/sandbox\/task(?:\/runtime\/public)?$/ }, () => ({
|
|
2115
|
+
path: "sandbox-task-runtime-shim",
|
|
2116
|
+
namespace: SHIM_NAMESPACE
|
|
2117
|
+
}));
|
|
2118
|
+
pluginBuild.onLoad({
|
|
2119
|
+
filter: /.*/,
|
|
2120
|
+
namespace: SHIM_NAMESPACE
|
|
2121
|
+
}, () => ({
|
|
2122
|
+
contents: [
|
|
2123
|
+
"function hasStandardValidator(value) {",
|
|
2124
|
+
" if (!value || typeof value !== \"object\") return false",
|
|
2125
|
+
" const standard = value[\"~standard\"]",
|
|
2126
|
+
" return Object.hasOwn(value, \"~standard\") && !!standard && typeof standard === \"object\" && typeof standard.validate === \"function\"",
|
|
2127
|
+
"}",
|
|
2128
|
+
"",
|
|
2129
|
+
"function isErrorWithHttpMetadata(error) {",
|
|
2130
|
+
" if (!(error instanceof Error)) return false",
|
|
2131
|
+
" return typeof error.status === \"number\" || typeof error.statusCode === \"number\" || typeof error.statusText === \"string\" || typeof error.statusMessage === \"string\"",
|
|
2132
|
+
"}",
|
|
2133
|
+
"",
|
|
2134
|
+
"function createValidationError(cause) {",
|
|
2135
|
+
" if (isErrorWithHttpMetadata(cause)) return cause",
|
|
2136
|
+
" const message = cause instanceof Error",
|
|
2137
|
+
" ? cause.message || \"Validation failed\"",
|
|
2138
|
+
" : cause && typeof cause === \"object\" && typeof cause.message === \"string\" && cause.message",
|
|
2139
|
+
" ? cause.message",
|
|
2140
|
+
" : \"Validation failed\"",
|
|
2141
|
+
" const error = new Error(message, { cause })",
|
|
2142
|
+
" if (cause && typeof cause === \"object\")",
|
|
2143
|
+
" Object.assign(error, cause)",
|
|
2144
|
+
" error.code = \"SANDBOX_TASK_VALIDATION_ERROR\"",
|
|
2145
|
+
" return error",
|
|
2146
|
+
"}",
|
|
2147
|
+
"",
|
|
2148
|
+
"export async function readValidatedPayload(payload, validate) {",
|
|
2149
|
+
" if (hasStandardValidator(validate)) {",
|
|
2150
|
+
" let result",
|
|
2151
|
+
" try {",
|
|
2152
|
+
" result = await validate[\"~standard\"].validate(payload)",
|
|
2153
|
+
" }",
|
|
2154
|
+
" catch (error) {",
|
|
2155
|
+
" throw createValidationError(error)",
|
|
2156
|
+
" }",
|
|
2157
|
+
" if (result.issues !== undefined)",
|
|
2158
|
+
" throw createValidationError({ message: \"Validation failed\", issues: result.issues })",
|
|
2159
|
+
" return result.value",
|
|
2160
|
+
" }",
|
|
2161
|
+
" try {",
|
|
2162
|
+
" const result = await validate(payload)",
|
|
2163
|
+
" if (result === false)",
|
|
2164
|
+
" throw createValidationError({ message: \"Validation failed\" })",
|
|
2165
|
+
" return result === true || result == null ? payload : result",
|
|
2166
|
+
" }",
|
|
2167
|
+
" catch (error) {",
|
|
2168
|
+
" throw createValidationError(error)",
|
|
2169
|
+
" }",
|
|
2170
|
+
"}",
|
|
2171
|
+
"",
|
|
2172
|
+
"export function defineSandboxTask(input) {",
|
|
2173
|
+
" const { project: _project, run, ...options } = input",
|
|
2174
|
+
" return { run, options: Object.keys(options).length ? options : undefined }",
|
|
2175
|
+
"}"
|
|
2176
|
+
].join("\n"),
|
|
2177
|
+
loader: "js"
|
|
2178
|
+
}));
|
|
2179
|
+
}
|
|
2180
|
+
}]
|
|
2181
|
+
});
|
|
2182
|
+
const hasUnbundledRuntimeDependency = hasRuntimeModuleResolution || externalImports.some((specifier) => !builtinModuleSet$1.has(specifier));
|
|
2183
|
+
if (options.includeProject === false && hasUnbundledRuntimeDependency) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0002({ message: `[vitehub] Sandbox Task Definition ${file} declares project: false but has a runtime dependency that could not be bundled.` });
|
|
2184
|
+
const requiresProject = options.includeProject === true || options.includeProject !== false && (hasUnbundledRuntimeDependency || !!project && hasProjectAssetReference(bundle.modules, file, project, source));
|
|
2185
|
+
if (!project || !requiresProject) return {
|
|
2186
|
+
...bundle,
|
|
2187
|
+
...options.execution ? { execution: options.execution } : {}
|
|
2188
|
+
};
|
|
2189
|
+
const prefix = project.packagePath === "." ? ".vitehub-sandbox-task" : `${project.packagePath}/.vitehub-sandbox-task`;
|
|
2190
|
+
const modules = {
|
|
2191
|
+
[`${prefix}/package.json`]: JSON.stringify({
|
|
2192
|
+
private: true,
|
|
2193
|
+
type: "module"
|
|
2194
|
+
}),
|
|
2195
|
+
...Object.fromEntries(Object.entries(bundle.modules).map(([path, contents]) => [`${prefix}/${path}`, contents]))
|
|
2196
|
+
};
|
|
2197
|
+
const digest = createHash("sha256").update(JSON.stringify({
|
|
2198
|
+
modules,
|
|
2199
|
+
packagePath: project.packagePath,
|
|
2200
|
+
project: project.digest
|
|
2201
|
+
})).digest("hex");
|
|
2202
|
+
return {
|
|
2203
|
+
entry: `${prefix}/${bundle.entry}`,
|
|
2204
|
+
...options.execution ? { execution: options.execution } : {},
|
|
2205
|
+
modules,
|
|
2206
|
+
project: {
|
|
2207
|
+
...project,
|
|
2208
|
+
digest
|
|
2209
|
+
}
|
|
2210
|
+
};
|
|
2211
|
+
}
|
|
2212
|
+
//#endregion
|
|
2213
|
+
//#region src/task/definition-options.ts
|
|
2214
|
+
const sandboxTaskDefinitionSyntax = "`defineSandboxTask({ run, ...options })`";
|
|
2215
|
+
function readStaticValue(node) {
|
|
2216
|
+
const ts = loadTypeScript();
|
|
2217
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
|
|
2218
|
+
if (ts.isNumericLiteral(node)) return Number(node.text);
|
|
2219
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
|
|
2220
|
+
if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
|
|
2221
|
+
if (node.kind === ts.SyntaxKind.NullKeyword) return null;
|
|
2222
|
+
if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(node.operand)) return -Number(node.operand.text);
|
|
2223
|
+
if (ts.isParenthesizedExpression(node)) return readStaticValue(node.expression);
|
|
2224
|
+
if (ts.isArrayLiteralExpression(node)) return node.elements.map((element) => {
|
|
2225
|
+
if (!ts.isExpression(element)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0001({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} options arrays must use static values.` });
|
|
2226
|
+
return readStaticValue(element);
|
|
2227
|
+
});
|
|
2228
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
2229
|
+
const value = {};
|
|
2230
|
+
for (const property of node.properties) {
|
|
2231
|
+
if (!ts.isPropertyAssignment(property)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0002({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} options must use plain object literals.` });
|
|
2232
|
+
const key = ts.isIdentifier(property.name) ? property.name.text : ts.isStringLiteral(property.name) ? property.name.text : void 0;
|
|
2233
|
+
if (!key) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0003({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} options only support identifier or string-literal keys.` });
|
|
2234
|
+
Object.defineProperty(value, key, {
|
|
2235
|
+
configurable: true,
|
|
2236
|
+
enumerable: true,
|
|
2237
|
+
value: readStaticValue(property.initializer),
|
|
2238
|
+
writable: true
|
|
2239
|
+
});
|
|
2240
|
+
}
|
|
2241
|
+
return value;
|
|
2242
|
+
}
|
|
2243
|
+
throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0004({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} options must use static JSON-serializable values.` });
|
|
2244
|
+
}
|
|
2245
|
+
function readSandboxTaskDefinitionFactories(sourceFile) {
|
|
2246
|
+
const ts = loadTypeScript();
|
|
2247
|
+
const names = /* @__PURE__ */ new Set(["defineSandboxTask"]);
|
|
2248
|
+
const namespaces = /* @__PURE__ */ new Set();
|
|
2249
|
+
for (const statement of sourceFile.statements) {
|
|
2250
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== "@vite-hub/sandbox/task" || !statement.importClause?.namedBindings) continue;
|
|
2251
|
+
const bindings = statement.importClause.namedBindings;
|
|
2252
|
+
if (ts.isNamespaceImport(bindings)) {
|
|
2253
|
+
namespaces.add(bindings.name.text);
|
|
2254
|
+
continue;
|
|
2255
|
+
}
|
|
2256
|
+
for (const element of bindings.elements) if ((element.propertyName ?? element.name).text === "defineSandboxTask") names.add(element.name.text);
|
|
2257
|
+
}
|
|
2258
|
+
return {
|
|
2259
|
+
names,
|
|
2260
|
+
namespaces
|
|
2261
|
+
};
|
|
2262
|
+
}
|
|
2263
|
+
function readDefinitionObject(sourceFile) {
|
|
2264
|
+
const ts = loadTypeScript();
|
|
2265
|
+
const factories = readSandboxTaskDefinitionFactories(sourceFile);
|
|
2266
|
+
const immutableBindings = /* @__PURE__ */ new Map();
|
|
2267
|
+
for (const statement of sourceFile.statements) {
|
|
2268
|
+
if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;
|
|
2269
|
+
for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.initializer) immutableBindings.set(declaration.name.text, declaration.initializer);
|
|
2270
|
+
}
|
|
2271
|
+
for (const statement of sourceFile.statements) {
|
|
2272
|
+
let expression;
|
|
2273
|
+
if (ts.isExportAssignment(statement)) expression = statement.expression;
|
|
2274
|
+
else if (ts.isExportDeclaration(statement) && !statement.moduleSpecifier && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
|
|
2275
|
+
const defaultExport = statement.exportClause.elements.find((element) => element.name.text === "default");
|
|
2276
|
+
const binding = defaultExport && (defaultExport.propertyName ?? defaultExport.name);
|
|
2277
|
+
if (binding) expression = immutableBindings.get(binding.text);
|
|
2278
|
+
}
|
|
2279
|
+
if (!expression) continue;
|
|
2280
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2281
|
+
while (expression) {
|
|
2282
|
+
if (ts.isParenthesizedExpression(expression)) {
|
|
2283
|
+
expression = expression.expression;
|
|
2284
|
+
continue;
|
|
2285
|
+
}
|
|
2286
|
+
if (ts.isIdentifier(expression) && !seen.has(expression.text)) {
|
|
2287
|
+
seen.add(expression.text);
|
|
2288
|
+
expression = immutableBindings.get(expression.text);
|
|
2289
|
+
continue;
|
|
2290
|
+
}
|
|
2291
|
+
break;
|
|
2292
|
+
}
|
|
2293
|
+
if (!expression) continue;
|
|
2294
|
+
if (!ts.isCallExpression(expression)) continue;
|
|
2295
|
+
const factory = expression.expression;
|
|
2296
|
+
if (!(ts.isIdentifier(factory) ? factories.names.has(factory.text) : ts.isPropertyAccessExpression(factory) && ts.isIdentifier(factory.expression) && factories.namespaces.has(factory.expression.text) && factory.name.text === "defineSandboxTask")) continue;
|
|
2297
|
+
if (expression.arguments.length !== 1 || !ts.isObjectLiteralExpression(expression.arguments[0])) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0005({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} requires one direct object literal.` });
|
|
2298
|
+
return expression.arguments[0];
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
function propertyName(property) {
|
|
2302
|
+
const ts = loadTypeScript();
|
|
2303
|
+
if (!("name" in property) || !property.name) return void 0;
|
|
2304
|
+
return ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : void 0;
|
|
2305
|
+
}
|
|
2306
|
+
async function extractSandboxTaskDefinitionMetadata(file) {
|
|
2307
|
+
const source = await readFile(file, "utf8");
|
|
2308
|
+
const ts = loadTypeScript();
|
|
2309
|
+
const input = readDefinitionObject(ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS));
|
|
2310
|
+
if (!input) return void 0;
|
|
2311
|
+
const options = {};
|
|
2312
|
+
let project;
|
|
2313
|
+
let hasRun = false;
|
|
2314
|
+
for (const property of input.properties) {
|
|
2315
|
+
const key = propertyName(property);
|
|
2316
|
+
if (key === "run" && ts.isShorthandPropertyAssignment(property)) {
|
|
2317
|
+
hasRun = true;
|
|
2318
|
+
continue;
|
|
2319
|
+
}
|
|
2320
|
+
if (!key || !ts.isPropertyAssignment(property) && !ts.isMethodDeclaration(property)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0006({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} requires explicit object properties.` });
|
|
2321
|
+
if (key === "run") {
|
|
2322
|
+
hasRun = true;
|
|
2323
|
+
continue;
|
|
2324
|
+
}
|
|
2325
|
+
if (!ts.isPropertyAssignment(property)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0007({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} options must use static values.` });
|
|
2326
|
+
const value = readStaticValue(property.initializer);
|
|
2327
|
+
if (key === "project") {
|
|
2328
|
+
if (value !== true && value !== false) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0008({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} project must be a boolean.` });
|
|
2329
|
+
project = value;
|
|
2330
|
+
} else Object.defineProperty(options, key, {
|
|
2331
|
+
configurable: true,
|
|
2332
|
+
enumerable: true,
|
|
2333
|
+
value,
|
|
2334
|
+
writable: true
|
|
2335
|
+
});
|
|
2336
|
+
}
|
|
2337
|
+
if (!hasRun) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_C0009({ message: `[vitehub] ${sandboxTaskDefinitionSyntax} requires a \`run\` handler.` });
|
|
2338
|
+
const runtimeOptions = Object.keys(options).length ? options : void 0;
|
|
2339
|
+
return runtimeOptions || project !== void 0 ? {
|
|
2340
|
+
...runtimeOptions ? { options: runtimeOptions } : {},
|
|
2341
|
+
...project !== void 0 ? { project } : {}
|
|
2342
|
+
} : void 0;
|
|
2343
|
+
}
|
|
2344
|
+
//#endregion
|
|
2345
|
+
//#region src/task/type-template.ts
|
|
2346
|
+
function createDefinitionContract(definition) {
|
|
2347
|
+
const module = `typeof import(${JSON.stringify(definition.handler)})`;
|
|
2348
|
+
if (definition.kind === "definition") return `{ payload: Parameters<${module}['default']['run']>[0], result: Awaited<ReturnType<${module}['default']['run']>> }`;
|
|
2349
|
+
return `SandboxTaskPackageContract<${module}['default']>`;
|
|
2350
|
+
}
|
|
2351
|
+
function createSandboxTaskTypeTemplateContents(definitions) {
|
|
2352
|
+
return [
|
|
2353
|
+
`declare module '#vitehub-sandbox-task-registry' {`,
|
|
2354
|
+
` type SandboxTaskPackageContract<TDefault extends (...args: any[]) => any> = TDefault extends (...args: infer TArgs) => infer TResult`,
|
|
2355
|
+
` ? { payload: TArgs extends [] ? unknown : TArgs[0], result: Awaited<TResult> }`,
|
|
2356
|
+
` : never`,
|
|
2357
|
+
` export interface SandboxTaskDefinitionModules {`,
|
|
2358
|
+
...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: ${createDefinitionContract(definition)},`),
|
|
2359
|
+
` }`,
|
|
2360
|
+
` const sandboxTaskRegistry: {`,
|
|
2361
|
+
...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: () => Promise<{ default?: { bundle: import('@vite-hub/sandbox/task').SandboxTaskDefinitionBundle, options?: import('@vite-hub/sandbox/task').SandboxTaskDefinitionOptions } }>,`),
|
|
2362
|
+
` }`,
|
|
2363
|
+
` export default sandboxTaskRegistry`,
|
|
2364
|
+
`}`,
|
|
2365
|
+
``
|
|
2366
|
+
].join("\n");
|
|
2367
|
+
}
|
|
2368
|
+
//#endregion
|
|
2369
|
+
//#region src/task/feature.ts
|
|
2370
|
+
const sandboxTaskRuntimeStateSpecifier = "@vite-hub/sandbox/task/runtime/state";
|
|
2371
|
+
const sandboxTaskRuntimeSpecifier = "@vite-hub/sandbox/_internal/task/runtime";
|
|
2372
|
+
const sandboxTaskRuntimeProviderSpecifiers = {
|
|
2373
|
+
cloudflare: `${sandboxTaskRuntimeSpecifier}/providers/cloudflare`,
|
|
2374
|
+
vercel: `${sandboxTaskRuntimeSpecifier}/providers/vercel`
|
|
2375
|
+
};
|
|
2376
|
+
const sandboxTaskRuntimeDependencyByProvider = {
|
|
2377
|
+
cloudflare: "@cloudflare/sandbox",
|
|
2378
|
+
vercel: "@vercel/sandbox"
|
|
2379
|
+
};
|
|
2380
|
+
function resolveSandboxTaskProviderLoaderTarget(provider, deps) {
|
|
2381
|
+
if (provider) return provider;
|
|
2382
|
+
const hasCloudflareSandbox = Boolean(deps["@cloudflare/sandbox"]);
|
|
2383
|
+
if (hasCloudflareSandbox === Boolean(deps["@vercel/sandbox"])) return void 0;
|
|
2384
|
+
return hasCloudflareSandbox ? "cloudflare" : "vercel";
|
|
2385
|
+
}
|
|
2386
|
+
const sandboxTaskProviderLoaderSpecifiers = [
|
|
2387
|
+
"vitehub-sandbox-task-provider-loader",
|
|
2388
|
+
"@vite-hub/sandbox/task/runtime/provider-loader",
|
|
2389
|
+
"virtual:vitehub-sandbox-task-provider-loader",
|
|
2390
|
+
"#vitehub-sandbox-task-provider-loader"
|
|
2391
|
+
];
|
|
2392
|
+
function createSandboxTaskProviderLoaderAliases(defaultProviderName) {
|
|
2393
|
+
const keys = sandboxTaskProviderLoaderSpecifiers;
|
|
2394
|
+
if (defaultProviderName) return keys.map((key) => ({
|
|
2395
|
+
key,
|
|
2396
|
+
artifactKey: "sandbox-task-provider-loader"
|
|
2397
|
+
}));
|
|
2398
|
+
const providerLoaderPath = resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox/task", "./runtime/provider-loader", "runtime/provider-loader.js");
|
|
2399
|
+
return keys.map((key) => ({
|
|
2400
|
+
key,
|
|
2401
|
+
value: providerLoaderPath
|
|
2402
|
+
}));
|
|
2403
|
+
}
|
|
2404
|
+
function createSandboxTaskManifest(aliasPath, typeTemplate) {
|
|
2405
|
+
return {
|
|
2406
|
+
alias: "@vite-hub/sandbox/task",
|
|
2407
|
+
aliasPath,
|
|
2408
|
+
imports: [
|
|
2409
|
+
{
|
|
2410
|
+
name: "defineSandboxTask",
|
|
2411
|
+
from: "@vite-hub/sandbox/task",
|
|
2412
|
+
meta: { description: "Define a free-form sandbox resource." }
|
|
2413
|
+
},
|
|
2414
|
+
{
|
|
2415
|
+
name: "readValidatedPayload",
|
|
2416
|
+
as: "readValidatedSandboxTaskPayload",
|
|
2417
|
+
from: "@vite-hub/sandbox/task",
|
|
2418
|
+
meta: { description: "Validate sandbox payload input before execution." }
|
|
2419
|
+
},
|
|
2420
|
+
{
|
|
2421
|
+
name: "runSandboxTask",
|
|
2422
|
+
from: "@vite-hub/sandbox/task",
|
|
2423
|
+
meta: { description: "Run a named sandbox definition." }
|
|
2424
|
+
},
|
|
2425
|
+
{
|
|
2426
|
+
name: "SandboxTaskDefinition",
|
|
2427
|
+
as: "SandboxTaskDefinition",
|
|
2428
|
+
from: "@vite-hub/sandbox/task",
|
|
2429
|
+
type: true
|
|
2430
|
+
},
|
|
2431
|
+
{
|
|
2432
|
+
name: "SandboxTaskRunResult",
|
|
2433
|
+
as: "SandboxTaskRunResult",
|
|
2434
|
+
from: "@vite-hub/sandbox/task",
|
|
2435
|
+
type: true
|
|
2436
|
+
}
|
|
2437
|
+
],
|
|
2438
|
+
typeTemplate: {
|
|
2439
|
+
filename: "runtime/sandbox-task.d.ts",
|
|
2440
|
+
contents: typeTemplate
|
|
2441
|
+
}
|
|
2442
|
+
};
|
|
2443
|
+
}
|
|
2444
|
+
function normalizeSandboxTaskDefinitionOptions(name, options) {
|
|
2445
|
+
if (!options) return void 0;
|
|
2446
|
+
try {
|
|
2447
|
+
return JSON.parse(JSON.stringify(options));
|
|
2448
|
+
} catch (error) {
|
|
2449
|
+
throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0011({
|
|
2450
|
+
message: `[vitehub] Sandbox Task Definition "${name}" options must be JSON-serializable.`,
|
|
2451
|
+
cause: error
|
|
2452
|
+
});
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
async function loadSandboxTaskDefinitionMetadata(definitions, rootDir) {
|
|
2456
|
+
return await Promise.all(definitions.map(async (definition) => {
|
|
2457
|
+
const sourceMetadata = definition.kind === "package-entry" ? void 0 : await extractSandboxTaskDefinitionMetadata(definition.handler);
|
|
2458
|
+
const project = sourceMetadata?.project === false ? void 0 : await resolveSandboxTaskProject(definition.handler, rootDir, { readSandboxTaskOptions: definition.kind === "package-entry" });
|
|
2459
|
+
return {
|
|
2460
|
+
kind: definition.kind,
|
|
2461
|
+
name: definition.name,
|
|
2462
|
+
options: definition.kind === "package-entry" ? project?.options : normalizeSandboxTaskDefinitionOptions(definition.name, sourceMetadata?.options),
|
|
2463
|
+
project,
|
|
2464
|
+
projectMode: sourceMetadata?.project
|
|
2465
|
+
};
|
|
2466
|
+
}));
|
|
2467
|
+
}
|
|
2468
|
+
function createSandboxTaskRegistryContents(file, definitions, scope) {
|
|
2469
|
+
const scopeSpecifier = createFileImportSpecifier(scope);
|
|
2470
|
+
return [
|
|
2471
|
+
`import { createGeneratedSandboxTaskRuntimeRegistry } from ${JSON.stringify(sandboxTaskRuntimeStateSpecifier)}`,
|
|
2472
|
+
"",
|
|
2473
|
+
`const registry = createGeneratedSandboxTaskRuntimeRegistry(${JSON.stringify(scopeSpecifier)}, {`,
|
|
2474
|
+
...definitions.map((definition) => [
|
|
2475
|
+
` [${JSON.stringify(definition.name)}]: {`,
|
|
2476
|
+
` load: async () => import(${JSON.stringify(createImportPath(file, definition.definitionModulePath))}),`,
|
|
2477
|
+
` stablePath: ${JSON.stringify(createFileImportSpecifier(definition.stableDefinitionModulePath))},`,
|
|
2478
|
+
" },"
|
|
2479
|
+
].join("\n")),
|
|
2480
|
+
"})",
|
|
2481
|
+
"export default registry",
|
|
2482
|
+
""
|
|
2483
|
+
].join("\n");
|
|
2484
|
+
}
|
|
2485
|
+
function createSandboxTaskProviderLoaderContents(provider) {
|
|
2486
|
+
const providerExport = sandboxTaskProviderRuntimeExport(provider);
|
|
2487
|
+
const providerLoaderPath = sandboxTaskRuntimeProviderSpecifiers[provider];
|
|
2488
|
+
return [
|
|
2489
|
+
`import { ${providerExport} as resolveTaskSandbox } from ${JSON.stringify(providerLoaderPath)}`,
|
|
2490
|
+
`import { unsupportedHostedSandboxTaskProviderError } from ${JSON.stringify(sandboxTaskRuntimeSpecifier)}`,
|
|
2491
|
+
"",
|
|
2492
|
+
"export async function loadSandboxTaskRuntimeProvider(selectedProvider) {",
|
|
2493
|
+
` if (selectedProvider !== ${JSON.stringify(provider)})`,
|
|
2494
|
+
" throw unsupportedHostedSandboxTaskProviderError(selectedProvider)",
|
|
2495
|
+
" return {",
|
|
2496
|
+
" resolveTaskSandbox,",
|
|
2497
|
+
" }",
|
|
2498
|
+
"}",
|
|
2499
|
+
""
|
|
2500
|
+
].join("\n");
|
|
2501
|
+
}
|
|
2502
|
+
function sandboxTaskProviderRuntimeExport(provider) {
|
|
2503
|
+
return provider === "cloudflare" ? "resolveCloudflareTaskSandbox" : "resolveVercelTaskSandbox";
|
|
2504
|
+
}
|
|
2505
|
+
function resolveSandboxTaskFeatureConfig(sandboxTaskConfig, hosting) {
|
|
2506
|
+
if (getSandboxTaskFeatureProvider(sandboxTaskConfig)?.provider) return { ...sandboxTaskConfig };
|
|
2507
|
+
const config = { ...sandboxTaskConfig };
|
|
2508
|
+
const hostedProvider = getSupportedHostingProvider(hosting, ["cloudflare", "vercel"]);
|
|
2509
|
+
if (hostedProvider) return {
|
|
2510
|
+
...config,
|
|
2511
|
+
provider: hostedProvider
|
|
2512
|
+
};
|
|
2513
|
+
const unsupportedHostedProvider = deploymentPresetFromNitro(hosting);
|
|
2514
|
+
if (unsupportedHostedProvider) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0012({ message: "[vitehub] Sandbox hosting inference does not support " + unsupportedHostedProvider + ". An explicit `sandbox.provider` is required." });
|
|
2515
|
+
return config;
|
|
2516
|
+
}
|
|
2517
|
+
async function createSandboxTaskFeaturePlan(sandboxTaskConfig, definitions, paths, deps, hosting, discoveredDefinitionOptions = {}) {
|
|
2518
|
+
const resolvedConfig = definitions.length > 0 ? resolveSandboxTaskFeatureConfig(sandboxTaskConfig, hosting) : { ...sandboxTaskConfig };
|
|
2519
|
+
const sandboxTaskDefinitions = definitions.map((definition) => ({
|
|
2520
|
+
...definition,
|
|
2521
|
+
definitionArtifactKey: `sandbox-task-definition:${definition.name}`,
|
|
2522
|
+
definitionFilename: `runtime/sandbox-task-definitions/${toTemplateSafeName(definition.name)}.mjs`
|
|
2523
|
+
}));
|
|
2524
|
+
const definitionFileByName = /* @__PURE__ */ new Map();
|
|
2525
|
+
for (const definition of sandboxTaskDefinitions) {
|
|
2526
|
+
const existing = definitionFileByName.get(definition.definitionFilename);
|
|
2527
|
+
if (existing) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0013({ message: `[vitehub] Sandbox Task Definitions "${existing}" and "${definition.name}" generate the same artifact path "${definition.definitionFilename}".` });
|
|
2528
|
+
definitionFileByName.set(definition.definitionFilename, definition.name);
|
|
2529
|
+
}
|
|
2530
|
+
const definitionMetadata = await loadSandboxTaskDefinitionMetadata(definitions, discoveredDefinitionOptions.rootDir || process.cwd());
|
|
2531
|
+
const metadataByName = new Map(definitionMetadata.map((definition) => [definition.name, definition]));
|
|
2532
|
+
const manifest = createSandboxTaskManifest(paths.aliasPath, createSandboxTaskTypeTemplateContents(definitions.map((definition) => {
|
|
2533
|
+
return {
|
|
2534
|
+
handler: definition.handler,
|
|
2535
|
+
kind: definition.kind,
|
|
2536
|
+
name: definition.name
|
|
2537
|
+
};
|
|
2538
|
+
})));
|
|
2539
|
+
const { bundleAlias, featureImports = manifest.imports, ...definitionCompilerOptions } = discoveredDefinitionOptions;
|
|
2540
|
+
const definitionCompiler = await createDiscoveredDefinitionCompiler({
|
|
2541
|
+
...definitionCompilerOptions,
|
|
2542
|
+
featureImports
|
|
2543
|
+
});
|
|
2544
|
+
const defaultProvider = getSandboxTaskFeatureProvider(resolvedConfig);
|
|
2545
|
+
const defaultProviderName = defaultProvider?.provider;
|
|
2546
|
+
const sandboxTaskArtifacts = sandboxTaskDefinitions.map((definition) => ({
|
|
2547
|
+
key: definition.definitionArtifactKey,
|
|
2548
|
+
filename: definition.definitionFilename,
|
|
2549
|
+
async getContents() {
|
|
2550
|
+
const source = await definitionCompiler.readSource(definition._meta.sourcePath);
|
|
2551
|
+
const metadata = metadataByName.get(definition.name);
|
|
2552
|
+
const bundle = await bundleSandboxTaskDefinition(source, definition._meta.sourcePath, {
|
|
2553
|
+
alias: bundleAlias,
|
|
2554
|
+
execution: metadata?.kind === "package-entry" ? "module" : "definition",
|
|
2555
|
+
includeProject: metadata?.projectMode,
|
|
2556
|
+
project: metadata?.project
|
|
2557
|
+
});
|
|
2558
|
+
return `export default ${JSON.stringify({
|
|
2559
|
+
bundle,
|
|
2560
|
+
options: metadata?.options
|
|
2561
|
+
})}\n`;
|
|
2562
|
+
}
|
|
2563
|
+
}));
|
|
2564
|
+
const providerLoaderTarget = resolveSandboxTaskProviderLoaderTarget(defaultProviderName, deps);
|
|
2565
|
+
const cloudflareOptions = defaultProvider?.provider === "cloudflare" ? {
|
|
2566
|
+
binding: typeof defaultProvider.binding === "string" ? defaultProvider.binding : defaultCloudflareSandboxBinding,
|
|
2567
|
+
className: typeof defaultProvider.className === "string" ? defaultProvider.className : defaultCloudflareSandboxClassName,
|
|
2568
|
+
migrationTag: typeof defaultProvider.migrationTag === "string" ? defaultProvider.migrationTag : "v1",
|
|
2569
|
+
name: typeof defaultProvider.name === "string" ? defaultProvider.name : void 0
|
|
2570
|
+
} : void 0;
|
|
2571
|
+
return {
|
|
2572
|
+
manifest,
|
|
2573
|
+
watchFiles: [...new Set(definitionMetadata.flatMap((metadata) => metadata.project ? getSandboxTaskProjectSourceFiles(metadata.project) : []))],
|
|
2574
|
+
aliases: [{
|
|
2575
|
+
key: "#vitehub-sandbox-task-registry",
|
|
2576
|
+
artifactKey: "sandbox-task-registry"
|
|
2577
|
+
}, ...createSandboxTaskProviderLoaderAliases(providerLoaderTarget)],
|
|
2578
|
+
artifacts: [
|
|
2579
|
+
...sandboxTaskArtifacts,
|
|
2580
|
+
{
|
|
2581
|
+
key: "sandbox-task-registry",
|
|
2582
|
+
filename: "runtime/sandbox-task-registry.mjs",
|
|
2583
|
+
getContents(emitted, location) {
|
|
2584
|
+
return createSandboxTaskRegistryContents(location.dst, sandboxTaskDefinitions.map((definition) => {
|
|
2585
|
+
const artifact = emitted.get(definition.definitionArtifactKey);
|
|
2586
|
+
if (!artifact) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0014({ message: `[vitehub] Missing generated sandbox definition module for "${definition.name}".` });
|
|
2587
|
+
return {
|
|
2588
|
+
name: definition.name,
|
|
2589
|
+
definitionModulePath: artifact.dst,
|
|
2590
|
+
stableDefinitionModulePath: artifact.stableDst
|
|
2591
|
+
};
|
|
2592
|
+
}), paths.aliasPath);
|
|
2593
|
+
}
|
|
2594
|
+
},
|
|
2595
|
+
...providerLoaderTarget ? [{
|
|
2596
|
+
key: "sandbox-task-provider-loader",
|
|
2597
|
+
filename: "runtime/sandbox-task-provider-loader.mjs",
|
|
2598
|
+
contents: createSandboxTaskProviderLoaderContents(providerLoaderTarget)
|
|
2599
|
+
}] : []
|
|
2600
|
+
],
|
|
2601
|
+
cloudflare: cloudflareOptions
|
|
2602
|
+
};
|
|
2603
|
+
}
|
|
2604
|
+
//#endregion
|
|
2605
|
+
//#region src/task/discovery.ts
|
|
2606
|
+
const sandboxTaskSuffixPattern = /\.sandbox-task\.(?:c|m)?[jt]s$/i;
|
|
2607
|
+
const sandboxTaskEntrypointFilenames = [
|
|
2608
|
+
"index.ts",
|
|
2609
|
+
"index.mts",
|
|
2610
|
+
"index.js",
|
|
2611
|
+
"index.mjs"
|
|
2612
|
+
];
|
|
2613
|
+
function createDiscoveredSandboxTaskDefinition(source, kind) {
|
|
2614
|
+
return (context) => ({
|
|
2615
|
+
handler: context.file,
|
|
2616
|
+
kind,
|
|
2617
|
+
name: context.name,
|
|
2618
|
+
source,
|
|
2619
|
+
_meta: {
|
|
2620
|
+
filename: context.name,
|
|
2621
|
+
sourcePath: context.file
|
|
2622
|
+
}
|
|
2623
|
+
});
|
|
2624
|
+
}
|
|
2625
|
+
function isServerSandboxTaskFile(rootDir, file) {
|
|
2626
|
+
const path = relative$1(rootDir, file).replace(/\\/g, "/");
|
|
2627
|
+
return path.startsWith("server/sandbox-tasks/") || path.startsWith("src/server/sandbox-tasks/");
|
|
2628
|
+
}
|
|
2629
|
+
function normalizeSuffixSandboxTaskName(rootDir, file) {
|
|
2630
|
+
if (isServerSandboxTaskFile(rootDir, file)) return void 0;
|
|
2631
|
+
return normalizeSuffixDefinitionName(rootDir, file, sandboxTaskSuffixPattern, { stripPrefix: "src/" });
|
|
2632
|
+
}
|
|
2633
|
+
function normalizeDirectorySandboxTaskName(directory, file) {
|
|
2634
|
+
return normalizePathDefinitionName(directory, file).replace(/\.sandbox-task$/, "");
|
|
2635
|
+
}
|
|
2636
|
+
function isNestedDirectory(parent, candidate) {
|
|
2637
|
+
const path = relative$1(parent, candidate).replace(/\\/g, "/");
|
|
2638
|
+
return path !== "" && path !== ".." && !path.startsWith("../");
|
|
2639
|
+
}
|
|
2640
|
+
function discoverServerSandboxTaskDefinitions(scanDirs) {
|
|
2641
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
2642
|
+
const createDefinition = createDiscoveredSandboxTaskDefinition("server-sandbox-tasks", "package-entry");
|
|
2643
|
+
for (const scanDir of scanDirs) {
|
|
2644
|
+
const directory = resolve$1(scanDir, "sandbox-tasks");
|
|
2645
|
+
const packageRoots = listMatchingFiles(directory, (name) => name === "package.json").map((manifest) => dirname$1(manifest)).sort((left, right) => {
|
|
2646
|
+
return relative$1(directory, left).split(/[\\/]/).length - relative$1(directory, right).split(/[\\/]/).length || left.localeCompare(right);
|
|
2647
|
+
});
|
|
2648
|
+
const entrypoints = new Map(packageRoots.map((packageRoot) => [packageRoot, sandboxTaskEntrypointFilenames.map((filename) => resolve$1(packageRoot, filename)).filter((file) => existsSync(file))]));
|
|
2649
|
+
const selectedRoots = [];
|
|
2650
|
+
for (const packageRoot of packageRoots) {
|
|
2651
|
+
if (selectedRoots.some((root) => isNestedDirectory(root, packageRoot))) continue;
|
|
2652
|
+
const packageEntrypoints = entrypoints.get(packageRoot);
|
|
2653
|
+
if (packageEntrypoints.length > 1) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0009({ message: `[vitehub] Sandbox package "${packageRoot}" has multiple entrypoints: ${packageEntrypoints.join(", ")}.` });
|
|
2654
|
+
if (packageEntrypoints.length === 0) continue;
|
|
2655
|
+
const file = packageEntrypoints[0];
|
|
2656
|
+
registerDefinition(definitions, createDefinition({
|
|
2657
|
+
file,
|
|
2658
|
+
name: normalizeDirectorySandboxTaskName(directory, file)
|
|
2659
|
+
}), "Sandbox Task");
|
|
2660
|
+
selectedRoots.push(packageRoot);
|
|
2661
|
+
}
|
|
2662
|
+
for (const packageRoot of packageRoots) {
|
|
2663
|
+
if (entrypoints.get(packageRoot).length > 0) continue;
|
|
2664
|
+
if (selectedRoots.some((root) => isNestedDirectory(packageRoot, root) || isNestedDirectory(root, packageRoot))) continue;
|
|
2665
|
+
throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0010({ message: `[vitehub] Sandbox package "${packageRoot}" requires one ESM entrypoint: ${sandboxTaskEntrypointFilenames.join(", ")}.` });
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
return sortDefinitions(definitions);
|
|
2669
|
+
}
|
|
2670
|
+
function discoverSandboxTaskDefinitions(options) {
|
|
2671
|
+
if (options.mode === "server-sandbox-tasks") return discoverServerSandboxTaskDefinitions(options.scanDirs);
|
|
2672
|
+
const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
|
|
2673
|
+
const serverScanDirs = roots.map((root) => resolve$1(root, "server"));
|
|
2674
|
+
return mergeDefinitions("Sandbox Task", discoverDefinitions("Sandbox Task", [createSuffixDefinitionSource("vite-suffix", roots, sandboxTaskSuffixPattern, normalizeSuffixSandboxTaskName, { createDefinition: createDiscoveredSandboxTaskDefinition("vite-suffix", "definition") })]), discoverServerSandboxTaskDefinitions(serverScanDirs));
|
|
2675
|
+
}
|
|
2676
|
+
//#endregion
|
|
2677
|
+
//#region src/task/internal/runtime-generation.ts
|
|
2678
|
+
const generationMarker = "// vitehub-sandbox-task-generation: ";
|
|
2679
|
+
const generationLockClaimStaleMs = 3e4;
|
|
2680
|
+
const generationLockInitializationStaleMs = 5e3;
|
|
2681
|
+
const generationLockName = ".runtime-generation.lock";
|
|
2682
|
+
const generationLockPublicationStaleMs = 3e5;
|
|
2683
|
+
const generationLockWaitMs = 6e4;
|
|
2684
|
+
const generationLockStaleMs = 3e5;
|
|
2685
|
+
const generationLockHeartbeatMs = 3e4;
|
|
2686
|
+
const releasedSandboxTaskRuntimeGenerationLocks = /* @__PURE__ */ new Set();
|
|
2687
|
+
function readNodeErrorCode$1(error) {
|
|
2688
|
+
return error instanceof Error && "code" in error ? error.code : void 0;
|
|
2689
|
+
}
|
|
2690
|
+
function parseSandboxTaskRuntimeGenerationLockOwner(value) {
|
|
2691
|
+
if (!value) return void 0;
|
|
2692
|
+
try {
|
|
2693
|
+
const parsed = JSON.parse(value);
|
|
2694
|
+
if (Object(parsed) !== parsed || Array.isArray(parsed)) return void 0;
|
|
2695
|
+
const host = Reflect.get(Object(parsed), "host");
|
|
2696
|
+
const pid = Reflect.get(Object(parsed), "pid");
|
|
2697
|
+
const released = Reflect.get(Object(parsed), "released");
|
|
2698
|
+
const token = Reflect.get(Object(parsed), "token");
|
|
2699
|
+
if (String(host) !== host || !Number.isSafeInteger(pid) || Number(pid) <= 0 || !(released === void 0 || released === true || released === false) || String(token) !== token) return void 0;
|
|
2700
|
+
const owner = {
|
|
2701
|
+
host: String(host),
|
|
2702
|
+
pid: Number(pid),
|
|
2703
|
+
token: String(token)
|
|
2704
|
+
};
|
|
2705
|
+
if (released === true) owner.released = true;
|
|
2706
|
+
return owner;
|
|
2707
|
+
} catch {
|
|
2708
|
+
return;
|
|
2709
|
+
}
|
|
2710
|
+
}
|
|
2711
|
+
function isLocalProcessAlive(pid) {
|
|
2712
|
+
try {
|
|
2713
|
+
process.kill(pid, 0);
|
|
2714
|
+
return true;
|
|
2715
|
+
} catch (error) {
|
|
2716
|
+
return readNodeErrorCode$1(error) !== "ESRCH";
|
|
2717
|
+
}
|
|
2718
|
+
}
|
|
2719
|
+
async function observeSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath) {
|
|
2720
|
+
const before = await stat(lockDir).catch(() => void 0);
|
|
2721
|
+
if (!before) return void 0;
|
|
2722
|
+
const ownerValue = await readFile(ownerPath, "utf8").catch(() => void 0);
|
|
2723
|
+
const publicationValue = await readFile(publicationPath, "utf8").catch(() => void 0);
|
|
2724
|
+
const lease = await stat(leasePath).catch(() => void 0);
|
|
2725
|
+
const after = await stat(lockDir).catch(() => void 0);
|
|
2726
|
+
if (!after || before.dev !== after.dev || before.ino !== after.ino) return void 0;
|
|
2727
|
+
return {
|
|
2728
|
+
dev: after.dev,
|
|
2729
|
+
ino: after.ino,
|
|
2730
|
+
leaseDev: lease?.dev,
|
|
2731
|
+
leaseIno: lease?.ino,
|
|
2732
|
+
leaseMtimeMs: lease?.mtimeMs ?? after.mtimeMs,
|
|
2733
|
+
ownerValue,
|
|
2734
|
+
publicationValue
|
|
2735
|
+
};
|
|
2736
|
+
}
|
|
2737
|
+
function isSandboxTaskRuntimeGenerationLockStale(observation, staleMs) {
|
|
2738
|
+
const owner = parseSandboxTaskRuntimeGenerationLockOwner(observation.ownerValue);
|
|
2739
|
+
if (owner?.released === true || owner && releasedSandboxTaskRuntimeGenerationLocks.has(owner.token)) return true;
|
|
2740
|
+
if (owner?.host === hostname()) {
|
|
2741
|
+
if (!isLocalProcessAlive(owner.pid)) return true;
|
|
2742
|
+
return Date.now() - observation.leaseMtimeMs > Math.max(staleMs, generationLockPublicationStaleMs);
|
|
2743
|
+
}
|
|
2744
|
+
if (owner && observation.publicationValue === owner.token) return Date.now() - observation.leaseMtimeMs > Math.max(staleMs, generationLockPublicationStaleMs);
|
|
2745
|
+
if (!owner || observation.leaseIno === void 0) return Date.now() - observation.leaseMtimeMs > Math.min(staleMs, generationLockInitializationStaleMs);
|
|
2746
|
+
return Date.now() - observation.leaseMtimeMs > staleMs;
|
|
2747
|
+
}
|
|
2748
|
+
function isSameSandboxTaskRuntimeGenerationLock(left, right) {
|
|
2749
|
+
return !!right && left.dev === right.dev && left.ino === right.ino && left.leaseDev === right.leaseDev && left.leaseIno === right.leaseIno && (left.leaseIno === void 0 || left.leaseMtimeMs === right.leaseMtimeMs) && left.ownerValue === right.ownerValue && left.publicationValue === right.publicationValue;
|
|
2750
|
+
}
|
|
2751
|
+
function isSameSandboxTaskRuntimeGenerationLockDirectory(left, right) {
|
|
2752
|
+
return !!right && left.dev === right.dev && left.ino === right.ino;
|
|
2753
|
+
}
|
|
2754
|
+
async function reclaimSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath, observation, staleMs) {
|
|
2755
|
+
const claimPath = resolve$1(lockDir, ".reclaim");
|
|
2756
|
+
let claim;
|
|
2757
|
+
while (!claim) try {
|
|
2758
|
+
claim = await open(claimPath, "wx");
|
|
2759
|
+
} catch (error) {
|
|
2760
|
+
const code = readNodeErrorCode$1(error);
|
|
2761
|
+
if (code === "ENOENT") return false;
|
|
2762
|
+
if (code !== "EEXIST") throw error;
|
|
2763
|
+
const claimInfo = await stat(claimPath).catch(() => void 0);
|
|
2764
|
+
if (!claimInfo || Date.now() - claimInfo.mtimeMs <= generationLockClaimStaleMs) return false;
|
|
2765
|
+
await rm(claimPath, { force: true }).catch(() => {});
|
|
2766
|
+
}
|
|
2767
|
+
await claim.close();
|
|
2768
|
+
let reclaimed = false;
|
|
2769
|
+
try {
|
|
2770
|
+
const current = await observeSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2771
|
+
const stillStale = current?.leaseIno === void 0 ? isSandboxTaskRuntimeGenerationLockStale(observation, staleMs) : isSandboxTaskRuntimeGenerationLockStale(current, staleMs);
|
|
2772
|
+
if (!isSameSandboxTaskRuntimeGenerationLock(observation, current) || !current || !stillStale) return false;
|
|
2773
|
+
const staleDir = `${lockDir}.stale-${randomUUID()}`;
|
|
2774
|
+
reclaimed = await rename(lockDir, staleDir).then(() => true, (error) => {
|
|
2775
|
+
if (readNodeErrorCode$1(error) === "ENOENT") return false;
|
|
2776
|
+
throw error;
|
|
2777
|
+
});
|
|
2778
|
+
if (reclaimed) await rm(staleDir, {
|
|
2779
|
+
recursive: true,
|
|
2780
|
+
force: true
|
|
2781
|
+
});
|
|
2782
|
+
if (reclaimed) {
|
|
2783
|
+
const owner = parseSandboxTaskRuntimeGenerationLockOwner(observation.ownerValue);
|
|
2784
|
+
if (owner) releasedSandboxTaskRuntimeGenerationLocks.delete(owner.token);
|
|
2785
|
+
}
|
|
2786
|
+
return reclaimed;
|
|
2787
|
+
} finally {
|
|
2788
|
+
if (!reclaimed) await rm(claimPath, { force: true }).catch(() => {});
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
async function retireSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath, observation, markReleased, retireLock) {
|
|
2792
|
+
const claimPath = resolve$1(lockDir, ".reclaim");
|
|
2793
|
+
let claim;
|
|
2794
|
+
try {
|
|
2795
|
+
claim = await open(claimPath, "wx");
|
|
2796
|
+
} catch (error) {
|
|
2797
|
+
if (readNodeErrorCode$1(error) === "ENOENT" || readNodeErrorCode$1(error) === "EEXIST") return;
|
|
2798
|
+
throw error;
|
|
2799
|
+
}
|
|
2800
|
+
await claim.close();
|
|
2801
|
+
let retired = false;
|
|
2802
|
+
try {
|
|
2803
|
+
if (!isSameSandboxTaskRuntimeGenerationLock(observation, await observeSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath))) return;
|
|
2804
|
+
await markReleased();
|
|
2805
|
+
if (!isSameSandboxTaskRuntimeGenerationLockDirectory(observation, await observeSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath))) return;
|
|
2806
|
+
const retiredDir = `${lockDir}.released-${randomUUID()}`;
|
|
2807
|
+
retired = await retireLock(lockDir, retiredDir).then(() => true, (error) => {
|
|
2808
|
+
if (readNodeErrorCode$1(error) === "ENOENT") return false;
|
|
2809
|
+
throw error;
|
|
2810
|
+
});
|
|
2811
|
+
return retired ? retiredDir : void 0;
|
|
2812
|
+
} finally {
|
|
2813
|
+
if (!retired) await rm(claimPath, { force: true }).catch(() => {});
|
|
2814
|
+
}
|
|
2815
|
+
}
|
|
2816
|
+
async function withSandboxTaskRuntimeGenerationLock(generatedDir, operation, options = {}) {
|
|
2817
|
+
const lockDir = resolve$1(generatedDir, generationLockName);
|
|
2818
|
+
const ownerPath = resolve$1(lockDir, "owner.json");
|
|
2819
|
+
const leasePath = resolve$1(lockDir, "lease");
|
|
2820
|
+
const publicationPath = resolve$1(lockDir, "publication");
|
|
2821
|
+
const heartbeatMs = options.heartbeatMs ?? generationLockHeartbeatMs;
|
|
2822
|
+
const pollMs = options.pollMs ?? 25;
|
|
2823
|
+
const removeLock = options.removeLock ?? rm;
|
|
2824
|
+
const retireLock = options.retireLock ?? rename;
|
|
2825
|
+
const staleMs = options.staleMs ?? generationLockStaleMs;
|
|
2826
|
+
const writeReleasedOwner = options.writeReleasedOwner ?? (async (file, value) => {
|
|
2827
|
+
await file.write(value, 0, "utf8");
|
|
2828
|
+
await file.truncate(Buffer.byteLength(value));
|
|
2829
|
+
});
|
|
2830
|
+
const ownerRecord = {
|
|
2831
|
+
host: options.host ?? hostname(),
|
|
2832
|
+
pid: process.pid,
|
|
2833
|
+
token: randomUUID()
|
|
2834
|
+
};
|
|
2835
|
+
const owner = JSON.stringify(ownerRecord);
|
|
2836
|
+
const deadline = Date.now() + (options.waitMs ?? generationLockWaitMs);
|
|
2837
|
+
let ownedLock;
|
|
2838
|
+
let createdLock;
|
|
2839
|
+
let leaseFile;
|
|
2840
|
+
let ownerFile;
|
|
2841
|
+
await mkdir(generatedDir, { recursive: true });
|
|
2842
|
+
while (true) {
|
|
2843
|
+
try {
|
|
2844
|
+
await mkdir(lockDir);
|
|
2845
|
+
} catch (error) {
|
|
2846
|
+
if (readNodeErrorCode$1(error) !== "EEXIST") throw error;
|
|
2847
|
+
const observation = await observeSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2848
|
+
if (observation && isSandboxTaskRuntimeGenerationLockStale(observation, staleMs)) {
|
|
2849
|
+
await reclaimSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath, observation, staleMs);
|
|
2850
|
+
continue;
|
|
2851
|
+
}
|
|
2852
|
+
if (Date.now() >= deadline) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0033({ message: `[vitehub] Timed out waiting to prepare the Sandbox runtime in ${generatedDir}.` });
|
|
2853
|
+
await setTimeout(pollMs);
|
|
2854
|
+
continue;
|
|
2855
|
+
}
|
|
2856
|
+
try {
|
|
2857
|
+
const created = await observeSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2858
|
+
if (!created || created.ownerValue !== void 0 || created.leaseIno !== void 0) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0034({ message: `[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.` });
|
|
2859
|
+
createdLock = created;
|
|
2860
|
+
await options.beforeInitializeLock?.();
|
|
2861
|
+
ownerFile = await open(ownerPath, "wx");
|
|
2862
|
+
await ownerFile.writeFile(owner);
|
|
2863
|
+
leaseFile = await open(leasePath, "wx");
|
|
2864
|
+
await leaseFile.writeFile(owner);
|
|
2865
|
+
ownedLock = await observeSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2866
|
+
if (!ownedLock) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0035({ message: `[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.` });
|
|
2867
|
+
break;
|
|
2868
|
+
} catch (error) {
|
|
2869
|
+
await leaseFile?.close().catch(() => {});
|
|
2870
|
+
leaseFile = void 0;
|
|
2871
|
+
await ownerFile?.close().catch(() => {});
|
|
2872
|
+
ownerFile = void 0;
|
|
2873
|
+
const failed = await observeSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2874
|
+
const failedOwnerBelongsToAttempt = failed?.ownerValue === owner || failed?.ownerValue === void 0 && failed?.leaseIno === void 0;
|
|
2875
|
+
if (createdLock && isSameSandboxTaskRuntimeGenerationLockDirectory(createdLock, failed) && failed && failedOwnerBelongsToAttempt) {
|
|
2876
|
+
const retiredDir = await retireSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath, failed, async () => {}, rename).catch(() => void 0);
|
|
2877
|
+
if (retiredDir) await rm(retiredDir, {
|
|
2878
|
+
recursive: true,
|
|
2879
|
+
force: true
|
|
2880
|
+
}).catch(() => {});
|
|
2881
|
+
}
|
|
2882
|
+
throw error;
|
|
2883
|
+
}
|
|
2884
|
+
}
|
|
2885
|
+
let heartbeatError;
|
|
2886
|
+
const assertOwned = async () => {
|
|
2887
|
+
if (heartbeatError) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0036({
|
|
2888
|
+
message: `[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.`,
|
|
2889
|
+
cause: heartbeatError
|
|
2890
|
+
});
|
|
2891
|
+
const active = await observeSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2892
|
+
if (!ownedLock || !active || active.dev !== ownedLock.dev || active.ino !== ownedLock.ino || active.leaseDev !== ownedLock.leaseDev || active.leaseIno !== ownedLock.leaseIno || active.ownerValue !== owner) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0037({ message: `[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.` });
|
|
2893
|
+
};
|
|
2894
|
+
const publish = async (publication) => {
|
|
2895
|
+
await assertOwned();
|
|
2896
|
+
const publicationFile = await open(publicationPath, "wx");
|
|
2897
|
+
try {
|
|
2898
|
+
await publicationFile.writeFile(ownerRecord.token);
|
|
2899
|
+
} finally {
|
|
2900
|
+
await publicationFile.close();
|
|
2901
|
+
}
|
|
2902
|
+
try {
|
|
2903
|
+
await assertOwned();
|
|
2904
|
+
return await publication();
|
|
2905
|
+
} finally {
|
|
2906
|
+
await assertOwned();
|
|
2907
|
+
await rm(publicationPath, { force: true });
|
|
2908
|
+
}
|
|
2909
|
+
};
|
|
2910
|
+
const heartbeatAbort = new AbortController();
|
|
2911
|
+
const heartbeat = (async () => {
|
|
2912
|
+
while (!heartbeatAbort.signal.aborted) {
|
|
2913
|
+
try {
|
|
2914
|
+
await setTimeout(heartbeatMs, void 0, { signal: heartbeatAbort.signal });
|
|
2915
|
+
} catch (error) {
|
|
2916
|
+
if (heartbeatAbort.signal.aborted) return;
|
|
2917
|
+
throw error;
|
|
2918
|
+
}
|
|
2919
|
+
if (heartbeatAbort.signal.aborted) return;
|
|
2920
|
+
const now = /* @__PURE__ */ new Date();
|
|
2921
|
+
await leaseFile.utimes(now, now);
|
|
2922
|
+
await assertOwned();
|
|
2923
|
+
}
|
|
2924
|
+
})().catch((error) => {
|
|
2925
|
+
heartbeatError = error;
|
|
2926
|
+
});
|
|
2927
|
+
let operationFailed = false;
|
|
2928
|
+
let operationError;
|
|
2929
|
+
let operationResult;
|
|
2930
|
+
try {
|
|
2931
|
+
operationResult = { value: await operation({
|
|
2932
|
+
assertOwned,
|
|
2933
|
+
publish
|
|
2934
|
+
}) };
|
|
2935
|
+
} catch (error) {
|
|
2936
|
+
operationFailed = true;
|
|
2937
|
+
operationError = error;
|
|
2938
|
+
}
|
|
2939
|
+
const cleanupErrors = [];
|
|
2940
|
+
heartbeatAbort.abort();
|
|
2941
|
+
await heartbeat.catch((error) => cleanupErrors.push(error));
|
|
2942
|
+
if (heartbeatError) cleanupErrors.push(sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0038({
|
|
2943
|
+
message: `[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.`,
|
|
2944
|
+
cause: heartbeatError
|
|
2945
|
+
}));
|
|
2946
|
+
const activeOwner = await readFile(ownerPath, "utf8").catch(() => void 0);
|
|
2947
|
+
const active = await observeSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2948
|
+
if (activeOwner === owner && ownedLock && active?.dev === ownedLock.dev && active.ino === ownedLock.ino && active.leaseDev === ownedLock.leaseDev && active.leaseIno === ownedLock.leaseIno) {
|
|
2949
|
+
releasedSandboxTaskRuntimeGenerationLocks.add(ownerRecord.token);
|
|
2950
|
+
const markReleased = async () => {
|
|
2951
|
+
const releasedOwner = JSON.stringify({
|
|
2952
|
+
...ownerRecord,
|
|
2953
|
+
released: true
|
|
2954
|
+
});
|
|
2955
|
+
await writeReleasedOwner(ownerFile, releasedOwner);
|
|
2956
|
+
const expired = /* @__PURE__ */ new Date(0);
|
|
2957
|
+
await leaseFile.utimes(expired, expired);
|
|
2958
|
+
};
|
|
2959
|
+
let retiredDir;
|
|
2960
|
+
try {
|
|
2961
|
+
retiredDir = await retireSandboxTaskRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath, active, markReleased, retireLock);
|
|
2962
|
+
} catch (releaseError) {
|
|
2963
|
+
try {
|
|
2964
|
+
await markReleased();
|
|
2965
|
+
} catch (recoveryError) {
|
|
2966
|
+
cleanupErrors.push(new AggregateError([releaseError, recoveryError], `[vitehub] Failed to release the Sandbox runtime generation lock in ${generatedDir}.`));
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
if (!retiredDir && cleanupErrors.length === 0) await markReleased().catch((error) => cleanupErrors.push(error));
|
|
2970
|
+
await leaseFile?.close().catch((error) => cleanupErrors.push(error));
|
|
2971
|
+
leaseFile = void 0;
|
|
2972
|
+
await ownerFile?.close().catch((error) => cleanupErrors.push(error));
|
|
2973
|
+
ownerFile = void 0;
|
|
2974
|
+
if (retiredDir) {
|
|
2975
|
+
await removeLock(retiredDir, {
|
|
2976
|
+
recursive: true,
|
|
2977
|
+
force: true
|
|
2978
|
+
}).catch(() => {});
|
|
2979
|
+
releasedSandboxTaskRuntimeGenerationLocks.delete(ownerRecord.token);
|
|
2980
|
+
}
|
|
2981
|
+
} else if (!heartbeatError) cleanupErrors.push(sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0039({ message: `[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.` }));
|
|
2982
|
+
await leaseFile?.close().catch((error) => cleanupErrors.push(error));
|
|
2983
|
+
await ownerFile?.close().catch((error) => cleanupErrors.push(error));
|
|
2984
|
+
if (operationFailed) {
|
|
2985
|
+
if (cleanupErrors.length > 0) throw new AggregateError([operationError, ...cleanupErrors], `[vitehub] Sandbox runtime preparation and generation lock cleanup failed in ${generatedDir}.`);
|
|
2986
|
+
throw operationError;
|
|
2987
|
+
}
|
|
2988
|
+
if (cleanupErrors.length === 1) throw cleanupErrors[0];
|
|
2989
|
+
if (cleanupErrors.length > 1) throw new AggregateError(cleanupErrors, `[vitehub] Failed to clean up the Sandbox runtime generation lock in ${generatedDir}.`);
|
|
2990
|
+
if (!operationResult) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0040({ message: `[vitehub] Sandbox runtime preparation completed without a result in ${generatedDir}.` });
|
|
2991
|
+
return operationResult.value;
|
|
2992
|
+
}
|
|
2993
|
+
function markSandboxTaskRuntimeGeneration(contents, generationDir) {
|
|
2994
|
+
return `${generationMarker}${basename$1(generationDir)}\n${contents}`;
|
|
2995
|
+
}
|
|
2996
|
+
async function readSandboxTaskRuntimeGeneration(facadeFile, generationsDir) {
|
|
2997
|
+
const name = (await readFile(facadeFile, "utf8").catch(() => void 0))?.split("\n", 1)[0]?.slice(36);
|
|
2998
|
+
return name?.startsWith("runtime-") && basename$1(name) === name ? resolve$1(generationsDir, name) : void 0;
|
|
2999
|
+
}
|
|
3000
|
+
async function activateSandboxTaskRuntimeFile(source, target, staged, operations = {
|
|
3001
|
+
copyFile,
|
|
3002
|
+
rename,
|
|
3003
|
+
rm
|
|
3004
|
+
}) {
|
|
3005
|
+
await operations.copyFile(source, staged);
|
|
3006
|
+
try {
|
|
3007
|
+
await operations.rename(staged, target);
|
|
3008
|
+
} finally {
|
|
3009
|
+
await operations.rm(staged, { force: true }).catch(() => {});
|
|
3010
|
+
}
|
|
3011
|
+
}
|
|
3012
|
+
async function restoreSandboxTaskRuntimeGeneration(previousRuntime, activeRuntime, lease, move = rename) {
|
|
3013
|
+
await lease.assertOwned();
|
|
3014
|
+
if (await lstat(activeRuntime).then(() => true, (error) => {
|
|
3015
|
+
if (readNodeErrorCode$1(error) === "ENOENT") return false;
|
|
3016
|
+
throw error;
|
|
3017
|
+
})) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0041({ message: `[vitehub] Sandbox runtime changed during activation; the previous runtime is retained at ${previousRuntime}.` });
|
|
3018
|
+
await lease.assertOwned();
|
|
3019
|
+
await move(previousRuntime, activeRuntime);
|
|
3020
|
+
}
|
|
3021
|
+
function resolveSandboxTaskRuntimeLinkType(platform) {
|
|
3022
|
+
return platform === "win32" ? "junction" : "dir";
|
|
3023
|
+
}
|
|
3024
|
+
function resolveSandboxTaskRuntimeFacadeImportBase(runtimeDir, generationFacadeFile, platform) {
|
|
3025
|
+
return platform === "win32" ? resolve$1(runtimeDir, "sandbox-task.mjs") : generationFacadeFile;
|
|
3026
|
+
}
|
|
3027
|
+
async function pruneSandboxTaskRuntimeGeneration(path, remove = rm) {
|
|
3028
|
+
await remove(path, {
|
|
3029
|
+
recursive: true,
|
|
3030
|
+
force: true
|
|
3031
|
+
}).catch(() => {});
|
|
3032
|
+
}
|
|
3033
|
+
//#endregion
|
|
3034
|
+
//#region src/task/internal/runtime-preparation.ts
|
|
3035
|
+
const SANDBOX_PACKAGE_ID$1 = "@vite-hub/sandbox/task";
|
|
3036
|
+
const SANDBOX_REGISTRY_ID = "#vitehub-sandbox-task-registry";
|
|
3037
|
+
const builtinModuleSet = /* @__PURE__ */ new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
3038
|
+
function readNodeErrorCode(error) {
|
|
3039
|
+
return error instanceof Error && "code" in error ? error.code : void 0;
|
|
3040
|
+
}
|
|
3041
|
+
function normalizeSandboxTaskOptions(options) {
|
|
3042
|
+
if (options === false) return false;
|
|
3043
|
+
if (!isPlainObject$1(options)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0042({ message: "[vitehub] `sandboxTask` must be a plain object." });
|
|
3044
|
+
return { ...options };
|
|
3045
|
+
}
|
|
3046
|
+
function createSandboxTaskRuntimeConfig(config, hosting) {
|
|
3047
|
+
const provider = getSandboxTaskFeatureProvider(config);
|
|
3048
|
+
const sandbox = provider?.provider === "vercel" ? {
|
|
3049
|
+
...config,
|
|
3050
|
+
token: provider.token ?? "",
|
|
3051
|
+
teamId: provider.teamId ?? "",
|
|
3052
|
+
projectId: provider.projectId ?? ""
|
|
3053
|
+
} : config;
|
|
3054
|
+
return {
|
|
3055
|
+
...hosting ? { hosting } : {},
|
|
3056
|
+
sandboxTask: sandbox
|
|
3057
|
+
};
|
|
3058
|
+
}
|
|
3059
|
+
async function readSandboxTaskWorkspaceDeps(rootDir) {
|
|
3060
|
+
const packageJson = JSON.parse(await readFile(resolve$1(rootDir, "package.json"), "utf8"));
|
|
3061
|
+
return {
|
|
3062
|
+
...packageJson.dependencies,
|
|
3063
|
+
...packageJson.devDependencies
|
|
3064
|
+
};
|
|
3065
|
+
}
|
|
3066
|
+
async function resolveSandboxTaskViteContext(integrationOptions, userConfig, env, hasDefinitions) {
|
|
3067
|
+
const configOptions = userConfig.sandboxTask;
|
|
3068
|
+
const options = normalizeSandboxTaskOptions(typeof configOptions === "undefined" ? integrationOptions ?? {} : configOptions);
|
|
3069
|
+
const nitro = isPlainObject$1(userConfig.nitro) ? userConfig.nitro : {};
|
|
3070
|
+
const hosting = normalizeHosting(resolveHostPreset({
|
|
3071
|
+
hosting: userConfig.preset,
|
|
3072
|
+
nitro
|
|
3073
|
+
})) || void 0;
|
|
3074
|
+
const config = options === false ? false : hasDefinitions ? resolveSandboxTaskFeatureConfig(options, hosting) : { ...options };
|
|
3075
|
+
const runtimeSandboxTaskConfig = config !== false && (hasDefinitions || getSandboxTaskFeatureProvider(config)?.provider) ? config : false;
|
|
3076
|
+
const rootDir = resolve$1(process.cwd(), typeof userConfig.root === "string" ? userConfig.root : ".");
|
|
3077
|
+
return {
|
|
3078
|
+
rootDir,
|
|
3079
|
+
config,
|
|
3080
|
+
deps: hasDefinitions ? await readSandboxTaskWorkspaceDeps(rootDir) : {},
|
|
3081
|
+
runtimeConfig: createSandboxTaskRuntimeConfig(runtimeSandboxTaskConfig, hosting),
|
|
3082
|
+
hosting,
|
|
3083
|
+
command: env.command,
|
|
3084
|
+
mode: env.mode
|
|
3085
|
+
};
|
|
3086
|
+
}
|
|
3087
|
+
function createSandboxTaskStateModuleContents(context) {
|
|
3088
|
+
const state = {
|
|
3089
|
+
config: context.config,
|
|
3090
|
+
runtimeConfig: context.runtimeConfig,
|
|
3091
|
+
hosting: context.hosting,
|
|
3092
|
+
rootDir: context.rootDir,
|
|
3093
|
+
mode: context.mode,
|
|
3094
|
+
command: context.command
|
|
3095
|
+
};
|
|
3096
|
+
return [
|
|
3097
|
+
`const state = ${JSON.stringify(state, null, 2)}`,
|
|
3098
|
+
"export const config = state.config",
|
|
3099
|
+
"export const runtimeConfig = state.runtimeConfig",
|
|
3100
|
+
"export const hosting = state.hosting",
|
|
3101
|
+
"export const rootDir = state.rootDir",
|
|
3102
|
+
"export const mode = state.mode",
|
|
3103
|
+
"export const command = state.command",
|
|
3104
|
+
"export default state",
|
|
3105
|
+
""
|
|
3106
|
+
].join("\n");
|
|
3107
|
+
}
|
|
3108
|
+
function readAliasEntries(alias) {
|
|
3109
|
+
if (Array.isArray(alias)) return alias;
|
|
3110
|
+
if (!alias || typeof alias !== "object") return [];
|
|
3111
|
+
return Object.entries(alias).filter((entry) => typeof entry[1] === "string").map(([find, replacement]) => ({
|
|
3112
|
+
find,
|
|
3113
|
+
replacement
|
|
3114
|
+
}));
|
|
3115
|
+
}
|
|
3116
|
+
function resolveStringAliases(alias) {
|
|
3117
|
+
const aliases = {};
|
|
3118
|
+
for (const entry of readAliasEntries(alias)) {
|
|
3119
|
+
if (typeof entry.find !== "string" || typeof entry.replacement !== "string") continue;
|
|
3120
|
+
const find = entry.find.replace(/\/$/, "");
|
|
3121
|
+
if (builtinModuleSet.has(entry.find) || builtinModuleSet.has(find)) continue;
|
|
3122
|
+
if (!find) continue;
|
|
3123
|
+
aliases[find] = entry.replacement;
|
|
3124
|
+
}
|
|
3125
|
+
return aliases;
|
|
3126
|
+
}
|
|
3127
|
+
function readResolveOptions(config) {
|
|
3128
|
+
if (!config || typeof config !== "object" || !("resolve" in config)) return {};
|
|
3129
|
+
const resolveOptions = config.resolve;
|
|
3130
|
+
return resolveOptions && typeof resolveOptions === "object" ? resolveOptions : {};
|
|
3131
|
+
}
|
|
3132
|
+
function createSandboxTaskRuntimeFacadeContents(file, runtimeConfig, registryFile, providerLoaderFile) {
|
|
3133
|
+
return [
|
|
3134
|
+
`import sandboxTaskRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
|
|
3135
|
+
...providerLoaderFile ? [`export { loadSandboxTaskRuntimeProvider } from ${JSON.stringify(createImportPath(file, providerLoaderFile))}`] : [],
|
|
3136
|
+
`import { setSandboxTaskRuntimeConfig, setSandboxTaskRuntimeRegistry } from ${JSON.stringify(sandboxTaskRuntimeStateSpecifier)}`,
|
|
3137
|
+
"",
|
|
3138
|
+
`setSandboxTaskRuntimeConfig(${JSON.stringify(runtimeConfig, null, 2)})`,
|
|
3139
|
+
"setSandboxTaskRuntimeRegistry(sandboxTaskRegistry)",
|
|
3140
|
+
"",
|
|
3141
|
+
"export default sandboxTaskRegistry",
|
|
3142
|
+
`export * from ${JSON.stringify(sandboxTaskRuntimeSpecifier)}`,
|
|
3143
|
+
""
|
|
3144
|
+
].join("\n");
|
|
3145
|
+
}
|
|
3146
|
+
function createGeneratedAliasMap(rootDir, plan, platform = process.platform) {
|
|
3147
|
+
const generatedDir = ensureGeneratedDir(rootDir, "sandbox-task");
|
|
3148
|
+
const artifactPaths = new Map((plan.artifacts || []).map((artifact) => [artifact.key, resolve$1(generatedDir, artifact.filename)]));
|
|
3149
|
+
const aliases = { [SANDBOX_PACKAGE_ID$1]: plan.manifest.aliasPath };
|
|
3150
|
+
for (const alias of plan.aliases || []) {
|
|
3151
|
+
if (alias.value) {
|
|
3152
|
+
aliases[alias.key] = alias.value;
|
|
3153
|
+
continue;
|
|
3154
|
+
}
|
|
3155
|
+
if (platform === "win32" && alias.artifactKey) {
|
|
3156
|
+
aliases[alias.key] = plan.manifest.aliasPath;
|
|
3157
|
+
continue;
|
|
3158
|
+
}
|
|
3159
|
+
if (alias.artifactKey && artifactPaths.has(alias.artifactKey)) aliases[alias.key] = artifactPaths.get(alias.artifactKey);
|
|
3160
|
+
}
|
|
3161
|
+
return aliases;
|
|
3162
|
+
}
|
|
3163
|
+
async function writeSandboxTaskArtifacts(rootDir, plan, createFacadeContents, platform = process.platform) {
|
|
3164
|
+
const generatedDir = ensureGeneratedDir(rootDir, "sandbox-task");
|
|
3165
|
+
await mkdir(generatedDir, { recursive: true });
|
|
3166
|
+
return await withSandboxTaskRuntimeGenerationLock(generatedDir, async (lease) => await writeSandboxTaskArtifactsLocked(plan, createFacadeContents, generatedDir, platform, lease));
|
|
3167
|
+
}
|
|
3168
|
+
async function writeSandboxTaskArtifactsLocked(plan, createFacadeContents, generatedDir, platform, lease) {
|
|
3169
|
+
const generationsDir = resolve$1(generatedDir, ".runtime-generations");
|
|
3170
|
+
await mkdir(generationsDir, { recursive: true });
|
|
3171
|
+
const generationDir = await mkdtemp(resolve$1(generationsDir, "runtime-"));
|
|
3172
|
+
const runtimeDir = resolve$1(generatedDir, "runtime");
|
|
3173
|
+
const stagedLink = resolve$1(generatedDir, `.runtime-link-${generationDir.slice(generationsDir.length + 1)}`);
|
|
3174
|
+
const legacyRuntimeDir = resolve$1(generationsDir, `.legacy-${generationDir.slice(generationsDir.length + 1)}`);
|
|
3175
|
+
const emitted = /* @__PURE__ */ new Map();
|
|
3176
|
+
const typeTemplate = plan.manifest.typeTemplate;
|
|
3177
|
+
let activated = false;
|
|
3178
|
+
const previousGeneration = await readlink(runtimeDir).catch(() => void 0);
|
|
3179
|
+
const previousWindowsGeneration = platform === "win32" ? await readSandboxTaskRuntimeGeneration(resolve$1(runtimeDir, "sandbox-task.mjs"), generationsDir) : void 0;
|
|
3180
|
+
try {
|
|
3181
|
+
for (const artifact of plan.artifacts || []) {
|
|
3182
|
+
const stableDst = resolve$1(generatedDir, artifact.filename);
|
|
3183
|
+
const relativePath = stableDst.slice(runtimeDir.length + 1);
|
|
3184
|
+
const dst = resolve$1(generationDir, relativePath);
|
|
3185
|
+
const contents = artifact.contents ?? await artifact.getContents?.(emitted, {
|
|
3186
|
+
dst,
|
|
3187
|
+
stableDst
|
|
3188
|
+
});
|
|
3189
|
+
if (typeof contents !== "string") throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0043({ message: `[vitehub] Sandbox generated artifact "${artifact.key}" did not return contents.` });
|
|
3190
|
+
emitted.set(artifact.key, {
|
|
3191
|
+
...artifact,
|
|
3192
|
+
contents,
|
|
3193
|
+
dst,
|
|
3194
|
+
stableDst
|
|
3195
|
+
});
|
|
3196
|
+
}
|
|
3197
|
+
if (typeTemplate) await writeFileIfChanged(resolve$1(generationDir, typeTemplate.filename.replace(/^runtime\//, "")), typeTemplate.contents);
|
|
3198
|
+
for (const artifact of emitted.values()) await writeFileIfChanged(artifact.dst, artifact.contents);
|
|
3199
|
+
const generationFacadeFile = resolve$1(generationDir, "sandbox-task.mjs");
|
|
3200
|
+
const activeFacadeFile = resolveSandboxTaskRuntimeFacadeImportBase(runtimeDir, generationFacadeFile, platform);
|
|
3201
|
+
const registryArtifact = emitted.get(plan.aliases?.find((alias) => alias.key === SANDBOX_REGISTRY_ID)?.artifactKey || "");
|
|
3202
|
+
if (!registryArtifact) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0044({ message: "[vitehub] Sandbox runtime plan did not emit a registry artifact." });
|
|
3203
|
+
const providerLoaderArtifact = emitted.get("sandbox-task-provider-loader");
|
|
3204
|
+
await writeFileIfChanged(generationFacadeFile, markSandboxTaskRuntimeGeneration(createFacadeContents(activeFacadeFile, registryArtifact.dst, providerLoaderArtifact?.dst), generationDir));
|
|
3205
|
+
await lease.assertOwned();
|
|
3206
|
+
if (platform === "win32") await lease.publish(async () => {
|
|
3207
|
+
await lease.assertOwned();
|
|
3208
|
+
await mkdir(runtimeDir, { recursive: true });
|
|
3209
|
+
const stableDefinitions = [...emitted.values()].filter((artifact) => artifact.key.startsWith("sandbox-task-definition:"));
|
|
3210
|
+
for (const artifact of stableDefinitions) {
|
|
3211
|
+
await lease.assertOwned();
|
|
3212
|
+
await mkdir(dirname$1(artifact.stableDst), { recursive: true });
|
|
3213
|
+
const stagedDefinition = resolve$1(generatedDir, `.runtime-definition-${generationDir.slice(generationsDir.length + 1)}-${basename$1(artifact.stableDst)}`);
|
|
3214
|
+
await activateSandboxTaskRuntimeFile(artifact.dst, artifact.stableDst, stagedDefinition);
|
|
3215
|
+
}
|
|
3216
|
+
if (typeTemplate) {
|
|
3217
|
+
await lease.assertOwned();
|
|
3218
|
+
const relativePath = typeTemplate.filename.replace(/^runtime\//, "");
|
|
3219
|
+
const stagedType = resolve$1(generatedDir, `.runtime-types-${generationDir.slice(generationsDir.length + 1)}.d.ts`);
|
|
3220
|
+
await activateSandboxTaskRuntimeFile(resolve$1(generationDir, relativePath), resolve$1(runtimeDir, relativePath), stagedType);
|
|
3221
|
+
}
|
|
3222
|
+
await lease.assertOwned();
|
|
3223
|
+
const stagedFacade = resolve$1(generatedDir, `.runtime-facade-${generationDir.slice(generationsDir.length + 1)}.mjs`);
|
|
3224
|
+
await activateSandboxTaskRuntimeFile(generationFacadeFile, resolve$1(runtimeDir, "sandbox-task.mjs"), stagedFacade);
|
|
3225
|
+
activated = true;
|
|
3226
|
+
const stableDefinitionDir = resolve$1(runtimeDir, "sandbox-task-definitions");
|
|
3227
|
+
const retainedDefinitions = new Set(stableDefinitions.map((artifact) => artifact.stableDst));
|
|
3228
|
+
for (const entry of await readdir(stableDefinitionDir).catch(() => [])) {
|
|
3229
|
+
const path = resolve$1(stableDefinitionDir, entry);
|
|
3230
|
+
if (!retainedDefinitions.has(path)) {
|
|
3231
|
+
await lease.assertOwned();
|
|
3232
|
+
await pruneSandboxTaskRuntimeGeneration(path);
|
|
3233
|
+
}
|
|
3234
|
+
}
|
|
3235
|
+
});
|
|
3236
|
+
else await lease.publish(async () => {
|
|
3237
|
+
await lease.assertOwned();
|
|
3238
|
+
await symlink(generationDir, stagedLink, resolveSandboxTaskRuntimeLinkType(platform));
|
|
3239
|
+
await lease.assertOwned();
|
|
3240
|
+
try {
|
|
3241
|
+
await rename(stagedLink, runtimeDir);
|
|
3242
|
+
activated = true;
|
|
3243
|
+
} catch (error) {
|
|
3244
|
+
const code = readNodeErrorCode(error);
|
|
3245
|
+
if (code !== "EEXIST" && code !== "EISDIR" && code !== "ENOTEMPTY") throw error;
|
|
3246
|
+
await lease.assertOwned();
|
|
3247
|
+
await rename(runtimeDir, legacyRuntimeDir);
|
|
3248
|
+
try {
|
|
3249
|
+
await lease.assertOwned();
|
|
3250
|
+
await rename(stagedLink, runtimeDir);
|
|
3251
|
+
activated = true;
|
|
3252
|
+
} catch (activationError) {
|
|
3253
|
+
try {
|
|
3254
|
+
await restoreSandboxTaskRuntimeGeneration(legacyRuntimeDir, runtimeDir, lease);
|
|
3255
|
+
} catch (rollbackError) {
|
|
3256
|
+
throw new AggregateError([activationError, rollbackError], `[vitehub] Sandbox runtime activation failed; the previous runtime is retained at ${legacyRuntimeDir}.`);
|
|
3257
|
+
}
|
|
3258
|
+
throw activationError;
|
|
3259
|
+
}
|
|
3260
|
+
await lease.assertOwned();
|
|
3261
|
+
await pruneSandboxTaskRuntimeGeneration(legacyRuntimeDir);
|
|
3262
|
+
}
|
|
3263
|
+
});
|
|
3264
|
+
} finally {
|
|
3265
|
+
await rm(stagedLink, { force: true });
|
|
3266
|
+
if (!activated) await rm(generationDir, {
|
|
3267
|
+
recursive: true,
|
|
3268
|
+
force: true
|
|
3269
|
+
});
|
|
3270
|
+
}
|
|
3271
|
+
const retained = new Set([
|
|
3272
|
+
generationDir,
|
|
3273
|
+
previousGeneration && resolve$1(generatedDir, previousGeneration),
|
|
3274
|
+
previousWindowsGeneration
|
|
3275
|
+
].filter(Boolean));
|
|
3276
|
+
await lease.publish(async () => {
|
|
3277
|
+
await lease.assertOwned();
|
|
3278
|
+
for (const entry of await readdir(generationsDir)) {
|
|
3279
|
+
const path = resolve$1(generationsDir, entry);
|
|
3280
|
+
if (!retained.has(path)) {
|
|
3281
|
+
await lease.assertOwned();
|
|
3282
|
+
await pruneSandboxTaskRuntimeGeneration(path);
|
|
3283
|
+
}
|
|
3284
|
+
}
|
|
3285
|
+
});
|
|
3286
|
+
return emitted;
|
|
3287
|
+
}
|
|
3288
|
+
async function prepareSandboxTaskRuntime(options) {
|
|
3289
|
+
const resolvedRoot = options.resolvedConfig?.root || resolve$1(process.cwd(), typeof options.userConfig.root === "string" ? options.userConfig.root : ".");
|
|
3290
|
+
const configuredProjectRoot = options.userConfig[VITEHUB_PROJECT_ROOT];
|
|
3291
|
+
const rootDir = typeof configuredProjectRoot === "string" ? resolve$1(configuredProjectRoot) : resolvedRoot;
|
|
3292
|
+
const configOptions = options.userConfig.sandboxTask;
|
|
3293
|
+
const definitions = (typeof configOptions === "undefined" ? options.integrationOptions === false : configOptions === false) ? [] : discoverSandboxTaskDefinitions({ rootDir });
|
|
3294
|
+
const resolvedNitro = options.resolvedConfig?.nitro;
|
|
3295
|
+
const context = await resolveSandboxTaskViteContext(options.integrationOptions, {
|
|
3296
|
+
...options.userConfig,
|
|
3297
|
+
...isPlainObject$1(resolvedNitro) ? { nitro: resolvedNitro } : {},
|
|
3298
|
+
root: rootDir
|
|
3299
|
+
}, options.env, definitions.length > 0);
|
|
3300
|
+
const stateModule = createSandboxTaskStateModuleContents(context);
|
|
3301
|
+
if (!context.config) return {
|
|
3302
|
+
aliases: {},
|
|
3303
|
+
definitions: [],
|
|
3304
|
+
files: [],
|
|
3305
|
+
hosting: context.hosting,
|
|
3306
|
+
provider: void 0,
|
|
3307
|
+
rootDir,
|
|
3308
|
+
stateModule,
|
|
3309
|
+
watchFiles: []
|
|
3310
|
+
};
|
|
3311
|
+
const facadeFile = resolve$1(ensureGeneratedDir(rootDir, "sandbox-task"), "runtime/sandbox-task.mjs");
|
|
3312
|
+
const plan = await createSandboxTaskFeaturePlan(context.config, definitions, { aliasPath: facadeFile }, context.deps, context.hosting, {
|
|
3313
|
+
bundleAlias: resolveStringAliases(options.resolvedConfig?.resolve.alias ?? readResolveOptions(options.userConfig).alias),
|
|
3314
|
+
rootDir,
|
|
3315
|
+
scanRoots: [rootDir],
|
|
3316
|
+
serverImports: { presets: [] }
|
|
3317
|
+
});
|
|
3318
|
+
const aliases = createGeneratedAliasMap(rootDir, plan, options.platform);
|
|
3319
|
+
if (options.writeArtifacts === false) return {
|
|
3320
|
+
aliases,
|
|
3321
|
+
cloudflare: plan.cloudflare,
|
|
3322
|
+
definitions,
|
|
3323
|
+
files: [],
|
|
3324
|
+
hosting: context.hosting,
|
|
3325
|
+
provider: getSandboxTaskFeatureProvider(context.config)?.provider,
|
|
3326
|
+
rootDir,
|
|
3327
|
+
stateModule,
|
|
3328
|
+
watchFiles: plan.watchFiles || []
|
|
3329
|
+
};
|
|
3330
|
+
const emitted = await writeSandboxTaskArtifacts(rootDir, plan, (file, registryFile, providerLoaderFile) => createSandboxTaskRuntimeFacadeContents(file, context.runtimeConfig.sandboxTask, registryFile, providerLoaderFile), options.platform);
|
|
3331
|
+
return {
|
|
3332
|
+
aliases,
|
|
3333
|
+
cloudflare: plan.cloudflare,
|
|
3334
|
+
definitions,
|
|
3335
|
+
files: [
|
|
3336
|
+
facadeFile,
|
|
3337
|
+
...Array.from(emitted.values(), (artifact) => artifact.dst),
|
|
3338
|
+
...(plan.artifacts || []).map((artifact) => resolve$1(ensureGeneratedDir(rootDir, "sandbox-task"), artifact.filename))
|
|
3339
|
+
],
|
|
3340
|
+
hosting: context.hosting,
|
|
3341
|
+
provider: getSandboxTaskFeatureProvider(context.config)?.provider,
|
|
3342
|
+
rootDir,
|
|
3343
|
+
stateModule,
|
|
3344
|
+
watchFiles: plan.watchFiles || []
|
|
3345
|
+
};
|
|
3346
|
+
}
|
|
3347
|
+
//#endregion
|
|
3348
|
+
//#region ../internal/src/inspect.ts
|
|
3349
|
+
function relativeDefinitionFile(projectRoot, file) {
|
|
3350
|
+
return relative$1(projectRoot, file).replaceAll("\\", "/");
|
|
3351
|
+
}
|
|
3352
|
+
const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
|
|
3353
|
+
new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
|
|
3354
|
+
new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
|
|
3355
|
+
//#endregion
|
|
3356
|
+
//#region src/task/inspect.ts
|
|
3357
|
+
/** Lists Sandbox Task Definitions and package entries as serializable inspection summaries. */
|
|
3358
|
+
function inspectSandboxTaskDefinitions(options) {
|
|
3359
|
+
return discoverSandboxTaskDefinitions({ rootDir: options.rootDir }).map((definition) => ({
|
|
3360
|
+
fields: [{
|
|
3361
|
+
label: "Kind",
|
|
3362
|
+
value: definition.kind === "package-entry" ? "Package entry" : "Definition"
|
|
3363
|
+
}],
|
|
3364
|
+
file: relativeDefinitionFile(options.projectRoot, definition.handler),
|
|
3365
|
+
name: definition.name,
|
|
3366
|
+
source: definition.source
|
|
3367
|
+
}));
|
|
3368
|
+
}
|
|
3369
|
+
/** Console section that lists discovered Sandbox Task Definitions. `vitehub inspect definitions` reads the same data. */
|
|
3370
|
+
const sandboxTaskConsoleSection = {
|
|
3371
|
+
description: "Inspect discovered Sandbox Task Definitions without starting runtime resources.",
|
|
3372
|
+
icon: "i-lucide-container",
|
|
3373
|
+
id: "sandbox-tasks",
|
|
3374
|
+
label: "Sandbox Tasks",
|
|
3375
|
+
read: inspectSandboxTaskDefinitions,
|
|
3376
|
+
view: {
|
|
3377
|
+
kind: "definition-catalog",
|
|
3378
|
+
notice: "Running Sandbox Tasks, files, processes, logs, ports, and lifecycle state are not included in this build-time catalog."
|
|
3379
|
+
}
|
|
3380
|
+
};
|
|
3381
|
+
//#endregion
|
|
3382
|
+
//#region src/task/vite.ts
|
|
3383
|
+
const SANDBOX_PACKAGE_ID = "@vite-hub/sandbox/task";
|
|
3384
|
+
const SANDBOX_PACKAGE_NAME = "@vite-hub/sandbox";
|
|
3385
|
+
const SANDBOX_PROVIDER_LOADER_ID = "vitehub-sandbox-task-provider-loader";
|
|
3386
|
+
const SANDBOX_STATE_ID = "#vitehub/sandbox-task";
|
|
3387
|
+
const RESOLVED_SANDBOX_STATE_ID = "\0vitehub:sandbox-task:state";
|
|
3388
|
+
function mergeSandboxTaskNitroProviderAliases(nitro, aliases) {
|
|
3389
|
+
const providerAliases = Object.fromEntries(sandboxTaskProviderLoaderSpecifiers.flatMap((specifier) => {
|
|
3390
|
+
const replacement = aliases[specifier];
|
|
3391
|
+
return replacement ? [[specifier, replacement]] : [];
|
|
3392
|
+
}));
|
|
3393
|
+
if (!Object.keys(providerAliases).length) return;
|
|
3394
|
+
nitro.alias = {
|
|
3395
|
+
...isPlainObject$1(nitro.alias) ? nitro.alias : {},
|
|
3396
|
+
...providerAliases
|
|
3397
|
+
};
|
|
3398
|
+
}
|
|
3399
|
+
function mergeSandboxTaskNitroNoExternals(nitro, provider) {
|
|
3400
|
+
if (provider !== "cloudflare" && provider !== "vercel") return;
|
|
3401
|
+
const existing = nitro.noExternals;
|
|
3402
|
+
if (existing === true) return;
|
|
3403
|
+
const existingEntries = Array.isArray(existing) ? existing : [];
|
|
3404
|
+
const additions = [SANDBOX_PACKAGE_NAME, sandboxTaskRuntimeDependencyByProvider[provider]];
|
|
3405
|
+
nitro.noExternals = [...existingEntries, ...additions.filter((addition) => !existingEntries.includes(addition))];
|
|
3406
|
+
}
|
|
3407
|
+
function sandboxTaskProviderLoaderFallback() {
|
|
3408
|
+
return resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox/task", "./runtime/provider-loader", "runtime/provider-loader.js");
|
|
3409
|
+
}
|
|
3410
|
+
const sandboxTaskRuntimePackageAliases = {
|
|
3411
|
+
[sandboxTaskRuntimeProviderSpecifiers.cloudflare]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./runtime/providers/cloudflare", "runtime/providers/cloudflare.js"),
|
|
3412
|
+
[sandboxTaskRuntimeProviderSpecifiers.vercel]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./runtime/providers/vercel", "runtime/providers/vercel.js"),
|
|
3413
|
+
[sandboxTaskRuntimeSpecifier]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./index", "index.js"),
|
|
3414
|
+
[sandboxTaskRuntimeStateSpecifier]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./runtime/state", "runtime/state.js")
|
|
3415
|
+
};
|
|
3416
|
+
function toSandboxTaskAliasEntries(aliases) {
|
|
3417
|
+
return Object.entries(aliases).map(([find, replacement]) => ({
|
|
3418
|
+
find: find === SANDBOX_PACKAGE_ID ? /^@vite-hub\/sandbox\/task$/ : find,
|
|
3419
|
+
replacement
|
|
3420
|
+
}));
|
|
3421
|
+
}
|
|
3422
|
+
function withoutSandboxTaskPackageAlias(aliases) {
|
|
3423
|
+
const { [SANDBOX_PACKAGE_ID]: _sandboxTaskAlias, ...rest } = aliases;
|
|
3424
|
+
return rest;
|
|
3425
|
+
}
|
|
3426
|
+
function isSandboxTaskSourceFile(file) {
|
|
3427
|
+
return /\.(?:c|m)?[jt]s$/i.test(file) && !/\.d\.(?:c|m)?[jt]s$/i.test(file);
|
|
3428
|
+
}
|
|
3429
|
+
function isLocalSourceFile(file, rootDir) {
|
|
3430
|
+
if (!rootDir) return false;
|
|
3431
|
+
const path = normalize(relative$1(rootDir, file));
|
|
3432
|
+
return path !== "" && !path.startsWith("../") && !path.startsWith("/") && !path.startsWith("node_modules/") && !path.startsWith(".vitehub/");
|
|
3433
|
+
}
|
|
3434
|
+
function isSandboxTaskProjectManifestUpdate(file, rootDir) {
|
|
3435
|
+
if (basename$1(file) !== "package.json" || !isLocalSourceFile(file, rootDir)) return false;
|
|
3436
|
+
const path = normalize(relative$1(rootDir, file));
|
|
3437
|
+
return /(?:^|\/)(?:src\/)?server\/sandbox-tasks\//.test(path);
|
|
3438
|
+
}
|
|
3439
|
+
function isSandboxTaskProjectFileUpdate(file, rootDir) {
|
|
3440
|
+
if (!isLocalSourceFile(file, rootDir)) return false;
|
|
3441
|
+
const path = normalize(relative$1(rootDir, file));
|
|
3442
|
+
return /(?:^|\/)(?:src\/)?server\/sandbox-tasks\//.test(path) || /^(?:pnpm-workspace\.yaml|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lock)$/.test(path);
|
|
3443
|
+
}
|
|
3444
|
+
function isSandboxTaskDefinitionUpdate(file, definitions, generatedFiles, watchFiles, rootDir) {
|
|
3445
|
+
const changedFile = normalize(file);
|
|
3446
|
+
if (definitions.some((definition) => normalize(definition.handler) === changedFile)) return true;
|
|
3447
|
+
if (generatedFiles.some((file) => normalize(file) === changedFile)) return false;
|
|
3448
|
+
if (watchFiles.some((file) => normalize(file) === changedFile)) return true;
|
|
3449
|
+
if (isSandboxTaskProjectManifestUpdate(changedFile, rootDir)) return true;
|
|
3450
|
+
if (isSandboxTaskProjectFileUpdate(changedFile, rootDir)) return true;
|
|
3451
|
+
if (isLocalSourceFile(changedFile, rootDir)) return true;
|
|
3452
|
+
if (!isSandboxTaskSourceFile(changedFile)) return false;
|
|
3453
|
+
return /\.sandbox-task\.(?:c|m)?[jt]s$/i.test(changedFile) || /(?:^|\/)(?:src\/)?server\/sandbox-tasks\//.test(changedFile) || isLocalSourceFile(changedFile, rootDir);
|
|
3454
|
+
}
|
|
3455
|
+
function invalidateGeneratedSandboxTaskModules(files, moduleGraph) {
|
|
3456
|
+
for (const file of new Set(files.map((file) => normalize(file)))) {
|
|
3457
|
+
const module = moduleGraph.getModuleById(file);
|
|
3458
|
+
if (module) moduleGraph.invalidateModule(module);
|
|
3459
|
+
}
|
|
3460
|
+
}
|
|
3461
|
+
async function resolveGeneratedSandboxTaskModuleIds(files) {
|
|
3462
|
+
return Promise.all(files.map(async (file) => normalize(await realpath(file).catch(() => file))));
|
|
3463
|
+
}
|
|
3464
|
+
function publicSandboxTaskOptions(options) {
|
|
3465
|
+
return Object.fromEntries(Object.entries(options).filter(([key]) => key !== "providerImportAliases" && key !== "providerImportSpecifier"));
|
|
3466
|
+
}
|
|
3467
|
+
function mutableSandboxTaskNitroTarget(value) {
|
|
3468
|
+
return value;
|
|
3469
|
+
}
|
|
3470
|
+
function hubSandboxTask(options) {
|
|
3471
|
+
const internalOptions = options;
|
|
3472
|
+
const integrationOptions = internalOptions ? publicSandboxTaskOptions(internalOptions) : internalOptions;
|
|
3473
|
+
const mergeSandboxTaskNoExternal = createNoExternalAddition(SANDBOX_PACKAGE_NAME);
|
|
3474
|
+
let generatedAliases = {};
|
|
3475
|
+
let generatedFiles = [];
|
|
3476
|
+
let watchFiles = [];
|
|
3477
|
+
let definitions = [];
|
|
3478
|
+
let rootDir;
|
|
3479
|
+
let sandboxTaskStateModule;
|
|
3480
|
+
let rawConfig = {};
|
|
3481
|
+
let rawEnv = {
|
|
3482
|
+
command: "serve",
|
|
3483
|
+
mode: "development"
|
|
3484
|
+
};
|
|
3485
|
+
let resolvedConfig;
|
|
3486
|
+
let sandboxTaskEnabled = integrationOptions !== false;
|
|
3487
|
+
let selectedProvider;
|
|
3488
|
+
let earlyNitroTarget;
|
|
3489
|
+
let earlyNitroSnapshot;
|
|
3490
|
+
let composedCloudflareEarly = false;
|
|
3491
|
+
let sandboxTaskRuntimeRefresh = Promise.resolve();
|
|
3492
|
+
const sandboxTaskNitroModule = (nitro) => {
|
|
3493
|
+
const options = nitro.options;
|
|
3494
|
+
mergeSandboxTaskNitroNoExternals(options, selectedProvider);
|
|
3495
|
+
if (selectedProvider) mergeSandboxTaskNitroProviderAliases(options, generatedAliases);
|
|
3496
|
+
nitro.hooks.hook("build:before", () => {
|
|
3497
|
+
mergeSandboxTaskNitroNoExternals(options, selectedProvider);
|
|
3498
|
+
if (selectedProvider) mergeSandboxTaskNitroProviderAliases(options, generatedAliases);
|
|
3499
|
+
});
|
|
3500
|
+
};
|
|
3501
|
+
function cloneConfigValue(value) {
|
|
3502
|
+
if (Array.isArray(value)) return value.map(cloneConfigValue);
|
|
3503
|
+
if (isPlainRecord(value) && Object.getPrototypeOf(value) === Object.prototype) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cloneConfigValue(entry)]));
|
|
3504
|
+
return value;
|
|
3505
|
+
}
|
|
3506
|
+
async function prepareCurrentSandboxTaskRuntime(writeArtifacts = true) {
|
|
3507
|
+
const prepared = await prepareSandboxTaskRuntime({
|
|
3508
|
+
integrationOptions,
|
|
3509
|
+
userConfig: rawConfig,
|
|
3510
|
+
env: rawEnv,
|
|
3511
|
+
resolvedConfig,
|
|
3512
|
+
writeArtifacts
|
|
3513
|
+
});
|
|
3514
|
+
sandboxTaskStateModule = prepared.stateModule;
|
|
3515
|
+
return prepared;
|
|
3516
|
+
}
|
|
3517
|
+
async function activateCurrentSandboxTaskRuntime() {
|
|
3518
|
+
const prepared = await prepareCurrentSandboxTaskRuntime();
|
|
3519
|
+
generatedAliases = prepared.aliases;
|
|
3520
|
+
generatedFiles = prepared.files;
|
|
3521
|
+
watchFiles = prepared.watchFiles;
|
|
3522
|
+
definitions = prepared.definitions;
|
|
3523
|
+
rootDir = prepared.rootDir;
|
|
3524
|
+
if (internalOptions?.providerImportAliases && internalOptions.providerImportSpecifier) {
|
|
3525
|
+
const facade = generatedAliases[SANDBOX_PACKAGE_ID];
|
|
3526
|
+
if (facade) {
|
|
3527
|
+
internalOptions.providerImportAliases[internalOptions.providerImportSpecifier] = facade;
|
|
3528
|
+
Object.assign(internalOptions.providerImportAliases, sandboxTaskRuntimePackageAliases);
|
|
3529
|
+
} else {
|
|
3530
|
+
delete internalOptions.providerImportAliases[internalOptions.providerImportSpecifier];
|
|
3531
|
+
for (const specifier of Object.keys(sandboxTaskRuntimePackageAliases)) delete internalOptions.providerImportAliases[specifier];
|
|
3532
|
+
}
|
|
3533
|
+
for (const specifier of sandboxTaskProviderLoaderSpecifiers) {
|
|
3534
|
+
const providerLoader = generatedAliases[specifier];
|
|
3535
|
+
if (providerLoader) internalOptions.providerImportAliases[specifier] = providerLoader;
|
|
3536
|
+
else delete internalOptions.providerImportAliases[specifier];
|
|
3537
|
+
}
|
|
3538
|
+
}
|
|
3539
|
+
return prepared;
|
|
3540
|
+
}
|
|
3541
|
+
async function refreshSandboxTaskRuntime(transaction = (refresh) => refresh()) {
|
|
3542
|
+
const refresh = sandboxTaskRuntimeRefresh.then(() => transaction(activateCurrentSandboxTaskRuntime));
|
|
3543
|
+
sandboxTaskRuntimeRefresh = refresh.then(() => void 0, () => void 0);
|
|
3544
|
+
return await refresh;
|
|
3545
|
+
}
|
|
3546
|
+
async function composeCloudflareSandbox(config, prepared, finalizeWrangler = false) {
|
|
3547
|
+
if (!prepared.cloudflare || !hasNitroConfigContext(config) || getHostingProvider(prepared.hosting) !== "cloudflare") return false;
|
|
3548
|
+
config.nitro = await configureCloudflareSandboxNitro(mutableSandboxTaskNitroTarget(config.nitro), prepared.rootDir, prepared.cloudflare, finalizeWrangler);
|
|
3549
|
+
return true;
|
|
3550
|
+
}
|
|
3551
|
+
return {
|
|
3552
|
+
name: "@vite-hub/sandbox/task/vite",
|
|
3553
|
+
enforce: "pre",
|
|
3554
|
+
nitro: {
|
|
3555
|
+
name: "@vite-hub/sandbox/task/provider-runtime",
|
|
3556
|
+
setup: sandboxTaskNitroModule
|
|
3557
|
+
},
|
|
3558
|
+
vitehub: { inspect: () => sandboxTaskEnabled ? { definitions: [{
|
|
3559
|
+
kind: "sandbox-task",
|
|
3560
|
+
label: "Sandbox Tasks",
|
|
3561
|
+
list: () => {
|
|
3562
|
+
const sandboxTaskRoot = rootDir ?? resolvedConfig?.root ?? process.cwd();
|
|
3563
|
+
return inspectSandboxTaskDefinitions({
|
|
3564
|
+
projectRoot: resolveViteHubProjectRoot(sandboxTaskRoot),
|
|
3565
|
+
rootDir: sandboxTaskRoot
|
|
3566
|
+
});
|
|
3567
|
+
}
|
|
3568
|
+
}] } : void 0 },
|
|
3569
|
+
async config(config, env) {
|
|
3570
|
+
rawConfig = config;
|
|
3571
|
+
rawEnv = env;
|
|
3572
|
+
const prepared = await prepareCurrentSandboxTaskRuntime(false);
|
|
3573
|
+
sandboxTaskEnabled = rawConfig.sandboxTask !== false && integrationOptions !== false;
|
|
3574
|
+
generatedAliases = prepared.aliases;
|
|
3575
|
+
generatedFiles = prepared.files;
|
|
3576
|
+
watchFiles = prepared.watchFiles;
|
|
3577
|
+
definitions = prepared.definitions;
|
|
3578
|
+
rootDir = prepared.rootDir;
|
|
3579
|
+
selectedProvider = prepared.provider;
|
|
3580
|
+
const nitro = config.nitro;
|
|
3581
|
+
if (isPlainObject$1(nitro)) {
|
|
3582
|
+
earlyNitroTarget = nitro;
|
|
3583
|
+
earlyNitroSnapshot = cloneConfigValue(earlyNitroTarget);
|
|
3584
|
+
}
|
|
3585
|
+
composedCloudflareEarly = await composeCloudflareSandbox(config, prepared);
|
|
3586
|
+
return { resolve: { alias: toSandboxTaskAliasEntries({
|
|
3587
|
+
[SANDBOX_PROVIDER_LOADER_ID]: sandboxTaskProviderLoaderFallback(),
|
|
3588
|
+
...withoutSandboxTaskPackageAlias(generatedAliases)
|
|
3589
|
+
}) } };
|
|
3590
|
+
},
|
|
3591
|
+
resolveId(id) {
|
|
3592
|
+
if (!sandboxTaskStateModule) return;
|
|
3593
|
+
if (id === SANDBOX_STATE_ID) return RESOLVED_SANDBOX_STATE_ID;
|
|
3594
|
+
if (id === RESOLVED_SANDBOX_STATE_ID) return id;
|
|
3595
|
+
},
|
|
3596
|
+
load(id) {
|
|
3597
|
+
if (id === SANDBOX_STATE_ID || id === RESOLVED_SANDBOX_STATE_ID) return sandboxTaskStateModule;
|
|
3598
|
+
},
|
|
3599
|
+
async configResolved(config) {
|
|
3600
|
+
resolvedConfig = config;
|
|
3601
|
+
const prepared = await refreshSandboxTaskRuntime();
|
|
3602
|
+
sandboxTaskEnabled = rawConfig.sandboxTask !== false && integrationOptions !== false;
|
|
3603
|
+
selectedProvider = prepared.provider;
|
|
3604
|
+
if (!await composeCloudflareSandbox(config, prepared, true) && composedCloudflareEarly && earlyNitroTarget && earlyNitroSnapshot) for (const key of ["cloudflare", "rollupConfig"]) if (key in earlyNitroSnapshot) earlyNitroTarget[key] = earlyNitroSnapshot[key];
|
|
3605
|
+
else delete earlyNitroTarget[key];
|
|
3606
|
+
},
|
|
3607
|
+
async handleHotUpdate(context) {
|
|
3608
|
+
if (!isSandboxTaskDefinitionUpdate(context.file, definitions, generatedFiles, watchFiles, rootDir)) return;
|
|
3609
|
+
await refreshSandboxTaskRuntime(async (refresh) => {
|
|
3610
|
+
const previousFiles = [...generatedFiles, ...Object.values(generatedAliases)];
|
|
3611
|
+
const previousResolvedFiles = await resolveGeneratedSandboxTaskModuleIds(previousFiles);
|
|
3612
|
+
const prepared = await refresh();
|
|
3613
|
+
selectedProvider = prepared.provider;
|
|
3614
|
+
if (resolvedConfig) await composeCloudflareSandbox(resolvedConfig, prepared, true);
|
|
3615
|
+
const currentFiles = [...generatedFiles, ...Object.values(generatedAliases)];
|
|
3616
|
+
const currentResolvedFiles = await resolveGeneratedSandboxTaskModuleIds(currentFiles);
|
|
3617
|
+
invalidateGeneratedSandboxTaskModules([
|
|
3618
|
+
...previousFiles,
|
|
3619
|
+
...previousResolvedFiles,
|
|
3620
|
+
...currentFiles,
|
|
3621
|
+
...currentResolvedFiles
|
|
3622
|
+
], context.server.moduleGraph);
|
|
3623
|
+
return prepared;
|
|
3624
|
+
});
|
|
3625
|
+
},
|
|
3626
|
+
configEnvironment(name, config) {
|
|
3627
|
+
const result = config.consumer === "server" ? { define: { __VITEHUB_ENVIRONMENT_SANDBOX__: JSON.stringify(name) } } : void 0;
|
|
3628
|
+
if (!isServerEnvironment(name, config)) return result;
|
|
3629
|
+
return {
|
|
3630
|
+
...result,
|
|
3631
|
+
resolve: {
|
|
3632
|
+
alias: toSandboxTaskAliasEntries({
|
|
3633
|
+
[SANDBOX_PROVIDER_LOADER_ID]: sandboxTaskProviderLoaderFallback(),
|
|
3634
|
+
...generatedAliases
|
|
3635
|
+
}),
|
|
3636
|
+
noExternal: mergeSandboxTaskNoExternal(config.resolve?.noExternal)
|
|
3637
|
+
}
|
|
3638
|
+
};
|
|
3639
|
+
}
|
|
3640
|
+
};
|
|
3641
|
+
}
|
|
3642
|
+
//#endregion
|
|
3643
|
+
export { discoverSandboxTaskDefinitions, hubSandboxTask, inspectSandboxTaskDefinitions, sandboxTaskConsoleSection };
|