@vite-hub/sandbox 0.0.4 → 0.3.0

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