@vite-hub/sandbox 0.0.4 → 0.1.0

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