@vite-hub/sandbox 0.0.0 → 0.0.1

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 (35) hide show
  1. package/README.md +56 -1
  2. package/dist/_shared-CJ2_pS4E.js +53 -0
  3. package/dist/cloudflare-retry-Cfra7MvS.js +21 -0
  4. package/dist/common-CS4FcWrh.d.ts +369 -0
  5. package/dist/index-B4j3Mvzr.d.ts +146 -0
  6. package/dist/index.d.ts +74 -0
  7. package/dist/index.js +785 -0
  8. package/dist/integration-wkNE8jMO.js +2032 -0
  9. package/dist/module-types-BomzaqnM.js +7 -0
  10. package/dist/module-types-CUcY8iuI.d.ts +88 -0
  11. package/dist/nitro.d.ts +19 -0
  12. package/dist/nitro.js +488 -0
  13. package/dist/provider-detection-IbezCeoR.js +25 -0
  14. package/dist/runtime/empty-registry.d.ts +6 -0
  15. package/dist/runtime/empty-registry.js +20 -0
  16. package/dist/runtime/nitro-plugin.d.ts +4 -0
  17. package/dist/runtime/nitro-plugin.js +8 -0
  18. package/dist/runtime/provider-loader.d.ts +17 -0
  19. package/dist/runtime/provider-loader.js +21 -0
  20. package/dist/runtime/providers/cloudflare.d.ts +35 -0
  21. package/dist/runtime/providers/cloudflare.js +22 -0
  22. package/dist/runtime/providers/vercel.d.ts +21 -0
  23. package/dist/runtime/providers/vercel.js +65 -0
  24. package/dist/runtime/state.d.ts +17 -0
  25. package/dist/runtime/state.js +21 -0
  26. package/dist/sandbox/providers/cloudflare.d.ts +7 -0
  27. package/dist/sandbox/providers/cloudflare.js +339 -0
  28. package/dist/sandbox/providers/vercel.d.ts +17 -0
  29. package/dist/sandbox/providers/vercel.js +538 -0
  30. package/dist/shared-pqTHYWg1.d.ts +8 -0
  31. package/dist/utils-V7ODsDW_.js +44 -0
  32. package/dist/vercel-runtime-BPzvh_6V.js +11 -0
  33. package/dist/vite.d.ts +40 -0
  34. package/dist/vite.js +441 -0
  35. package/package.json +103 -5
@@ -0,0 +1,2032 @@
1
+ import { t as getSandboxFeatureProvider } from "./module-types-BomzaqnM.js";
2
+ import { builtinModules, createRequire } from "node:module";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "pathe";
4
+ import { readPackageJSON } from "pkg-types";
5
+ import { existsSync } from "node:fs";
6
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import { createUnimport } from "unimport";
9
+ import { build } from "esbuild";
10
+ import { resolveModule } from "local-pkg";
11
+ import { resolvePathSync } from "mlly";
12
+ import { resolveModulePath } from "exsolve";
13
+ //#region src/internal/shared/discovered-definition/bundler.ts
14
+ const builtinModuleSet = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
15
+ function resolveDefinitionLoader(options) {
16
+ let loader = options.loader;
17
+ if (!loader) {
18
+ const f = options.filename;
19
+ if (f.endsWith(".tsx")) loader = "tsx";
20
+ else if (f.endsWith(".jsx")) loader = "jsx";
21
+ else if (f.endsWith(".js") || f.endsWith(".mjs") || f.endsWith(".cjs")) loader = "js";
22
+ else loader = "ts";
23
+ }
24
+ return loader;
25
+ }
26
+ function isJsxDefinitionLoader(options) {
27
+ const loader = resolveDefinitionLoader(options);
28
+ return loader === "tsx" || loader === "jsx";
29
+ }
30
+ async function bundleDiscoveredDefinitionModule(options) {
31
+ const output = (await build({
32
+ stdin: {
33
+ contents: options.source,
34
+ loader: resolveDefinitionLoader(options),
35
+ resolveDir: dirname(options.filename),
36
+ sourcefile: options.filename
37
+ },
38
+ bundle: true,
39
+ write: false,
40
+ format: "esm",
41
+ platform: "node",
42
+ target: "es2022",
43
+ logLevel: "silent",
44
+ jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
45
+ jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
46
+ packages: options.packages === "external" ? "external" : void 0,
47
+ external: [...builtinModuleSet, ...options.external || []],
48
+ plugins: options.plugins
49
+ })).outputFiles?.[0]?.text;
50
+ if (!output) throw new Error(`[vitehub] Failed to bundle discovered definition "${options.filename}".`);
51
+ return output;
52
+ }
53
+ async function bundleDiscoveredDefinitionModuleGraph(options) {
54
+ const outdir = resolve(dirname(options.filename), ".vitehub-discovered-definition");
55
+ const result = await build({
56
+ stdin: {
57
+ contents: options.source,
58
+ loader: resolveDefinitionLoader(options),
59
+ resolveDir: dirname(options.filename),
60
+ sourcefile: options.filename
61
+ },
62
+ bundle: true,
63
+ splitting: true,
64
+ entryNames: "definition",
65
+ chunkNames: "chunks/[name]-[hash]",
66
+ outdir,
67
+ write: false,
68
+ format: "esm",
69
+ platform: "node",
70
+ target: "es2022",
71
+ logLevel: "silent",
72
+ jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
73
+ jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
74
+ packages: options.packages === "external" ? "external" : void 0,
75
+ external: [...builtinModuleSet, ...options.external || []],
76
+ plugins: options.plugins
77
+ });
78
+ const modules = Object.fromEntries((result.outputFiles || []).map((outputFile) => {
79
+ return [relative(outdir, outputFile.path), outputFile.text];
80
+ }));
81
+ if (!modules["definition.js"]) throw new Error(`[vitehub] Failed to bundle discovered definition graph "${options.filename}".`);
82
+ return {
83
+ entry: "definition.js",
84
+ modules
85
+ };
86
+ }
87
+ //#endregion
88
+ //#region src/internal/shared/discovered-definition/ast.ts
89
+ const typescript = createRequire(import.meta.url)("typescript");
90
+ function resolveImportLocalName(entry) {
91
+ return entry.as || entry.name;
92
+ }
93
+ function getScriptKind(id) {
94
+ const scriptKind = typescript.ScriptKind;
95
+ if (id.endsWith(".tsx")) return typescript.ScriptKind.TSX;
96
+ if (id.endsWith(".jsx")) return typescript.ScriptKind.JSX;
97
+ if (id.endsWith(".mts")) return scriptKind.MTS ?? typescript.ScriptKind.TS;
98
+ if (id.endsWith(".cts")) return scriptKind.CTS ?? typescript.ScriptKind.TS;
99
+ if (id.endsWith(".mjs")) return typescript.ScriptKind.JS;
100
+ if (id.endsWith(".cjs")) return typescript.ScriptKind.JS;
101
+ if (id.endsWith(".js")) return typescript.ScriptKind.JS;
102
+ return typescript.ScriptKind.TS;
103
+ }
104
+ function createSourceFile(id, source) {
105
+ return typescript.createSourceFile(id, source, typescript.ScriptTarget.Latest, true, getScriptKind(id));
106
+ }
107
+ function collectExplicitImportNames(sourceFile) {
108
+ const names = /* @__PURE__ */ new Set();
109
+ for (const statement of sourceFile.statements) {
110
+ if (!typescript.isImportDeclaration(statement)) continue;
111
+ const clause = statement.importClause;
112
+ if (!clause) continue;
113
+ if (clause.name) names.add(clause.name.text);
114
+ const bindings = clause.namedBindings;
115
+ if (!bindings) continue;
116
+ if (typescript.isNamespaceImport(bindings)) {
117
+ names.add(bindings.name.text);
118
+ continue;
119
+ }
120
+ for (const element of bindings.elements) names.add(element.name.text);
121
+ }
122
+ return names;
123
+ }
124
+ function collectDeclaredTypeNames(sourceFile) {
125
+ const names = /* @__PURE__ */ new Set();
126
+ function visit(node) {
127
+ if ((typescript.isInterfaceDeclaration(node) || typescript.isTypeAliasDeclaration(node) || typescript.isClassDeclaration(node) || typescript.isEnumDeclaration(node)) && node.name) names.add(node.name.text);
128
+ 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);
129
+ typescript.forEachChild(node, visit);
130
+ }
131
+ visit(sourceFile);
132
+ return names;
133
+ }
134
+ function collectTypeReferenceNames(sourceFile) {
135
+ const names = /* @__PURE__ */ new Set();
136
+ function addEntityName(name) {
137
+ if (typescript.isIdentifier(name)) names.add(name.text);
138
+ }
139
+ function visit(node) {
140
+ if (typescript.isImportTypeNode(node) || typescript.isTypeQueryNode(node)) return;
141
+ if (typescript.isTypeReferenceNode(node)) {
142
+ addEntityName(node.typeName);
143
+ node.typeArguments?.forEach((argument) => visit(argument));
144
+ return;
145
+ }
146
+ if (typescript.isExpressionWithTypeArguments(node)) {
147
+ if (typescript.isIdentifier(node.expression)) names.add(node.expression.text);
148
+ node.typeArguments?.forEach((argument) => visit(argument));
149
+ return;
150
+ }
151
+ typescript.forEachChild(node, visit);
152
+ }
153
+ visit(sourceFile);
154
+ return names;
155
+ }
156
+ function groupTypeImports(imports) {
157
+ const grouped = /* @__PURE__ */ new Map();
158
+ for (const entry of imports) {
159
+ const from = entry.typeFrom || entry.from;
160
+ const entries = grouped.get(from);
161
+ if (entries) {
162
+ entries.push(entry);
163
+ continue;
164
+ }
165
+ grouped.set(from, [entry]);
166
+ }
167
+ return grouped;
168
+ }
169
+ function stringifyTypeImport(entry) {
170
+ const localName = resolveImportLocalName(entry);
171
+ if (localName === entry.name) return entry.name;
172
+ return `${entry.name} as ${localName}`;
173
+ }
174
+ function injectTypeImports(source, imports, id) {
175
+ if (!imports.length) return source;
176
+ const importStatements = createSourceFile(id, source).statements.filter(typescript.isImportDeclaration);
177
+ const groupedImports = groupTypeImports(imports);
178
+ const block = Array.from(groupedImports.entries()).map(([from, entries]) => `import type { ${entries.map(stringifyTypeImport).join(", ")} } from ${JSON.stringify(from)}`).join("\n");
179
+ if (!block) return source;
180
+ const insertAt = importStatements.at(-1)?.end ?? (source.startsWith("#!") ? source.indexOf("\n") + 1 : 0);
181
+ const prefix = source.slice(0, insertAt);
182
+ const suffix = source.slice(insertAt);
183
+ const needsLeadingNewline = insertAt > 0 && !prefix.endsWith("\n");
184
+ const needsTrailingNewline = suffix.length > 0 && !suffix.startsWith("\n");
185
+ return `${prefix}${needsLeadingNewline ? "\n" : ""}${block}${needsTrailingNewline ? "\n" : ""}${suffix}`;
186
+ }
187
+ async function injectTypeImportsFromUnimport(source, id, imports) {
188
+ const sourceFile = createSourceFile(id, source);
189
+ const explicitImports = collectExplicitImportNames(sourceFile);
190
+ const declaredTypes = collectDeclaredTypeNames(sourceFile);
191
+ const usedTypes = collectTypeReferenceNames(sourceFile);
192
+ const pendingImports = [];
193
+ for (const entry of imports) {
194
+ if (!entry.type || entry.disabled) continue;
195
+ const localName = resolveImportLocalName(entry);
196
+ if (!usedTypes.has(localName)) continue;
197
+ if (explicitImports.has(localName) || declaredTypes.has(localName)) continue;
198
+ pendingImports.push(entry);
199
+ explicitImports.add(localName);
200
+ }
201
+ return injectTypeImports(source, pendingImports, id);
202
+ }
203
+ //#endregion
204
+ //#region src/internal/shared/server-imports.ts
205
+ function isNitroAutoImportEnabled(imports) {
206
+ return imports !== false && imports?.autoImport !== false;
207
+ }
208
+ function getServerImportKey(entry) {
209
+ return [
210
+ entry.from,
211
+ entry.name,
212
+ entry.as || "",
213
+ entry.type ? "type" : "value"
214
+ ].join(":");
215
+ }
216
+ function normalizePresetImport$1(from, entry) {
217
+ if (typeof entry === "string") return {
218
+ from,
219
+ name: entry
220
+ };
221
+ return {
222
+ from,
223
+ name: entry.name,
224
+ ...entry.as ? { as: entry.as } : {},
225
+ ...entry.type ? { type: true } : {}
226
+ };
227
+ }
228
+ function isInlinePreset$1(value) {
229
+ return !!value && typeof value === "object" && typeof value.from === "string" && Array.isArray(value.imports);
230
+ }
231
+ function isPresetImport$1(value) {
232
+ return !!value && typeof value === "object" && typeof value.name === "string";
233
+ }
234
+ function collectPresetImports(from, entry, normalized) {
235
+ if (typeof entry === "string") {
236
+ normalized.push(normalizePresetImport$1(from, entry));
237
+ return;
238
+ }
239
+ if (isInlinePreset$1(entry)) {
240
+ for (const nested of entry.imports) collectPresetImports(entry.from, nested, normalized);
241
+ return;
242
+ }
243
+ if (isPresetImport$1(entry)) normalized.push(normalizePresetImport$1(from, entry));
244
+ }
245
+ function toPresetImport(entry) {
246
+ if (!entry.as && !entry.type) return entry.name;
247
+ return {
248
+ name: entry.name,
249
+ ...entry.as ? { as: entry.as } : {},
250
+ ...entry.type ? { type: true } : {}
251
+ };
252
+ }
253
+ function dedupeServerImports(imports) {
254
+ const seen = /* @__PURE__ */ new Set();
255
+ const deduped = [];
256
+ for (const entry of imports) {
257
+ const key = getServerImportKey(entry);
258
+ if (seen.has(key)) continue;
259
+ seen.add(key);
260
+ deduped.push(entry);
261
+ }
262
+ return deduped;
263
+ }
264
+ function readNitroServerImports(imports) {
265
+ if (typeof imports === "undefined" || imports === false) return [];
266
+ const normalized = [];
267
+ for (const preset of imports.presets || []) {
268
+ if (!isInlinePreset$1(preset)) continue;
269
+ for (const entry of preset.imports) collectPresetImports(preset.from, entry, normalized);
270
+ }
271
+ return normalized;
272
+ }
273
+ function groupServerImportsIntoNitroPresets(imports) {
274
+ const grouped = /* @__PURE__ */ new Map();
275
+ for (const entry of imports) {
276
+ const items = grouped.get(entry.from) || [];
277
+ items.push(toPresetImport(entry));
278
+ grouped.set(entry.from, items);
279
+ }
280
+ return Array.from(grouped, ([from, entries]) => ({
281
+ from,
282
+ imports: entries
283
+ }));
284
+ }
285
+ function mergeNitroImportsWithServerImports(imports, serverImports) {
286
+ if (serverImports.length === 0) return imports;
287
+ if (imports === false) return false;
288
+ if (!isNitroAutoImportEnabled(imports)) return imports;
289
+ const mergedImports = dedupeServerImports([...readNitroServerImports(imports), ...serverImports]);
290
+ return {
291
+ ...imports,
292
+ presets: groupServerImportsIntoNitroPresets(mergedImports)
293
+ };
294
+ }
295
+ function applyServerImportsToNitro(target, serverImports) {
296
+ if (serverImports.length === 0) return target.imports;
297
+ if (target.imports === false) return false;
298
+ if (!isNitroAutoImportEnabled(target.imports)) return target.imports;
299
+ target.imports = mergeNitroImportsWithServerImports(target.imports, serverImports);
300
+ return target.imports;
301
+ }
302
+ //#endregion
303
+ //#region src/internal/shared/discovered-definition.ts
304
+ function normalizeDir(rootDir, dir) {
305
+ if (typeof dir === "string") return isAbsolute(dir) ? dir : resolve(rootDir, dir);
306
+ return {
307
+ ...dir,
308
+ glob: isAbsolute(dir.glob) ? dir.glob : resolve(rootDir, dir.glob)
309
+ };
310
+ }
311
+ function normalizePresetImport(from, entry) {
312
+ if (typeof entry === "string") return {
313
+ from,
314
+ name: entry
315
+ };
316
+ return {
317
+ from,
318
+ name: entry.name,
319
+ ...entry.as ? { as: entry.as } : {},
320
+ ...entry.type ? { type: true } : {}
321
+ };
322
+ }
323
+ function normalizeServerImport(entry) {
324
+ return {
325
+ from: entry.from,
326
+ name: entry.name,
327
+ ...entry.as ? { as: entry.as } : {},
328
+ ...entry.type ? { type: true } : {}
329
+ };
330
+ }
331
+ function resolveDefaultImportDirs(rootDir, scanRoots) {
332
+ return scanRoots.flatMap((scanRoot) => [normalizeDir(rootDir, join(scanRoot, "server/utils/**/*")), normalizeDir(rootDir, join(scanRoot, "shared/types/**/*"))]);
333
+ }
334
+ function isInlinePreset(value) {
335
+ return !!value && typeof value === "object" && typeof value.from === "string" && Array.isArray(value.imports);
336
+ }
337
+ function isPresetImport(value) {
338
+ return !!value && typeof value === "object" && typeof value.name === "string";
339
+ }
340
+ function normalizePresetImports(presets = []) {
341
+ const normalized = [];
342
+ function collect(from, entry) {
343
+ if (typeof entry === "string") {
344
+ normalized.push(normalizePresetImport(from, entry));
345
+ return;
346
+ }
347
+ if (isInlinePreset(entry)) {
348
+ for (const nested of entry.imports) collect(entry.from, nested);
349
+ return;
350
+ }
351
+ if (isPresetImport(entry)) normalized.push(normalizePresetImport(from, entry));
352
+ }
353
+ for (const preset of presets) {
354
+ if (!isInlinePreset(preset)) continue;
355
+ for (const entry of preset.imports) collect(preset.from, entry);
356
+ }
357
+ return normalized;
358
+ }
359
+ async function createInitializedUnimport(options) {
360
+ const nitroImports = options.nitroImports !== false ? options.nitroImports : void 0;
361
+ const unimport = createUnimport({
362
+ imports: [...normalizePresetImports(nitroImports?.presets), ...(options.featureImports || []).map(normalizeServerImport)],
363
+ dirs: [...resolveDefaultImportDirs(options.rootDir, options.scanRoots), ...(nitroImports?.dirs || []).map((dir) => normalizeDir(options.rootDir, dir))]
364
+ });
365
+ await unimport.init();
366
+ return unimport;
367
+ }
368
+ async function createDiscoveredDefinitionCompiler(options = {}) {
369
+ const resolvedOptions = {
370
+ rootDir: options.rootDir || process.cwd(),
371
+ scanRoots: options.scanRoots || [],
372
+ nitroImports: options.nitroImports,
373
+ featureImports: options.featureImports || []
374
+ };
375
+ if (!isNitroAutoImportEnabled(resolvedOptions.nitroImports)) return {
376
+ enabled: false,
377
+ async injectSource(source) {
378
+ return source;
379
+ },
380
+ async readSource(id) {
381
+ return await readFile(id, "utf8");
382
+ },
383
+ async bundleModule(bundleOptions) {
384
+ return await bundleDiscoveredDefinitionModule(bundleOptions);
385
+ }
386
+ };
387
+ const unimport = await createInitializedUnimport(resolvedOptions);
388
+ const injectSource = async (source, id) => {
389
+ return await injectTypeImportsFromUnimport((await unimport.injectImports(source, id)).code, id, await unimport.getImports());
390
+ };
391
+ return {
392
+ enabled: true,
393
+ injectSource,
394
+ async readSource(id) {
395
+ return await injectSource(await readFile(id, "utf8"), id);
396
+ },
397
+ async bundleModule(bundleOptions) {
398
+ return await bundleDiscoveredDefinitionModule(bundleOptions);
399
+ }
400
+ };
401
+ }
402
+ //#endregion
403
+ //#region src/internal/shared/module-resolve.ts
404
+ function normalizePaths(paths) {
405
+ if (paths?.length) return paths;
406
+ if (typeof process !== "undefined") return [process.cwd()];
407
+ return [];
408
+ }
409
+ function tryResolveFromRuntime(id) {
410
+ const requireResolver = globalThis.require?.resolve;
411
+ if (typeof requireResolver !== "function") return void 0;
412
+ try {
413
+ return requireResolver(id);
414
+ } catch {
415
+ return false;
416
+ }
417
+ }
418
+ function tryResolveModule(id, options = {}) {
419
+ const paths = normalizePaths(options.paths);
420
+ const runtimeResolved = tryResolveFromRuntime(id);
421
+ if (runtimeResolved === false) return {
422
+ ok: false,
423
+ error: `Unable to resolve module "${id}" using the active runtime resolver`
424
+ };
425
+ if (runtimeResolved) return {
426
+ ok: true,
427
+ path: runtimeResolved
428
+ };
429
+ const resolved = resolveModule(id, { paths });
430
+ if (resolved) return {
431
+ ok: true,
432
+ path: resolved
433
+ };
434
+ for (const url of paths) try {
435
+ return {
436
+ ok: true,
437
+ path: resolvePathSync(id, { url })
438
+ };
439
+ } catch {
440
+ continue;
441
+ }
442
+ return {
443
+ ok: false,
444
+ error: paths.length > 0 ? `Unable to resolve module "${id}" from ${paths.join(", ")}` : `Unable to resolve module "${id}" without explicit resolution paths`
445
+ };
446
+ }
447
+ //#endregion
448
+ //#region src/internal/shared/dependency.ts
449
+ function hasInstalledDependency(deps, dependency, options) {
450
+ return Boolean(deps[dependency]) || tryResolveModule(dependency, options).ok;
451
+ }
452
+ //#endregion
453
+ //#region src/internal/shared/feature-definitions.ts
454
+ const definitionExtensions = new Set([
455
+ ".ts",
456
+ ".mts",
457
+ ".js",
458
+ ".mjs"
459
+ ]);
460
+ function hasSupportedDefinitionExtension(file) {
461
+ for (const extension of definitionExtensions) if (file.endsWith(extension)) return true;
462
+ return false;
463
+ }
464
+ async function walkDefinitions(dir, out = []) {
465
+ if (!existsSync(dir)) return out;
466
+ const entries = await readdir(dir, { withFileTypes: true });
467
+ for (const entry of entries) {
468
+ if (entry.name.startsWith(".")) continue;
469
+ const full = join(dir, entry.name);
470
+ if (entry.isDirectory()) {
471
+ await walkDefinitions(full, out);
472
+ continue;
473
+ }
474
+ if (entry.isFile() && hasSupportedDefinitionExtension(entry.name)) out.push(full);
475
+ }
476
+ return out;
477
+ }
478
+ async function walkFlatDefinitions(dir, filter, out = []) {
479
+ if (!existsSync(dir)) return out;
480
+ const entries = await readdir(dir, { withFileTypes: true });
481
+ for (const entry of entries) {
482
+ if (entry.name.startsWith(".")) continue;
483
+ const full = join(dir, entry.name);
484
+ if (entry.isFile() && filter(entry.name)) out.push(full);
485
+ }
486
+ return out;
487
+ }
488
+ function resolveNitroScanRoots(nitro) {
489
+ return Array.from(new Set([nitro.options.rootDir, nitro.options.srcDir ? resolve(nitro.options.rootDir, nitro.options.srcDir) : nitro.options.rootDir]));
490
+ }
491
+ function normalizeDefinitionName(relativePath) {
492
+ let normalized = relativePath.replace(/\\/g, "/");
493
+ normalized = normalized.replace(/\.[a-z0-9]+$/i, "");
494
+ normalized = normalized.replace(/\/index$/, "");
495
+ return normalized;
496
+ }
497
+ function resolveFlatDefinitionSuffix(subdir) {
498
+ if (subdir === "sandboxes") return ".sandbox";
499
+ if (!subdir.endsWith("s")) return void 0;
500
+ return `.${subdir.slice(0, -1)}`;
501
+ }
502
+ function isFlatRootDefinitionFile(file, subdir) {
503
+ const suffix = resolveFlatDefinitionSuffix(subdir);
504
+ if (!suffix) return false;
505
+ for (const extension of definitionExtensions) if (file.endsWith(`${suffix}${extension}`)) return true;
506
+ return false;
507
+ }
508
+ function normalizeFlatDefinitionName(relativePath, subdir) {
509
+ const normalized = normalizeDefinitionName(relativePath);
510
+ const suffix = resolveFlatDefinitionSuffix(subdir);
511
+ if (!suffix || !normalized.endsWith(suffix)) return normalized;
512
+ return normalized.slice(0, -suffix.length);
513
+ }
514
+ function toTemplateSafeName(name) {
515
+ return name.replace(/[^a-z0-9/_:-]/gi, "_").replace(/\//g, "__").replace(/:/g, "__");
516
+ }
517
+ function normalizeDefinitionFilename(filename, subdir, srcScan) {
518
+ if (srcScan?.normalizeName && srcScan.filter(filename)) return srcScan.normalizeName(filename);
519
+ return normalizeFlatDefinitionName(filename, subdir);
520
+ }
521
+ async function loadFeatureDefinitions(options) {
522
+ const definitions = [];
523
+ const normalizeName = options.normalizeName || normalizeDefinitionName;
524
+ const scannedDirs = /* @__PURE__ */ new Set();
525
+ const scannedFiles = /* @__PURE__ */ new Set();
526
+ for (const scanRoot of options.scanRoots) {
527
+ const definitionDirs = basename(scanRoot) === "src" && options.srcScan ? [join(scanRoot, "server", options.subdir)] : [join(scanRoot, options.subdir), join(scanRoot, "server", options.subdir)];
528
+ for (const definitionDir of definitionDirs) {
529
+ if (scannedDirs.has(definitionDir)) continue;
530
+ scannedDirs.add(definitionDir);
531
+ const files = await walkDefinitions(definitionDir);
532
+ for (const file of files) {
533
+ if (scannedFiles.has(file)) continue;
534
+ scannedFiles.add(file);
535
+ const filename = relative(definitionDir, file).split(sep).join("/");
536
+ definitions.push({
537
+ name: basename(scanRoot) === "src" && options.srcScan ? normalizeDefinitionFilename(filename, options.subdir, options.srcScan) : normalizeName(filename),
538
+ handler: file,
539
+ _meta: {
540
+ filename,
541
+ sourcePath: file
542
+ }
543
+ });
544
+ }
545
+ }
546
+ if (basename(scanRoot) !== "src") continue;
547
+ const srcScan = options.srcScan;
548
+ const files = srcScan ? await (srcScan.mode === "recursive" ? walkDefinitions(scanRoot) : walkFlatDefinitions(scanRoot, (file) => hasSupportedDefinitionExtension(file))) : await walkFlatDefinitions(scanRoot, (file) => hasSupportedDefinitionExtension(file) && isFlatRootDefinitionFile(file, options.subdir));
549
+ for (const file of files) {
550
+ const filename = relative(scanRoot, file).split(sep).join("/");
551
+ if (srcScan && !srcScan.filter(filename)) continue;
552
+ if (scannedFiles.has(file)) continue;
553
+ scannedFiles.add(file);
554
+ definitions.push({
555
+ name: srcScan?.normalizeName ? srcScan.normalizeName(filename) : normalizeFlatDefinitionName(filename, options.subdir),
556
+ handler: file,
557
+ _meta: {
558
+ filename,
559
+ sourcePath: file
560
+ }
561
+ });
562
+ }
563
+ }
564
+ definitions.sort((left, right) => {
565
+ if (left.name === right.name) return left._meta.sourcePath.localeCompare(right._meta.sourcePath);
566
+ return left.name.localeCompare(right.name);
567
+ });
568
+ assertNoDuplicateDefinitionNames(options.feature, definitions);
569
+ return {
570
+ feature: options.feature,
571
+ subdir: options.subdir,
572
+ definitions
573
+ };
574
+ }
575
+ function assertNoDuplicateDefinitionNames(feature, definitions) {
576
+ const seen = /* @__PURE__ */ new Map();
577
+ for (const definition of definitions) {
578
+ const existing = seen.get(definition.name);
579
+ if (existing) throw new Error(`[vitehub] Duplicate ${feature} definition "${definition.name}" found in:\n- ${existing}\n- ${definition._meta.sourcePath}`);
580
+ seen.set(definition.name, definition._meta.sourcePath);
581
+ }
582
+ }
583
+ //#endregion
584
+ //#region src/internal/shared/feature-runtime-path.ts
585
+ function resolveExistingModulePath(path) {
586
+ if (existsSync(path)) return path;
587
+ for (const extension of [
588
+ ".ts",
589
+ ".mts",
590
+ ".js",
591
+ ".mjs"
592
+ ]) {
593
+ const withExtension = `${path}${extension}`;
594
+ if (existsSync(withExtension)) return withExtension;
595
+ }
596
+ }
597
+ function resolveFeatureRuntimePath(importMetaUrl, packageId, sourceRelativePath, distRelativePath) {
598
+ const importerDir = dirname(fileURLToPath(importMetaUrl));
599
+ const sourcePath = resolve(importerDir, sourceRelativePath);
600
+ const importerUsesDist = importerDir.split(sep).includes("dist");
601
+ const targetsSourceTree = /(?:^|\/)\.\.\/src(?:\/|$)|^\.\/*src(?:\/|$)/.test(sourceRelativePath);
602
+ const resolvedSourcePath = resolveExistingModulePath(sourcePath);
603
+ if ((!importerUsesDist || !targetsSourceTree) && resolvedSourcePath) return resolvedSourcePath;
604
+ const resolvedPackageJson = tryResolveModule(`${packageId}/package.json`);
605
+ if (resolvedPackageJson.ok) {
606
+ const resolvedPackageSourcePath = resolveExistingModulePath(join(dirname(resolvedPackageJson.path), "src", sourceRelativePath.replace(/^(\.\.\/)+src\//, "").replace(/^\.\//, "")));
607
+ if ((!importerUsesDist || !targetsSourceTree) && resolvedPackageSourcePath) return resolvedPackageSourcePath;
608
+ return join(dirname(resolvedPackageJson.path), "dist", distRelativePath);
609
+ }
610
+ const resolvedPackage = tryResolveModule(packageId);
611
+ if (resolvedPackage.ok) return join(dirname(resolvedPackage.path), distRelativePath);
612
+ return sourcePath;
613
+ }
614
+ //#endregion
615
+ //#region src/internal/shared/hosting.ts
616
+ function normalizeHosting(hosting) {
617
+ const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
618
+ if (normalized === "cloudflare") return "cloudflare-module";
619
+ return normalized;
620
+ }
621
+ function detectHosting(target) {
622
+ return normalizeHosting(target.options.nitro?.preset || target.options.preset || detectPresetArg() || process.env.NITRO_PRESET || process.env.VITEHUB_HOSTING || "");
623
+ }
624
+ function detectPresetArg() {
625
+ const argv = process.argv || [];
626
+ for (let index = 0; index < argv.length; index++) {
627
+ const arg = argv[index];
628
+ if (arg === "--preset") return argv[index + 1] || "";
629
+ if (arg?.startsWith("--preset=")) return arg.slice(9);
630
+ }
631
+ return "";
632
+ }
633
+ function getHostingProvider(hosting) {
634
+ const normalized = normalizeHosting(hosting);
635
+ if (!normalized) return void 0;
636
+ if (normalized.startsWith("cloudflare")) return "cloudflare";
637
+ if (normalized.startsWith("vercel")) return "vercel";
638
+ if (normalized.startsWith("netlify")) return "netlify";
639
+ }
640
+ function getSupportedHostingProvider(hosting, supportedProviders) {
641
+ const provider = getHostingProvider(hosting);
642
+ if (!provider || !supportedProviders.includes(provider)) return void 0;
643
+ return provider;
644
+ }
645
+ //#endregion
646
+ //#region src/bundle.ts
647
+ const SHIM_NAMESPACE = "vitehub-sandbox-runtime-shim";
648
+ async function bundleSandboxDefinition(source, file) {
649
+ return await bundleDiscoveredDefinitionModuleGraph({
650
+ filename: file,
651
+ source,
652
+ plugins: [{
653
+ name: SHIM_NAMESPACE,
654
+ setup(pluginBuild) {
655
+ pluginBuild.onResolve({ filter: /^@vite-hub\/sandbox(?:\/runtime\/public)?$/ }, () => ({
656
+ path: "sandbox-runtime-shim",
657
+ namespace: SHIM_NAMESPACE
658
+ }));
659
+ pluginBuild.onLoad({
660
+ filter: /.*/,
661
+ namespace: SHIM_NAMESPACE
662
+ }, () => ({
663
+ contents: [
664
+ "function hasStandardValidator(value) {",
665
+ " return !!value && typeof value === \"object\" && !!value[\"~standard\"] && typeof value[\"~standard\"].validate === \"function\"",
666
+ "}",
667
+ "",
668
+ "function createValidationError(cause) {",
669
+ " if (cause instanceof Error)",
670
+ " return cause",
671
+ " const message = cause && typeof cause === \"object\" && typeof cause.message === \"string\"",
672
+ " ? cause.message",
673
+ " : \"Validation failed\"",
674
+ " return Object.assign(new Error(message), cause && typeof cause === \"object\" ? cause : {})",
675
+ "}",
676
+ "",
677
+ "export async function readValidatedPayload(payload, validate) {",
678
+ " if (hasStandardValidator(validate)) {",
679
+ " const result = await validate[\"~standard\"].validate(payload)",
680
+ " if (result.issues?.length)",
681
+ " throw createValidationError({ message: \"Validation failed\", issues: result.issues })",
682
+ " return result.value",
683
+ " }",
684
+ " try {",
685
+ " const result = await validate(payload)",
686
+ " if (result === false)",
687
+ " throw createValidationError({ message: \"Validation failed\" })",
688
+ " return result === true || result == null ? payload : result",
689
+ " }",
690
+ " catch (error) {",
691
+ " throw createValidationError(error)",
692
+ " }",
693
+ "}",
694
+ "",
695
+ "export function defineSandbox(run, options) {",
696
+ " return { run, options }",
697
+ "}"
698
+ ].join("\n"),
699
+ loader: "js"
700
+ }));
701
+ }
702
+ }]
703
+ });
704
+ }
705
+ //#endregion
706
+ //#region src/cloudflare.ts
707
+ const defaultCloudflareSandboxBinding = "SANDBOX";
708
+ const defaultCloudflareSandboxClassName = "Sandbox";
709
+ const defaultCloudflareSandboxMaxInstances = 12;
710
+ const require$1 = createRequire(import.meta.url);
711
+ function resolveCloudflareSandboxEntrypoint() {
712
+ try {
713
+ return require$1.resolve("@cloudflare/sandbox");
714
+ } catch {
715
+ return "@cloudflare/sandbox";
716
+ }
717
+ }
718
+ function resolveCloudflareSandboxVersion() {
719
+ try {
720
+ const pkg = require$1(join(require$1.resolve("@cloudflare/sandbox"), "..", "..", "package.json"));
721
+ return typeof pkg?.version === "string" ? pkg.version : "0.7.0";
722
+ } catch {
723
+ return "0.7.0";
724
+ }
725
+ }
726
+ function resolveCloudflareSandboxEntrypointOptions(options = {}) {
727
+ return {
728
+ binding: options.binding || "SANDBOX",
729
+ className: options.className || "Sandbox",
730
+ migrationTag: options.migrationTag || "v1",
731
+ name: options.name || void 0
732
+ };
733
+ }
734
+ function configureCloudflareSandbox(target, options = {}) {
735
+ const { binding, className, migrationTag, name } = resolveCloudflareSandboxEntrypointOptions(options);
736
+ target.cloudflare ||= {};
737
+ target.cloudflare.wrangler ||= {};
738
+ target.cloudflare.wrangler.containers ||= [];
739
+ target.cloudflare.wrangler.durable_objects ||= {};
740
+ target.cloudflare.wrangler.durable_objects.bindings ||= [];
741
+ target.cloudflare.wrangler.migrations ||= [];
742
+ const containers = target.cloudflare.wrangler.containers;
743
+ const image = "./Dockerfile";
744
+ if (!containers.some((entry) => entry.class_name === className)) containers.push({
745
+ class_name: className,
746
+ image,
747
+ instance_type: "lite",
748
+ max_instances: defaultCloudflareSandboxMaxInstances,
749
+ ...name ? { name } : {}
750
+ });
751
+ else for (const container of containers) {
752
+ if (container.class_name !== className) continue;
753
+ if (typeof container.image !== "string") container.image = image;
754
+ if (typeof container.max_instances !== "number" || container.max_instances < defaultCloudflareSandboxMaxInstances) container.max_instances = defaultCloudflareSandboxMaxInstances;
755
+ if (name && typeof container.name !== "string") container.name = name;
756
+ }
757
+ const bindings = target.cloudflare.wrangler.durable_objects.bindings;
758
+ if (!bindings.some((entry) => entry.name === binding && entry.class_name === className)) bindings.push({
759
+ name: binding,
760
+ class_name: className
761
+ });
762
+ const migrations = target.cloudflare.wrangler.migrations;
763
+ if (!migrations.some((entry) => Array.isArray(entry.new_sqlite_classes) && entry.new_sqlite_classes.includes(className))) migrations.push({
764
+ tag: migrationTag,
765
+ new_sqlite_classes: [className]
766
+ });
767
+ }
768
+ function createCloudflareSandboxRollupPlugin(options = {}) {
769
+ const { className } = resolveCloudflareSandboxEntrypointOptions(options);
770
+ const cloudflareSandboxEntrypoint = resolveCloudflareSandboxEntrypoint();
771
+ const moduleId = "virtual:vitehub-sandbox-cloudflare-exports";
772
+ const resolvedModuleId = "\0virtual:vitehub-sandbox-cloudflare-exports";
773
+ return {
774
+ name: "vitehub-sandbox-cloudflare-exports",
775
+ buildStart() {
776
+ this.emitFile({
777
+ type: "chunk",
778
+ id: moduleId,
779
+ fileName: "sandbox-cloudflare-exports.mjs"
780
+ });
781
+ },
782
+ resolveId(id) {
783
+ if (id === moduleId) return resolvedModuleId;
784
+ if (id === "@cloudflare/sandbox") return cloudflareSandboxEntrypoint;
785
+ },
786
+ load(id) {
787
+ if (id === resolvedModuleId) return [
788
+ `import { Sandbox as CloudflareSandbox } from '@cloudflare/sandbox'`,
789
+ ``,
790
+ `export class ${className} extends CloudflareSandbox {}`,
791
+ ``
792
+ ].join("\n");
793
+ },
794
+ renderChunk(code, chunk) {
795
+ if (!chunk.isEntry || chunk.fileName !== "index.mjs") return null;
796
+ return {
797
+ code: `${code}\nexport { ${className} } from './sandbox-cloudflare-exports.mjs'\n`,
798
+ map: null
799
+ };
800
+ }
801
+ };
802
+ }
803
+ function installCloudflareSandboxEntrypoint(target, options = {}) {
804
+ const { className } = resolveCloudflareSandboxEntrypointOptions(options);
805
+ target.rollupConfig ||= {};
806
+ const plugins = Array.isArray(target.rollupConfig.plugins) ? target.rollupConfig.plugins : [];
807
+ target.rollupConfig.plugins = plugins;
808
+ if (plugins.some((plugin) => typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === `vitehub-sandbox-cloudflare-exports:${className}`)) return;
809
+ const plugin = createCloudflareSandboxRollupPlugin({ className });
810
+ plugin.name = `vitehub-sandbox-cloudflare-exports:${className}`;
811
+ plugins.push(plugin);
812
+ }
813
+ async function writeCloudflareSandboxDockerfile(serverDir) {
814
+ await writeFile(join(serverDir, "Dockerfile"), `FROM docker.io/cloudflare/sandbox:${resolveCloudflareSandboxVersion()}\n`);
815
+ }
816
+ //#endregion
817
+ //#region src/definition-options.ts
818
+ const require = createRequire(import.meta.url);
819
+ const sandboxDefinitionSyntax = "`defineSandbox()`";
820
+ function getTypeScript() {
821
+ return require("typescript");
822
+ }
823
+ function getSandboxDefinitionOptionsCall(expression) {
824
+ const ts = getTypeScript();
825
+ if (ts.isCallExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === "defineSandbox") {
826
+ if (expression.arguments.length > 2) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} accepts at most one handler and one options object.`);
827
+ return expression.arguments[1] || null;
828
+ }
829
+ }
830
+ function readExportedOptionsExpression(sourceFile) {
831
+ const ts = getTypeScript();
832
+ for (const statement of sourceFile.statements) {
833
+ if (!ts.isExportAssignment(statement)) continue;
834
+ const options = getSandboxDefinitionOptionsCall(statement.expression);
835
+ if (typeof options !== "undefined") return options;
836
+ }
837
+ }
838
+ function readStaticValue(node) {
839
+ const ts = getTypeScript();
840
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
841
+ if (ts.isNumericLiteral(node)) return Number(node.text);
842
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
843
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
844
+ if (node.kind === ts.SyntaxKind.NullKeyword) return null;
845
+ if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(node.operand)) return -Number(node.operand.text);
846
+ if (ts.isParenthesizedExpression(node)) return readStaticValue(node.expression);
847
+ if (ts.isArrayLiteralExpression(node)) return node.elements.map((element) => {
848
+ if (!ts.isExpression(element)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options arrays must use static values.`);
849
+ return readStaticValue(element);
850
+ });
851
+ if (ts.isObjectLiteralExpression(node)) {
852
+ const value = {};
853
+ for (const property of node.properties) {
854
+ if (!ts.isPropertyAssignment(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use plain object literals.`);
855
+ const key = ts.isIdentifier(property.name) ? property.name.text : ts.isStringLiteral(property.name) ? property.name.text : void 0;
856
+ if (!key) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options only support identifier or string-literal keys.`);
857
+ value[key] = readStaticValue(property.initializer);
858
+ }
859
+ return value;
860
+ }
861
+ throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use static JSON-serializable values.`);
862
+ }
863
+ async function extractSandboxDefinitionOptions(file) {
864
+ const source = await readFile(file, "utf8");
865
+ const ts = getTypeScript();
866
+ const options = readExportedOptionsExpression(ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS));
867
+ if (typeof options === "undefined" || options === null) return void 0;
868
+ if (!ts.isObjectLiteralExpression(options)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must be an object literal.`);
869
+ return readStaticValue(options);
870
+ }
871
+ //#endregion
872
+ //#region src/internal/shared/nitro-config-template.ts
873
+ function createNitroConfigTypeAugmentation(configKey, typeImport, typeName, enabledType = `boolean | ${typeName}`) {
874
+ return [
875
+ `declare module 'nitro/types' {`,
876
+ ` interface NitroConfig {`,
877
+ ` ${configKey}?: ${enabledType}`,
878
+ ` }`,
879
+ ` interface NitroRuntimeConfig {`,
880
+ ` ${configKey}?: false | ${typeName}`,
881
+ ` }`,
882
+ `}`,
883
+ ``,
884
+ `export type { ${typeName} } from ${JSON.stringify(typeImport)}`,
885
+ ``
886
+ ].join("\n");
887
+ }
888
+ //#endregion
889
+ //#region src/type-template.ts
890
+ function createSandboxTypeTemplateContents(definitions) {
891
+ return [
892
+ createNitroConfigTypeAugmentation("sandbox", "@vite-hub/sandbox", "AgentSandboxConfig"),
893
+ `declare module '#vitehub-sandbox-registry' {`,
894
+ ` export interface SandboxDefinitionModules {`,
895
+ ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: typeof import(${JSON.stringify(definition.handler)}),`),
896
+ ` }`,
897
+ ` const sandboxRegistry: {`,
898
+ ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: () => Promise<{ default?: { bundle: import('@vite-hub/sandbox').SandboxDefinitionBundle, options?: import('@vite-hub/sandbox').SandboxDefinitionOptions } }>,`),
899
+ ` }`,
900
+ ` export default sandboxRegistry`,
901
+ `}`,
902
+ ``
903
+ ].join("\n");
904
+ }
905
+ //#endregion
906
+ //#region src/feature.ts
907
+ const sandboxRuntimeDependencies = ["@cloudflare/sandbox", "@vercel/sandbox"];
908
+ const sandboxRuntimeDependencyByProvider = {
909
+ cloudflare: "@cloudflare/sandbox",
910
+ vercel: "@vercel/sandbox"
911
+ };
912
+ const sandboxClientExportByProvider = {
913
+ cloudflare: "createCloudflareSandboxClient",
914
+ vercel: "createVercelSandboxClient"
915
+ };
916
+ function resolveSandboxProviderLoaderTarget(provider, deps) {
917
+ if (provider) return provider;
918
+ const hasCloudflareSandbox = Boolean(deps["@cloudflare/sandbox"]);
919
+ if (hasCloudflareSandbox === Boolean(deps["@vercel/sandbox"])) return void 0;
920
+ return hasCloudflareSandbox ? "cloudflare" : "vercel";
921
+ }
922
+ function createSandboxProviderLoaderAliases(defaultProviderName) {
923
+ const keys = [
924
+ "vitehub-sandbox-provider-loader",
925
+ "@vite-hub/sandbox/runtime/provider-loader",
926
+ "virtual:vitehub-sandbox-provider-loader",
927
+ "#vitehub-sandbox-provider-loader"
928
+ ];
929
+ if (defaultProviderName) return keys.map((key) => ({
930
+ key,
931
+ artifactKey: "sandbox-provider-loader"
932
+ }));
933
+ const providerLoaderPath = resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./runtime/provider-loader", "runtime/provider-loader.js");
934
+ return keys.map((key) => ({
935
+ key,
936
+ value: providerLoaderPath
937
+ }));
938
+ }
939
+ function createSandboxManifest(aliasPath, nitroPlugin, typeTemplate) {
940
+ return {
941
+ alias: "@vite-hub/sandbox",
942
+ aliasPath,
943
+ nitroPlugin,
944
+ imports: [
945
+ {
946
+ name: "defineSandbox",
947
+ from: "@vite-hub/sandbox",
948
+ meta: { description: "Define a named sandbox resource." }
949
+ },
950
+ {
951
+ name: "readValidatedPayload",
952
+ as: "readValidatedSandboxPayload",
953
+ from: "@vite-hub/sandbox",
954
+ meta: { description: "Validate sandbox payload input before execution." }
955
+ },
956
+ {
957
+ name: "runSandbox",
958
+ from: "@vite-hub/sandbox",
959
+ meta: { description: "Run a named sandbox definition." }
960
+ },
961
+ {
962
+ name: "SandboxDefinition",
963
+ as: "SandboxDefinition",
964
+ from: "@vite-hub/sandbox",
965
+ type: true
966
+ },
967
+ {
968
+ name: "SandboxRunResult",
969
+ as: "SandboxRunResult",
970
+ from: "@vite-hub/sandbox",
971
+ type: true
972
+ }
973
+ ],
974
+ typeTemplate: {
975
+ filename: "runtime/sandbox.d.ts",
976
+ contents: typeTemplate
977
+ }
978
+ };
979
+ }
980
+ function normalizeSandboxDefinitionOptions(name, options) {
981
+ if (!options) return void 0;
982
+ try {
983
+ return JSON.parse(JSON.stringify(options));
984
+ } catch (error) {
985
+ throw new Error(`[vitehub] Sandbox definition "${name}" options must be JSON-serializable.`, { cause: error });
986
+ }
987
+ }
988
+ async function loadSandboxDefinitionMetadata(definitions) {
989
+ return await Promise.all(definitions.map(async (definition) => {
990
+ return {
991
+ name: definition.name,
992
+ options: normalizeSandboxDefinitionOptions(definition.name, await extractSandboxDefinitionOptions(definition.handler))
993
+ };
994
+ }));
995
+ }
996
+ function createSandboxRegistryContents(definitions) {
997
+ return [
998
+ "const registry = {",
999
+ ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: async () => import(${JSON.stringify(definition.definitionModulePath)}),`),
1000
+ "}",
1001
+ "export default registry",
1002
+ ""
1003
+ ].join("\n");
1004
+ }
1005
+ function createSandboxProviderLoaderContents(provider) {
1006
+ const providerLoaderPath = resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", `./runtime/providers/${provider}`, `runtime/providers/${provider}.js`);
1007
+ const clientProviderPath = resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", `./sandbox/providers/${provider}`, `sandbox/providers/${provider}.js`);
1008
+ const clientExportName = sandboxClientExportByProvider[provider];
1009
+ return [
1010
+ `import { resolveSandboxProvider } from ${JSON.stringify(providerLoaderPath)}`,
1011
+ `import { ${clientExportName} } from ${JSON.stringify(clientProviderPath)}`,
1012
+ "",
1013
+ "export async function loadSandboxRuntimeProvider(selectedProvider) {",
1014
+ ` if (selectedProvider !== ${JSON.stringify(provider)})`,
1015
+ " throw new Error(`[vitehub] Unsupported sandbox provider for this Nitro build: ${selectedProvider}`)",
1016
+ " return {",
1017
+ " resolveSandboxProvider,",
1018
+ ` createSandboxClient: ${clientExportName},`,
1019
+ " }",
1020
+ "}",
1021
+ ""
1022
+ ].join("\n");
1023
+ }
1024
+ function resolveSandboxFeatureConfig(sandboxConfig, hosting) {
1025
+ if (getSandboxFeatureProvider(sandboxConfig)?.provider) return { ...sandboxConfig };
1026
+ const config = { ...sandboxConfig };
1027
+ const hostedProvider = getSupportedHostingProvider(hosting, ["cloudflare", "vercel"]);
1028
+ if (hostedProvider) return {
1029
+ ...config,
1030
+ provider: hostedProvider
1031
+ };
1032
+ if (getHostingProvider(hosting) === "netlify") throw new TypeError("[vitehub] Sandbox hosting inference does not support Netlify. Set `sandbox.provider` explicitly.");
1033
+ return config;
1034
+ }
1035
+ async function createSandboxFeaturePlan(sandboxConfig, definitions, paths, deps, hosting, discoveredDefinitionOptions = {}) {
1036
+ const resolvedConfig = resolveSandboxFeatureConfig(sandboxConfig, hosting);
1037
+ const manifest = createSandboxManifest(paths.aliasPath, paths.nitroPlugin, createSandboxTypeTemplateContents(definitions));
1038
+ const definitionCompiler = await createDiscoveredDefinitionCompiler(discoveredDefinitionOptions);
1039
+ const definitionMetadata = await loadSandboxDefinitionMetadata(definitions);
1040
+ const metadataByName = new Map(definitionMetadata.map((definition) => [definition.name, definition]));
1041
+ const sandboxDefinitions = definitions.map((definition) => ({
1042
+ ...definition,
1043
+ definitionArtifactKey: `sandbox-definition:${definition.name}`,
1044
+ definitionFilename: `runtime/sandbox-definitions/${toTemplateSafeName(definition.name)}.mjs`
1045
+ }));
1046
+ const sandboxArtifacts = sandboxDefinitions.map((definition) => ({
1047
+ key: definition.definitionArtifactKey,
1048
+ filename: definition.definitionFilename,
1049
+ async getContents() {
1050
+ const bundle = await bundleSandboxDefinition(await definitionCompiler.readSource(definition._meta.sourcePath), definition._meta.sourcePath);
1051
+ const metadata = metadataByName.get(definition.name);
1052
+ return `export default ${JSON.stringify({
1053
+ bundle,
1054
+ options: metadata?.options
1055
+ })}\n`;
1056
+ }
1057
+ }));
1058
+ const defaultProvider = getSandboxFeatureProvider(resolvedConfig);
1059
+ const defaultProviderName = defaultProvider?.provider;
1060
+ const providerLoaderTarget = resolveSandboxProviderLoaderTarget(defaultProviderName, deps);
1061
+ const cloudflareOptions = defaultProvider?.provider === "cloudflare" ? {
1062
+ binding: typeof defaultProvider.binding === "string" ? defaultProvider.binding : defaultCloudflareSandboxBinding,
1063
+ className: typeof defaultProvider.className === "string" ? defaultProvider.className : defaultCloudflareSandboxClassName,
1064
+ migrationTag: typeof defaultProvider.migrationTag === "string" ? defaultProvider.migrationTag : "v1",
1065
+ name: typeof defaultProvider.name === "string" ? defaultProvider.name : void 0
1066
+ } : void 0;
1067
+ return {
1068
+ manifest,
1069
+ aliases: [{
1070
+ key: "#vitehub-sandbox-registry",
1071
+ artifactKey: "sandbox-registry"
1072
+ }, ...createSandboxProviderLoaderAliases(providerLoaderTarget)],
1073
+ artifacts: [
1074
+ ...sandboxArtifacts,
1075
+ {
1076
+ key: "sandbox-registry",
1077
+ filename: "runtime/sandbox-registry.mjs",
1078
+ getContents(emitted) {
1079
+ return createSandboxRegistryContents(sandboxDefinitions.map((definition) => {
1080
+ const artifact = emitted.get(definition.definitionArtifactKey);
1081
+ if (!artifact) throw new Error(`[vitehub] Missing generated sandbox definition module for "${definition.name}".`);
1082
+ return {
1083
+ name: definition.name,
1084
+ definitionModulePath: artifact.dst
1085
+ };
1086
+ }));
1087
+ }
1088
+ },
1089
+ ...providerLoaderTarget ? [{
1090
+ key: "sandbox-provider-loader",
1091
+ filename: "runtime/sandbox-provider-loader.mjs",
1092
+ getContents: () => createSandboxProviderLoaderContents(providerLoaderTarget)
1093
+ }] : []
1094
+ ],
1095
+ extendNitro(target) {
1096
+ const nitroTarget = target;
1097
+ if (cloudflareOptions) {
1098
+ configureCloudflareSandbox(nitroTarget, cloudflareOptions);
1099
+ installCloudflareSandboxEntrypoint(nitroTarget, cloudflareOptions);
1100
+ }
1101
+ nitroTarget.externals = nitroTarget.externals || {};
1102
+ nitroTarget.externals.inline = nitroTarget.externals.inline || [];
1103
+ nitroTarget.externals.traceInclude = nitroTarget.externals.traceInclude || [];
1104
+ const runtimeDependencies = providerLoaderTarget ? [sandboxRuntimeDependencyByProvider[providerLoaderTarget]].filter(Boolean) : sandboxRuntimeDependencies;
1105
+ for (const dependency of runtimeDependencies) {
1106
+ if (!hasInstalledDependency(deps, dependency)) continue;
1107
+ if (dependency !== "@vercel/sandbox" && !nitroTarget.externals.inline.includes(dependency)) nitroTarget.externals.inline.push(dependency);
1108
+ const resolved = tryResolveModule(dependency);
1109
+ if (resolved.ok && !nitroTarget.externals.traceInclude.includes(resolved.path)) nitroTarget.externals.traceInclude.push(resolved.path);
1110
+ }
1111
+ },
1112
+ async onCompiled(nitro) {
1113
+ if (cloudflareOptions) await writeCloudflareSandboxDockerfile(nitro.options.output.serverDir);
1114
+ }
1115
+ };
1116
+ }
1117
+ //#endregion
1118
+ //#region ../internal/src/nitro.ts
1119
+ function resolveRuntimeEntry(srcRelative, packageSubpath, importMetaUrl) {
1120
+ return resolveModulePath(srcRelative, {
1121
+ extensions: [".ts", ".mts"],
1122
+ from: importMetaUrl,
1123
+ try: true
1124
+ }) ?? resolveModulePath(packageSubpath, {
1125
+ extensions: [".js", ".mjs"],
1126
+ from: importMetaUrl
1127
+ });
1128
+ }
1129
+ function isPromiseLike(value) {
1130
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
1131
+ }
1132
+ async function hasNamedVitePlugin(plugin, name) {
1133
+ if (isPromiseLike(plugin)) return hasNamedVitePlugin(await plugin, name);
1134
+ if (Array.isArray(plugin)) {
1135
+ for (const entry of plugin) if (await hasNamedVitePlugin(entry, name)) return true;
1136
+ return false;
1137
+ }
1138
+ return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === name;
1139
+ }
1140
+ async function assertNoVitePlugin(vite, vitePluginName, integrationName) {
1141
+ if (await hasNamedVitePlugin(vite?.plugins, vitePluginName)) throw new Error(`[vitehub] Do not configure ${vitePluginName} when using ${integrationName}.`);
1142
+ }
1143
+ async function assertNoVitePluginInNitro(nitro, vitePluginName, integrationName) {
1144
+ await assertNoVitePlugin(nitro.options.vite, vitePluginName, integrationName);
1145
+ }
1146
+ //#endregion
1147
+ //#region ../internal/src/object.ts
1148
+ function isPlainObject(value) {
1149
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1150
+ }
1151
+ //#endregion
1152
+ //#region src/internal/shared/feature-options.ts
1153
+ function cloneFeatureOptions(feature, options) {
1154
+ if (!isPlainObject(options)) throw new TypeError(`[vitehub] \`${feature}\` must be a plain object.`);
1155
+ return { ...options };
1156
+ }
1157
+ function normalizeFeatureOptions(feature, options) {
1158
+ if (options === false || typeof options === "undefined") return void 0;
1159
+ return cloneFeatureOptions(feature, options);
1160
+ }
1161
+ //#endregion
1162
+ //#region src/internal/shared/feature-engine.ts
1163
+ function createFeatureEngine(options) {
1164
+ return options;
1165
+ }
1166
+ function normalizeFeaturePublicOptions(feature, options) {
1167
+ return normalizeFeatureOptions(feature, options);
1168
+ }
1169
+ function readFeaturePublicOptions(source, key) {
1170
+ if (source.kind === "vite") return source.userConfig[key];
1171
+ return source.nitro.options[key];
1172
+ }
1173
+ function resolveDefaultOptions(defaultOptions) {
1174
+ return typeof defaultOptions === "function" ? defaultOptions() : defaultOptions;
1175
+ }
1176
+ function applyRuntimeConfig(runtimeConfig, key, config) {
1177
+ runtimeConfig[key] = config;
1178
+ }
1179
+ async function readWorkspaceDeps(rootDir) {
1180
+ const packageJson = await readPackageJSON(rootDir);
1181
+ return {
1182
+ ...packageJson.dependencies,
1183
+ ...packageJson.devDependencies
1184
+ };
1185
+ }
1186
+ function resolveViteRoot(config) {
1187
+ return resolve(process.cwd(), typeof config.root === "string" ? config.root : ".");
1188
+ }
1189
+ function resolveRawOptions(engine, source) {
1190
+ const rawOptions = engine.readPublicOptions(source);
1191
+ return typeof rawOptions === "undefined" && typeof engine.defaultOptions !== "undefined" ? resolveDefaultOptions(engine.defaultOptions) : rawOptions;
1192
+ }
1193
+ function resolveNormalizedConfig(engine, source) {
1194
+ const normalizedOptions = engine.normalizeOptions(resolveRawOptions(engine, source));
1195
+ if (!normalizedOptions) return void 0;
1196
+ const hosting = source.kind === "vite" ? detectHosting({ options: source.userConfig }) : detectHosting(source.nitro);
1197
+ return {
1198
+ config: engine.resolveConfig ? engine.resolveConfig(normalizedOptions, hosting) : normalizedOptions,
1199
+ hosting: hosting || void 0
1200
+ };
1201
+ }
1202
+ async function buildFeatureResolvedState(engine, source) {
1203
+ const resolved = resolveNormalizedConfig(engine, source);
1204
+ if (!resolved) return void 0;
1205
+ const rootDir = source.kind === "vite" ? resolveViteRoot(source.userConfig) : source.nitro.options.rootDir;
1206
+ const runtimeConfig = source.kind === "nitro" ? source.nitro.options.runtimeConfig ||= {} : {};
1207
+ if (resolved.hosting) runtimeConfig.hosting ||= resolved.hosting;
1208
+ if (engine.assignRuntimeConfig) engine.assignRuntimeConfig(runtimeConfig, resolved.config);
1209
+ else applyRuntimeConfig(runtimeConfig, engine.configKey, resolved.config);
1210
+ const deps = engine.loadDeps ? await readWorkspaceDeps(rootDir) : {};
1211
+ return {
1212
+ rootDir,
1213
+ config: resolved.config,
1214
+ deps,
1215
+ runtimeConfig,
1216
+ hosting: resolved.hosting
1217
+ };
1218
+ }
1219
+ async function buildFeatureViteContext(engine, userConfig, env) {
1220
+ const state = await buildFeatureResolvedState(engine, {
1221
+ kind: "vite",
1222
+ userConfig,
1223
+ env
1224
+ });
1225
+ if (!state) return void 0;
1226
+ return {
1227
+ ...state,
1228
+ command: env.command,
1229
+ mode: env.mode
1230
+ };
1231
+ }
1232
+ async function buildFeatureNitroContext(engine, nitro) {
1233
+ return await buildFeatureResolvedState(engine, {
1234
+ kind: "nitro",
1235
+ nitro
1236
+ });
1237
+ }
1238
+ function createFeatureNitroBridge(engine) {
1239
+ return {
1240
+ name: engine.name,
1241
+ async setup(nitro) {
1242
+ await assertNoVitePluginInNitro(nitro, `${engine.name}/vite`, `${engine.name}/nitro`);
1243
+ const context = await buildFeatureNitroContext(engine, nitro);
1244
+ if (!context) return;
1245
+ await engine.setupNitro?.(nitro, context);
1246
+ }
1247
+ };
1248
+ }
1249
+ //#endregion
1250
+ //#region src/internal/shared/nitro-imports.ts
1251
+ function hasOwnImportsConfig(layer) {
1252
+ return Object.prototype.hasOwnProperty.call(layer?.config || {}, "imports");
1253
+ }
1254
+ function shouldEnableNitroImports(nitro) {
1255
+ const target = nitro;
1256
+ if (target.options.imports !== false) return false;
1257
+ const layers = target.options._c12?.layers;
1258
+ if (!Array.isArray(layers) || layers.length === 0) return false;
1259
+ return !layers.slice(1).some(hasOwnImportsConfig);
1260
+ }
1261
+ function ensureNitroImports(nitro) {
1262
+ const target = nitro;
1263
+ if (shouldEnableNitroImports(target)) target.options.imports = {};
1264
+ return target.options.imports;
1265
+ }
1266
+ //#endregion
1267
+ //#region src/internal/shared/cloudflare-wrangler.ts
1268
+ function compareNumericStrings(left, right) {
1269
+ return left.localeCompare(right, void 0, { numeric: true });
1270
+ }
1271
+ function compareMigrationTags(left, right) {
1272
+ return compareNumericStrings(left.tag, right.tag);
1273
+ }
1274
+ function isSameKVNamespace(left, right) {
1275
+ return left.binding === right.binding && left.id === right.id && left.preview_id === right.preview_id && left.experimental_remote === right.experimental_remote;
1276
+ }
1277
+ function isSameContainer(left, right) {
1278
+ return left.class_name === right.class_name && left.image === right.image && left.instance_type === right.instance_type && left.max_instances === right.max_instances && left.name === right.name;
1279
+ }
1280
+ function isSameDurableObjectBinding(left, right) {
1281
+ return left.name === right.name && left.class_name === right.class_name;
1282
+ }
1283
+ function isSameWorkerLoader(left, right) {
1284
+ return left.binding === right.binding;
1285
+ }
1286
+ function isSameAnalyticsEngineDataset(left, right) {
1287
+ return left.binding === right.binding && left.dataset === right.dataset;
1288
+ }
1289
+ function isSameWorkflow(left, right) {
1290
+ return left.binding === right.binding && left.name === right.name && left.class_name === right.class_name;
1291
+ }
1292
+ function dedupeByKey(entries, getKey, equals, conflictLabel) {
1293
+ if (!entries?.length) return void 0;
1294
+ const unique = /* @__PURE__ */ new Map();
1295
+ for (const entry of entries) {
1296
+ const key = getKey(entry);
1297
+ const existing = unique.get(key);
1298
+ if (!existing) {
1299
+ unique.set(key, entry);
1300
+ continue;
1301
+ }
1302
+ if (!equals(existing, entry)) throw new Error(`[vitehub] Conflicting Cloudflare ${conflictLabel} "${key}".`);
1303
+ }
1304
+ return [...unique.values()];
1305
+ }
1306
+ function mergeMigrations(migrations) {
1307
+ if (!migrations?.length) return void 0;
1308
+ const byTag = /* @__PURE__ */ new Map();
1309
+ for (const migration of migrations) {
1310
+ const classes = byTag.get(migration.tag) || /* @__PURE__ */ new Set();
1311
+ for (const className of migration.new_sqlite_classes || []) classes.add(className);
1312
+ byTag.set(migration.tag, classes);
1313
+ }
1314
+ return [...byTag.entries()].map(([tag, classes]) => ({
1315
+ tag,
1316
+ ...classes.size ? { new_sqlite_classes: [...classes].sort(compareNumericStrings) } : {}
1317
+ })).sort(compareMigrationTags);
1318
+ }
1319
+ function validateDurableObjectMigrations(wrangler) {
1320
+ const bindings = wrangler.durable_objects?.bindings;
1321
+ if (!bindings?.length) return;
1322
+ const declaredClasses = new Set((wrangler.migrations || []).flatMap((migration) => migration.new_sqlite_classes || []));
1323
+ const missingClasses = [...new Set(bindings.map((binding) => binding.class_name))].filter((className) => !declaredClasses.has(className)).sort(compareNumericStrings);
1324
+ if (missingClasses.length) throw new Error(`[vitehub] Missing Cloudflare durable object migration entries for: ${missingClasses.join(", ")}.`);
1325
+ }
1326
+ function finalizeCloudflareWranglerConfig(target) {
1327
+ const wrangler = target.cloudflare?.wrangler;
1328
+ if (!wrangler) return;
1329
+ wrangler.kv_namespaces = dedupeByKey(wrangler.kv_namespaces, (namespace) => namespace.binding, isSameKVNamespace, "KV namespace binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
1330
+ wrangler.containers = dedupeByKey(wrangler.containers, (container) => container.class_name, isSameContainer, "container")?.sort((left, right) => compareNumericStrings(left.class_name, right.class_name));
1331
+ wrangler.worker_loaders = dedupeByKey(wrangler.worker_loaders, (loader) => loader.binding, isSameWorkerLoader, "worker loader binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
1332
+ wrangler.analytics_engine_datasets = dedupeByKey(wrangler.analytics_engine_datasets, (dataset) => dataset.binding, isSameAnalyticsEngineDataset, "analytics engine dataset binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
1333
+ wrangler.durable_objects ||= {};
1334
+ wrangler.durable_objects.bindings = dedupeByKey(wrangler.durable_objects.bindings, (binding) => binding.name, isSameDurableObjectBinding, "durable object binding")?.sort((left, right) => compareNumericStrings(left.name, right.name));
1335
+ wrangler.workflows = dedupeByKey(wrangler.workflows, (workflow) => workflow.binding, isSameWorkflow, "workflow binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
1336
+ wrangler.migrations = mergeMigrations(wrangler.migrations);
1337
+ validateDurableObjectMigrations(wrangler);
1338
+ }
1339
+ function installCloudflareWranglerFinalizer(nitro) {
1340
+ const target = nitro;
1341
+ if (target.__vitehubCloudflareWranglerFinalizerInstalled) return;
1342
+ target.__vitehubCloudflareWranglerFinalizerInstalled = true;
1343
+ nitro.hooks.hook("build:before", () => {
1344
+ finalizeCloudflareWranglerConfig(nitro.options);
1345
+ });
1346
+ }
1347
+ //#endregion
1348
+ //#region src/internal/shared/runtime-artifacts.ts
1349
+ async function resolveArtifactContents(artifact, emitted) {
1350
+ if (typeof artifact.getContents === "function") return await artifact.getContents(emitted);
1351
+ return artifact.contents || "";
1352
+ }
1353
+ function resolvePlanAlias(alias, artifacts) {
1354
+ if (alias.artifactKey) {
1355
+ const artifact = artifacts.get(alias.artifactKey);
1356
+ if (!artifact) throw new Error(`[vitehub] Missing emitted artifact "${alias.artifactKey}" for alias "${alias.key}".`);
1357
+ return artifact.dst;
1358
+ }
1359
+ if (typeof alias.value === "string") return alias.value;
1360
+ throw new Error(`[vitehub] Alias "${alias.key}" must define either value or artifactKey.`);
1361
+ }
1362
+ function addPlanAliases(target, aliases, artifacts) {
1363
+ target.alias ||= {};
1364
+ for (const alias of aliases) target.alias[alias.key] = resolvePlanAlias(alias, artifacts);
1365
+ }
1366
+ function addPlanHandlers(target, handlers, artifacts) {
1367
+ target.handlers ||= [];
1368
+ for (const handler of handlers) {
1369
+ const resolvedHandler = handler.artifactKey ? artifacts.get(handler.artifactKey)?.dst : handler.handler;
1370
+ if (!resolvedHandler) throw new Error(`[vitehub] Missing handler for route "${handler.route}".`);
1371
+ target.handlers.push({
1372
+ route: handler.route,
1373
+ method: handler.method,
1374
+ handler: resolvedHandler
1375
+ });
1376
+ }
1377
+ }
1378
+ function getStableNitroRuntimeDir(nitro) {
1379
+ return join(nitro.options.rootDir, ".vitehub", "nitro-runtime");
1380
+ }
1381
+ async function emitNitroArtifacts(nitro, artifacts = []) {
1382
+ const emitted = /* @__PURE__ */ new Map();
1383
+ for (const artifact of artifacts) {
1384
+ const contents = await resolveArtifactContents(artifact, emitted);
1385
+ const path = join(getStableNitroRuntimeDir(nitro), artifact.filename);
1386
+ await mkdir(dirname(path), { recursive: true });
1387
+ await writeFile(path, contents);
1388
+ emitted.set(artifact.key, {
1389
+ ...artifact,
1390
+ contents,
1391
+ dst: path
1392
+ });
1393
+ }
1394
+ return emitted;
1395
+ }
1396
+ async function registerNitroFeature(nitro, registration) {
1397
+ nitro.options.alias ||= {};
1398
+ nitro.options.alias[registration.alias] = registration.aliasPath;
1399
+ if (registration.nitroPlugin) {
1400
+ nitro.options.plugins ||= [];
1401
+ if (!nitro.options.plugins.includes(registration.nitroPlugin)) nitro.options.plugins.push(registration.nitroPlugin);
1402
+ }
1403
+ ensureNitroImports(nitro);
1404
+ if (registration.imports?.length && nitro.options.imports !== false) applyServerImportsToNitro(nitro.options, registration.imports);
1405
+ if (registration.typeTemplate) {
1406
+ const typeTemplate = registration.typeTemplate;
1407
+ nitro.hooks.hook("types:extend", async (types) => {
1408
+ const dtsPath = join(nitro.options.buildDir, "types", typeTemplate.filename.replaceAll("/", "-"));
1409
+ await mkdir(dirname(dtsPath), { recursive: true });
1410
+ await writeFile(dtsPath, typeTemplate.contents);
1411
+ if (types.tsConfig) {
1412
+ types.tsConfig.include = types.tsConfig.include || [];
1413
+ types.tsConfig.include.push(dtsPath);
1414
+ }
1415
+ });
1416
+ }
1417
+ }
1418
+ async function applyFeaturePlanToNitro(nitro, plan) {
1419
+ const emitted = await emitNitroArtifacts(nitro, plan.artifacts);
1420
+ await registerNitroFeature(nitro, plan.manifest);
1421
+ if (plan.aliases?.length) addPlanAliases(nitro.options, plan.aliases, emitted);
1422
+ if (plan.handlers?.length) addPlanHandlers(nitro.options, plan.handlers, emitted);
1423
+ if (plan.extendNitro) await plan.extendNitro(nitro.options, emitted);
1424
+ installCloudflareWranglerFinalizer(nitro);
1425
+ if (plan.onCompiled) nitro.hooks.hook("compiled", async () => {
1426
+ await plan.onCompiled?.(nitro, emitted);
1427
+ });
1428
+ }
1429
+ //#endregion
1430
+ //#region src/internal/shared/feature-compiler.ts
1431
+ async function compileFeatureIntoNitro(nitro, config, deps, compiler) {
1432
+ if (!config) return false;
1433
+ const nitroOptions = nitro.options;
1434
+ nitroOptions.runtimeConfig ||= {};
1435
+ ensureNitroImports(nitro);
1436
+ await applyFeaturePlanToNitro(nitro, await compiler.compile({
1437
+ nitro,
1438
+ config,
1439
+ deps,
1440
+ runtimeConfig: nitroOptions.runtimeConfig,
1441
+ hosting: typeof nitroOptions.runtimeConfig.hosting === "string" ? nitroOptions.runtimeConfig.hosting : detectHosting(nitro),
1442
+ scanRoots: resolveNitroScanRoots(nitro)
1443
+ }));
1444
+ return true;
1445
+ }
1446
+ //#endregion
1447
+ //#region src/internal/shared/vitehub-server-imports.ts
1448
+ const featureImports = {
1449
+ analytics: [
1450
+ {
1451
+ name: "createTrack",
1452
+ from: "@vite-hub/analytics"
1453
+ },
1454
+ {
1455
+ name: "defineTrack",
1456
+ from: "@vite-hub/analytics"
1457
+ },
1458
+ {
1459
+ name: "getAnalytics",
1460
+ from: "@vite-hub/analytics"
1461
+ },
1462
+ {
1463
+ name: "track",
1464
+ from: "@vite-hub/analytics"
1465
+ },
1466
+ {
1467
+ name: "AnalyticsCapabilities",
1468
+ as: "AnalyticsCapabilities",
1469
+ from: "@vite-hub/analytics",
1470
+ type: true
1471
+ },
1472
+ {
1473
+ name: "AnalyticsClientOptions",
1474
+ as: "AnalyticsClientOptions",
1475
+ from: "@vite-hub/analytics",
1476
+ type: true
1477
+ },
1478
+ {
1479
+ name: "AnalyticsClientStrategy",
1480
+ as: "AnalyticsClientStrategy",
1481
+ from: "@vite-hub/analytics",
1482
+ type: true
1483
+ },
1484
+ {
1485
+ name: "AnalyticsCloudflareOptions",
1486
+ as: "AnalyticsCloudflareOptions",
1487
+ from: "@vite-hub/analytics",
1488
+ type: true
1489
+ },
1490
+ {
1491
+ name: "AnalyticsConfig",
1492
+ as: "AnalyticsConfig",
1493
+ from: "@vite-hub/analytics",
1494
+ type: true
1495
+ },
1496
+ {
1497
+ name: "AnalyticsDefinition",
1498
+ as: "AnalyticsDefinition",
1499
+ from: "@vite-hub/analytics",
1500
+ type: true
1501
+ },
1502
+ {
1503
+ name: "AnalyticsDefinitionOptions",
1504
+ as: "AnalyticsDefinitionOptions",
1505
+ from: "@vite-hub/analytics",
1506
+ type: true
1507
+ },
1508
+ {
1509
+ name: "AnalyticsHandle",
1510
+ as: "AnalyticsHandle",
1511
+ from: "@vite-hub/analytics",
1512
+ type: true
1513
+ },
1514
+ {
1515
+ name: "AnalyticsProvider",
1516
+ as: "AnalyticsProvider",
1517
+ from: "@vite-hub/analytics",
1518
+ type: true
1519
+ },
1520
+ {
1521
+ name: "AnalyticsPublicOptions",
1522
+ as: "AnalyticsPublicOptions",
1523
+ from: "@vite-hub/analytics",
1524
+ type: true
1525
+ },
1526
+ {
1527
+ name: "AnalyticsRuntimeKind",
1528
+ as: "AnalyticsRuntimeKind",
1529
+ from: "@vite-hub/analytics",
1530
+ type: true
1531
+ },
1532
+ {
1533
+ name: "AnalyticsVercelOptions",
1534
+ as: "AnalyticsVercelOptions",
1535
+ from: "@vite-hub/analytics",
1536
+ type: true
1537
+ }
1538
+ ],
1539
+ blob: [
1540
+ {
1541
+ name: "blob",
1542
+ from: "@vite-hub/blob"
1543
+ },
1544
+ {
1545
+ name: "ensureBlob",
1546
+ from: "@vite-hub/blob"
1547
+ },
1548
+ {
1549
+ name: "BlobStorage",
1550
+ as: "BlobStorage",
1551
+ from: "@vite-hub/blob",
1552
+ type: true
1553
+ },
1554
+ {
1555
+ name: "BlobObject",
1556
+ as: "BlobObject",
1557
+ from: "@vite-hub/blob",
1558
+ type: true
1559
+ },
1560
+ {
1561
+ name: "BlobListOptions",
1562
+ as: "BlobListOptions",
1563
+ from: "@vite-hub/blob",
1564
+ type: true
1565
+ },
1566
+ {
1567
+ name: "BlobPutOptions",
1568
+ as: "BlobPutOptions",
1569
+ from: "@vite-hub/blob",
1570
+ type: true
1571
+ },
1572
+ {
1573
+ name: "BlobUploadOptions",
1574
+ as: "BlobUploadOptions",
1575
+ from: "@vite-hub/blob",
1576
+ type: true
1577
+ }
1578
+ ],
1579
+ browser: [
1580
+ {
1581
+ name: "createBrowser",
1582
+ from: "@vite-hub/browser"
1583
+ },
1584
+ {
1585
+ name: "defineBrowser",
1586
+ from: "@vite-hub/browser"
1587
+ },
1588
+ {
1589
+ name: "getBrowser",
1590
+ from: "@vite-hub/browser"
1591
+ },
1592
+ {
1593
+ name: "readValidatedPayload",
1594
+ as: "readValidatedBrowserPayload",
1595
+ from: "@vite-hub/browser"
1596
+ },
1597
+ {
1598
+ name: "runBrowser",
1599
+ from: "@vite-hub/browser"
1600
+ },
1601
+ {
1602
+ name: "BrowserClient",
1603
+ as: "BrowserClient",
1604
+ from: "@vite-hub/browser",
1605
+ type: true
1606
+ },
1607
+ {
1608
+ name: "BrowserProvider",
1609
+ as: "BrowserProvider",
1610
+ from: "@vite-hub/browser",
1611
+ type: true
1612
+ },
1613
+ {
1614
+ name: "BrowserRunResult",
1615
+ as: "BrowserRunResult",
1616
+ from: "@vite-hub/browser",
1617
+ type: true
1618
+ }
1619
+ ],
1620
+ cache: [],
1621
+ cron: [
1622
+ {
1623
+ name: "createCron",
1624
+ from: "@vite-hub/cron"
1625
+ },
1626
+ {
1627
+ name: "defineCron",
1628
+ from: "@vite-hub/cron"
1629
+ },
1630
+ {
1631
+ name: "runCron",
1632
+ from: "@vite-hub/cron"
1633
+ },
1634
+ {
1635
+ name: "getCronsForExpression",
1636
+ from: "@vite-hub/cron"
1637
+ },
1638
+ {
1639
+ name: "readValidatedPayload",
1640
+ as: "readValidatedCronPayload",
1641
+ from: "@vite-hub/cron"
1642
+ },
1643
+ {
1644
+ name: "runCronsForExpression",
1645
+ from: "@vite-hub/cron"
1646
+ },
1647
+ {
1648
+ name: "startScheduleRunner",
1649
+ from: "@vite-hub/cron"
1650
+ },
1651
+ {
1652
+ name: "CronProvider",
1653
+ as: "CronProvider",
1654
+ from: "@vite-hub/cron",
1655
+ type: true
1656
+ }
1657
+ ],
1658
+ db: [],
1659
+ email: [
1660
+ {
1661
+ name: "createEmailClient",
1662
+ from: "@vite-hub/email"
1663
+ },
1664
+ {
1665
+ name: "renderEmail",
1666
+ from: "@vite-hub/email"
1667
+ },
1668
+ {
1669
+ name: "renderEmailMarkdown",
1670
+ from: "@vite-hub/email"
1671
+ },
1672
+ {
1673
+ name: "sendEmail",
1674
+ from: "@vite-hub/email"
1675
+ },
1676
+ {
1677
+ name: "sendEmails",
1678
+ from: "@vite-hub/email"
1679
+ },
1680
+ {
1681
+ name: "EmailSendBatchResult",
1682
+ as: "EmailSendBatchResult",
1683
+ from: "@vite-hub/email",
1684
+ type: true
1685
+ },
1686
+ {
1687
+ name: "EmailMessage",
1688
+ as: "EmailMessage",
1689
+ from: "@vite-hub/email",
1690
+ type: true
1691
+ },
1692
+ {
1693
+ name: "EmailProvider",
1694
+ as: "EmailProvider",
1695
+ from: "@vite-hub/email",
1696
+ type: true
1697
+ },
1698
+ {
1699
+ name: "EmailSendResult",
1700
+ as: "EmailSendResult",
1701
+ from: "@vite-hub/email",
1702
+ type: true
1703
+ }
1704
+ ],
1705
+ kv: [{
1706
+ name: "kv",
1707
+ from: "@vite-hub/kv"
1708
+ }, {
1709
+ name: "KVStorage",
1710
+ as: "KVStorage",
1711
+ from: "@vite-hub/kv",
1712
+ type: true
1713
+ }],
1714
+ queue: [
1715
+ {
1716
+ name: "createQueue",
1717
+ from: "@vite-hub/queue"
1718
+ },
1719
+ {
1720
+ name: "deferQueue",
1721
+ from: "@vite-hub/queue"
1722
+ },
1723
+ {
1724
+ name: "defineQueue",
1725
+ from: "@vite-hub/queue"
1726
+ },
1727
+ {
1728
+ name: "getQueue",
1729
+ from: "@vite-hub/queue"
1730
+ },
1731
+ {
1732
+ name: "readValidatedJob",
1733
+ from: "@vite-hub/queue"
1734
+ },
1735
+ {
1736
+ name: "readValidatedPayload",
1737
+ as: "readValidatedQueuePayload",
1738
+ from: "@vite-hub/queue"
1739
+ },
1740
+ {
1741
+ name: "runQueue",
1742
+ from: "@vite-hub/queue"
1743
+ },
1744
+ {
1745
+ name: "QueueEnqueueInput",
1746
+ as: "QueueEnqueueInput",
1747
+ from: "@vite-hub/queue",
1748
+ type: true
1749
+ },
1750
+ {
1751
+ name: "QueueClient",
1752
+ as: "QueueClient",
1753
+ from: "@vite-hub/queue",
1754
+ type: true
1755
+ },
1756
+ {
1757
+ name: "QueueProvider",
1758
+ as: "QueueProvider",
1759
+ from: "@vite-hub/queue",
1760
+ type: true
1761
+ }
1762
+ ],
1763
+ sandbox: [
1764
+ {
1765
+ name: "defineSandbox",
1766
+ from: "@vite-hub/sandbox"
1767
+ },
1768
+ {
1769
+ name: "readValidatedPayload",
1770
+ as: "readValidatedSandboxPayload",
1771
+ from: "@vite-hub/sandbox"
1772
+ },
1773
+ {
1774
+ name: "runSandbox",
1775
+ from: "@vite-hub/sandbox"
1776
+ },
1777
+ {
1778
+ name: "SandboxDefinition",
1779
+ as: "SandboxDefinition",
1780
+ from: "@vite-hub/sandbox",
1781
+ type: true
1782
+ },
1783
+ {
1784
+ name: "SandboxRunResult",
1785
+ as: "SandboxRunResult",
1786
+ from: "@vite-hub/sandbox",
1787
+ type: true
1788
+ }
1789
+ ],
1790
+ vector: [
1791
+ {
1792
+ name: "defineVector",
1793
+ from: "@vite-hub/vector"
1794
+ },
1795
+ {
1796
+ name: "getVector",
1797
+ from: "@vite-hub/vector"
1798
+ },
1799
+ {
1800
+ name: "VectorConfig",
1801
+ as: "VectorConfig",
1802
+ from: "@vite-hub/vector",
1803
+ type: true
1804
+ },
1805
+ {
1806
+ name: "VectorDefinition",
1807
+ as: "VectorDefinition",
1808
+ from: "@vite-hub/vector",
1809
+ type: true
1810
+ },
1811
+ {
1812
+ name: "VectorDefinitionOptions",
1813
+ as: "VectorDefinitionOptions",
1814
+ from: "@vite-hub/vector",
1815
+ type: true
1816
+ },
1817
+ {
1818
+ name: "VectorFilter",
1819
+ as: "VectorFilter",
1820
+ from: "@vite-hub/vector",
1821
+ type: true
1822
+ },
1823
+ {
1824
+ name: "VectorHandle",
1825
+ as: "VectorHandle",
1826
+ from: "@vite-hub/vector",
1827
+ type: true
1828
+ },
1829
+ {
1830
+ name: "VectorMatch",
1831
+ as: "VectorMatch",
1832
+ from: "@vite-hub/vector",
1833
+ type: true
1834
+ },
1835
+ {
1836
+ name: "VectorMetric",
1837
+ as: "VectorMetric",
1838
+ from: "@vite-hub/vector",
1839
+ type: true
1840
+ },
1841
+ {
1842
+ name: "VectorProvider",
1843
+ as: "VectorProvider",
1844
+ from: "@vite-hub/vector",
1845
+ type: true
1846
+ },
1847
+ {
1848
+ name: "VectorQuery",
1849
+ as: "VectorQuery",
1850
+ from: "@vite-hub/vector",
1851
+ type: true
1852
+ },
1853
+ {
1854
+ name: "VectorQueryResult",
1855
+ as: "VectorQueryResult",
1856
+ from: "@vite-hub/vector",
1857
+ type: true
1858
+ },
1859
+ {
1860
+ name: "VectorRecord",
1861
+ as: "VectorRecord",
1862
+ from: "@vite-hub/vector",
1863
+ type: true
1864
+ },
1865
+ {
1866
+ name: "VectorValues",
1867
+ as: "VectorValues",
1868
+ from: "@vite-hub/vector",
1869
+ type: true
1870
+ }
1871
+ ],
1872
+ workflow: [
1873
+ {
1874
+ name: "createWorkflow",
1875
+ from: "@vite-hub/workflow"
1876
+ },
1877
+ {
1878
+ name: "deferWorkflow",
1879
+ from: "@vite-hub/workflow"
1880
+ },
1881
+ {
1882
+ name: "defineWorkflow",
1883
+ from: "@vite-hub/workflow"
1884
+ },
1885
+ {
1886
+ name: "getWorkflowRun",
1887
+ from: "@vite-hub/workflow"
1888
+ },
1889
+ {
1890
+ name: "readValidatedPayload",
1891
+ as: "readValidatedWorkflowPayload",
1892
+ from: "@vite-hub/workflow"
1893
+ },
1894
+ {
1895
+ name: "runWorkflow",
1896
+ from: "@vite-hub/workflow"
1897
+ },
1898
+ {
1899
+ name: "WorkflowProvider",
1900
+ as: "WorkflowProvider",
1901
+ from: "@vite-hub/workflow",
1902
+ type: true
1903
+ },
1904
+ {
1905
+ name: "WorkflowRun",
1906
+ as: "WorkflowRun",
1907
+ from: "@vite-hub/workflow",
1908
+ type: true
1909
+ },
1910
+ {
1911
+ name: "WorkflowRunStatus",
1912
+ as: "WorkflowRunStatus",
1913
+ from: "@vite-hub/workflow",
1914
+ type: true
1915
+ }
1916
+ ]
1917
+ };
1918
+ function getDbFeatureImports(options) {
1919
+ return [{
1920
+ name: "db",
1921
+ from: "@vite-hub/database/drizzle"
1922
+ }, {
1923
+ name: "schema",
1924
+ from: "@vite-hub/database/drizzle"
1925
+ }];
1926
+ }
1927
+ const featureNitroModules = {
1928
+ analytics: "@vite-hub/analytics/nitro",
1929
+ blob: "@vite-hub/blob/nitro",
1930
+ browser: "@vite-hub/browser/nitro",
1931
+ cache: "@vite-hub/cache/nitro",
1932
+ cron: "@vite-hub/cron/nitro",
1933
+ db: "@vite-hub/database/nitro",
1934
+ email: "@vite-hub/email/nitro",
1935
+ kv: "@vite-hub/kv/nitro",
1936
+ queue: "@vite-hub/queue/nitro",
1937
+ vector: "@vite-hub/vector/nitro",
1938
+ workflow: "@vite-hub/workflow/nitro"
1939
+ };
1940
+ function hasNitroModule(options, modulePath) {
1941
+ return Array.isArray(options.modules) && options.modules.includes(modulePath);
1942
+ }
1943
+ function isFeatureEnabled(feature, options) {
1944
+ if (feature === "db") return typeof options.db !== "undefined";
1945
+ const optionValue = options[feature];
1946
+ if (optionValue === false) return false;
1947
+ if (typeof optionValue !== "undefined") return true;
1948
+ const nitroModule = featureNitroModules[feature];
1949
+ return !!nitroModule && hasNitroModule(options, nitroModule);
1950
+ }
1951
+ function getViteHubFeatureServerImports(feature, options = {}) {
1952
+ if (feature === "db") return dedupeServerImports(getDbFeatureImports(options));
1953
+ return dedupeServerImports(featureImports[feature]);
1954
+ }
1955
+ function resolveEnabledViteHubServerImports(options = {}) {
1956
+ return dedupeServerImports(Object.keys(featureImports).flatMap((feature) => {
1957
+ if (!isFeatureEnabled(feature, options)) return [];
1958
+ return getViteHubFeatureServerImports(feature, options);
1959
+ }));
1960
+ }
1961
+ function resolveEffectiveViteHubServerImports(options = {}, feature) {
1962
+ return dedupeServerImports([...resolveEnabledViteHubServerImports(options), ...feature ? getViteHubFeatureServerImports(feature, options) : []]);
1963
+ }
1964
+ //#endregion
1965
+ //#region src/setup-nitro.ts
1966
+ const sandboxFeatureCompiler = {
1967
+ feature: "sandbox",
1968
+ async compile(context) {
1969
+ applyServerImportsToNitro(context.nitro.options, resolveEffectiveViteHubServerImports(context.nitro.options, "sandbox"));
1970
+ const { definitions } = await loadFeatureDefinitions({
1971
+ feature: "sandbox",
1972
+ scanRoots: context.scanRoots,
1973
+ subdir: "sandboxes",
1974
+ srcScan: {
1975
+ mode: "recursive",
1976
+ filter: (relativePath) => relativePath.endsWith(".sandbox.ts") || relativePath.endsWith(".sandbox.mts") || relativePath.endsWith(".sandbox.js") || relativePath.endsWith(".sandbox.mjs"),
1977
+ normalizeName(relativePath) {
1978
+ return normalizeDefinitionName(relativePath.replace(/\.sandbox(\.[cm]?[tj]s)$/i, "$1"));
1979
+ }
1980
+ }
1981
+ });
1982
+ return await createSandboxFeaturePlan(context.config, definitions, {
1983
+ aliasPath: resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./index", "index.mjs"),
1984
+ nitroPlugin: resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "../src/runtime/nitro-plugin", "runtime/nitro-plugin.js")
1985
+ }, context.deps, context.hosting, {
1986
+ rootDir: context.nitro.options.rootDir,
1987
+ scanRoots: context.scanRoots,
1988
+ nitroImports: context.nitro.options.imports
1989
+ });
1990
+ }
1991
+ };
1992
+ async function setupSandboxNitro(nitro, sandboxConfig, deps) {
1993
+ if (!await compileFeatureIntoNitro(nitro, sandboxConfig, deps, sandboxFeatureCompiler)) return;
1994
+ const defaultProvider = getSandboxFeatureProvider(sandboxConfig);
1995
+ if (defaultProvider?.provider === "vercel" && !hasInstalledDependency(deps, "@vercel/sandbox", { paths: [nitro.options.rootDir] })) nitro.logger.warn("Install `@vercel/sandbox` for Vercel sandbox presets.");
1996
+ if (defaultProvider?.provider === "cloudflare" && !hasInstalledDependency(deps, "@cloudflare/sandbox", { paths: [nitro.options.rootDir] })) nitro.logger.warn("Install `@cloudflare/sandbox` for Cloudflare sandbox presets.");
1997
+ nitro.logger.info("`@vite-hub/sandbox` enabled");
1998
+ }
1999
+ //#endregion
2000
+ //#region src/integration.ts
2001
+ function normalizeSandboxPublicOptions(options) {
2002
+ return normalizeFeaturePublicOptions("sandbox", options);
2003
+ }
2004
+ function assignSandboxRuntimeConfig(runtimeConfig, config) {
2005
+ const provider = getSandboxFeatureProvider(config);
2006
+ if (provider?.provider === "vercel") {
2007
+ runtimeConfig.sandbox = {
2008
+ ...config,
2009
+ token: provider.token ?? "",
2010
+ teamId: provider.teamId ?? "",
2011
+ projectId: provider.projectId ?? ""
2012
+ };
2013
+ return;
2014
+ }
2015
+ runtimeConfig.sandbox = config;
2016
+ }
2017
+ const sandboxFeatureEngine = createFeatureEngine({
2018
+ name: "@vite-hub/sandbox",
2019
+ feature: "sandbox",
2020
+ configKey: "sandbox",
2021
+ defaultOptions: () => ({}),
2022
+ loadDeps: true,
2023
+ normalizeOptions: normalizeSandboxPublicOptions,
2024
+ resolveConfig: resolveSandboxFeatureConfig,
2025
+ assignRuntimeConfig: assignSandboxRuntimeConfig,
2026
+ readPublicOptions: (source) => readFeaturePublicOptions(source, "sandbox"),
2027
+ async setupNitro(nitro, context) {
2028
+ await setupSandboxNitro(nitro, context.config, context.deps);
2029
+ }
2030
+ });
2031
+ //#endregion
2032
+ export { resolveFeatureRuntimePath as C, applyServerImportsToNitro as D, createDiscoveredDefinitionCompiler as E, dedupeServerImports as O, getSupportedHostingProvider as S, tryResolveModule as T, defaultCloudflareSandboxClassName as _, ensureNitroImports as a, bundleSandboxDefinition as b, createFeatureNitroBridge as c, resolveSandboxProviderLoaderTarget as d, sandboxRuntimeDependencies as f, defaultCloudflareSandboxBinding as g, configureCloudflareSandbox as h, resolveEffectiveViteHubServerImports as i, resolveRuntimeEntry as l, extractSandboxDefinitionOptions as m, sandboxFeatureEngine as n, buildFeatureViteContext as o, sandboxRuntimeDependencyByProvider as p, getViteHubFeatureServerImports as r, createFeatureEngine as s, normalizeSandboxPublicOptions as t, createSandboxProviderLoaderContents as u, installCloudflareSandboxEntrypoint as v, hasInstalledDependency as w, detectHosting as x, writeCloudflareSandboxDockerfile as y };