@vite-hub/sandbox 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +388 -22
  3. package/dist/cloudflare-DO0h3Ncf.js +281 -0
  4. package/dist/cloudflare-env-BBJaBbuQ.js +39 -0
  5. package/dist/crabbox-BFCdf41h.js +1106 -0
  6. package/dist/error-diagnostics-BSysPv-D.js +166 -0
  7. package/dist/error-diagnostics-dGQqfgLt.js +99 -0
  8. package/dist/file-listing-DECFTdSl.js +26 -0
  9. package/dist/file-lock-CxyVl4Cv.js +73 -0
  10. package/dist/index-CXej1Bt0.d.ts +519 -0
  11. package/dist/index.d.ts +2 -65
  12. package/dist/index.js +277 -1172
  13. package/dist/internal/cloudflare.d.ts +4 -0
  14. package/dist/internal/cloudflare.js +16 -0
  15. package/dist/internal/host-toolchain.d.ts +22 -0
  16. package/dist/internal/host-toolchain.js +97 -0
  17. package/dist/internal/vercel.d.ts +4 -0
  18. package/dist/internal/vercel.js +16 -0
  19. package/dist/module-types-BfyRBaiP.js +7 -0
  20. package/dist/module-types-Cis4hrF1.d.ts +95 -0
  21. package/dist/remote-1Jz2oUMK.js +247 -0
  22. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  23. package/dist/runtime-DHp6ImeP.js +32 -0
  24. package/dist/runtime-type-DrmrW5m5.js +42 -0
  25. package/dist/session-DD0S1PDC.js +337 -0
  26. package/dist/shell-quote-Q3u3plif.js +6 -0
  27. package/dist/ssh.d.ts +55 -0
  28. package/dist/ssh.js +219 -0
  29. package/dist/task/index.d.ts +67 -0
  30. package/dist/task/index.js +1523 -0
  31. package/dist/task/runtime/empty-registry.d.ts +6 -0
  32. package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
  33. package/dist/task/runtime/provider-loader.d.ts +20 -0
  34. package/dist/task/runtime/provider-loader.js +19 -0
  35. package/dist/task/runtime/providers/cloudflare.d.ts +28 -0
  36. package/dist/task/runtime/providers/cloudflare.js +26 -0
  37. package/dist/task/runtime/providers/vercel.d.ts +12 -0
  38. package/dist/{runtime → task/runtime}/providers/vercel.js +17 -14
  39. package/dist/task/runtime/state.d.ts +24 -0
  40. package/dist/task/runtime/state.js +73 -0
  41. package/dist/task/vite.d.ts +360 -0
  42. package/dist/task/vite.js +3643 -0
  43. package/dist/toolchain-BUVXtQ2m.js +527 -0
  44. package/dist/trusted-host-DNMJ-Oig.js +872 -0
  45. package/dist/vercel-Jtxa9TJx.js +279 -0
  46. package/package.json +103 -39
  47. package/dist/cloudflare-env-2NctU8i7.js +0 -12
  48. package/dist/module-types-DfXe133f.d.ts +0 -91
  49. package/dist/module-types-Dj1MFmHT.js +0 -7
  50. package/dist/provider-loader-hL7uHVWp.d.ts +0 -21
  51. package/dist/runtime/empty-registry.d.ts +0 -6
  52. package/dist/runtime/provider-loader.d.ts +0 -2
  53. package/dist/runtime/provider-loader.js +0 -15
  54. package/dist/runtime/providers/cloudflare.d.ts +0 -29
  55. package/dist/runtime/providers/cloudflare.js +0 -25
  56. package/dist/runtime/providers/vercel.d.ts +0 -112
  57. package/dist/runtime/state.d.ts +0 -17
  58. package/dist/runtime/state.js +0 -21
  59. package/dist/vite.d.ts +0 -24
  60. package/dist/vite.js +0 -2367
package/dist/vite.js DELETED
@@ -1,2367 +0,0 @@
1
- import { t as getSandboxFeatureProvider } from "./module-types-Dj1MFmHT.js";
2
- import { builtinModules, createRequire } from "node:module";
3
- import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from "pathe";
4
- import { existsSync, readdirSync, realpathSync } from "node:fs";
5
- import { dirname as dirname$1, matchesGlob, relative as relative$1, resolve as resolve$1 } from "node:path";
6
- import { glob, mkdir, readFile, realpath, stat, 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 { createHash } from "node:crypto";
13
- import { dirname as dirname$2, join as join$1, normalize as normalize$1 } from "node:path/posix";
14
- [
15
- ".ts",
16
- ".mts",
17
- ".cts",
18
- ".js",
19
- ".mjs",
20
- ".cjs"
21
- ].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
22
- function createNoExternalMerger(packageName) {
23
- return (current) => {
24
- if (current === true) return true;
25
- if (!current) return [packageName];
26
- const values = Array.isArray(current) ? current : [current];
27
- return values.includes(packageName) ? values : [...values, packageName];
28
- };
29
- }
30
- function isServerEnvironment(name, config) {
31
- return name === "ssr" || config.consumer === "server";
32
- }
33
- function includesNitroVitePlugin(value) {
34
- if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
35
- if (!value || typeof value !== "object") return false;
36
- return "name" in value && value.name === "nitro:main";
37
- }
38
- function hasNitroConfigContext(config) {
39
- return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
40
- }
41
- function deploymentPresetFromNitro(value) {
42
- const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
43
- if (!normalized) return;
44
- if (normalized.startsWith("cloudflare")) return "cloudflare";
45
- if (normalized.startsWith("deno")) return "deno";
46
- if (normalized.startsWith("netlify")) return "netlify";
47
- if (normalized === "node" || normalized.startsWith("node-")) return "node";
48
- if (normalized.startsWith("vercel")) return "vercel";
49
- }
50
- //#endregion
51
- //#region ../internal/src/hosting.ts
52
- function normalizeHosting(hosting) {
53
- const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
54
- if (normalized === "cloudflare") return "cloudflare-module";
55
- return normalized;
56
- }
57
- function detectHosting(target) {
58
- return normalizeHosting(target.options.preset || process.env.VITEHUB_HOSTING || "");
59
- }
60
- function getHostingProvider(hosting) {
61
- const preset = deploymentPresetFromNitro(hosting);
62
- if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
63
- }
64
- function getSupportedHostingProvider(hosting, supportedProviders) {
65
- const provider = getHostingProvider(hosting);
66
- if (!provider || !supportedProviders.includes(provider)) return void 0;
67
- return provider;
68
- }
69
- //#endregion
70
- //#region ../internal/src/build/paths.ts
71
- function generatedDirSegments(productName) {
72
- return [".vitehub", productName];
73
- }
74
- function ensureGeneratedDir(rootDir, productName) {
75
- return resolve(rootDir, ...generatedDirSegments(productName));
76
- }
77
- function createImportPath(fromFile, targetFile) {
78
- const importPath = relative(realpathIfExists(dirname(fromFile)), realpathIfExists(targetFile));
79
- return importPath.startsWith(".") ? importPath : `./${importPath}`;
80
- }
81
- function realpathIfExists(path) {
82
- try {
83
- return realpathSync.native(path);
84
- } catch {
85
- return resolve(path);
86
- }
87
- }
88
- //#endregion
89
- //#region ../internal/src/definition-catalog.ts
90
- const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
91
- const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
92
- const ignoredDirs = new Set([
93
- "node_modules",
94
- "dist",
95
- ".output",
96
- ".nuxt",
97
- ".vercel",
98
- ".git",
99
- ".vitehub"
100
- ]);
101
- function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
102
- return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
103
- }
104
- function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
105
- return {
106
- ...options,
107
- kind: "suffix",
108
- normalizeName,
109
- pattern,
110
- roots,
111
- source
112
- };
113
- }
114
- function readDirEntries(root) {
115
- try {
116
- return readdirSync(root, { withFileTypes: true });
117
- } catch (error) {
118
- if (error.code === "ENOENT") return [];
119
- throw error;
120
- }
121
- }
122
- function listMatchingFiles(root, predicate, options = {}) {
123
- const files = [];
124
- for (const entry of readDirEntries(root)) {
125
- const absolute = resolve(root, entry.name);
126
- if (entry.isDirectory() && !entry.isSymbolicLink()) {
127
- if (entry.name.startsWith(".")) continue;
128
- if (ignoredDirs.has(entry.name)) continue;
129
- files.push(...listMatchingFiles(absolute, predicate, options));
130
- continue;
131
- }
132
- if (entry.name.startsWith(".") && !options.includeHidden) continue;
133
- if (entry.isFile() && predicate(entry.name)) files.push(absolute);
134
- }
135
- return files.sort();
136
- }
137
- function listSourceFiles(root, options = {}) {
138
- return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
139
- }
140
- function normalizePathDefinitionName(rootDir, file) {
141
- return relative(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
142
- }
143
- function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
144
- const normalized = relative(rootDir, file).replace(pattern, "");
145
- if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
146
- return normalized;
147
- }
148
- function sortDefinitions(definitions) {
149
- return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
150
- }
151
- function registerDefinition(definitions, definition, sourceLabel) {
152
- const existing = definitions.get(definition.name);
153
- if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
154
- definitions.set(definition.name, definition);
155
- }
156
- function mergeDefinitions(feature, ...sources) {
157
- const definitions = /* @__PURE__ */ new Map();
158
- for (const source of sources) {
159
- if (!source) continue;
160
- for (const definition of source) {
161
- const existing = definitions.get(definition.name);
162
- 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"})`);
163
- if (!existing) definitions.set(definition.name, definition);
164
- }
165
- }
166
- return sortDefinitions(definitions);
167
- }
168
- function createDefinition(source, file, name) {
169
- if (source.createDefinition) return source.createDefinition({
170
- file,
171
- name
172
- });
173
- return {
174
- handler: file,
175
- name,
176
- source: source.source
177
- };
178
- }
179
- function scanSuffixDefinitions(feature, source) {
180
- const definitions = /* @__PURE__ */ new Map();
181
- for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
182
- const name = source.normalizeName(root, file);
183
- if (!name) continue;
184
- registerDefinition(definitions, createDefinition(source, file, name), feature);
185
- }
186
- return sortDefinitions(definitions);
187
- }
188
- function scanDirectoryDefinitions(feature, source) {
189
- const definitions = /* @__PURE__ */ new Map();
190
- for (const scanDir of source.scanDirs) {
191
- const directory = resolve(scanDir, source.subdir);
192
- for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
193
- const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
194
- if (!name) continue;
195
- registerDefinition(definitions, createDefinition(source, file, name), feature);
196
- }
197
- }
198
- return sortDefinitions(definitions);
199
- }
200
- function discoverDefinitions(feature, sources) {
201
- return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
202
- }
203
- async function writeFileIfChanged(file, contents) {
204
- if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
205
- await mkdir(resolve(file, ".."), { recursive: true });
206
- await writeFile(file, contents, "utf8");
207
- }
208
- //#endregion
209
- //#region src/cloudflare.ts
210
- const defaultCloudflareSandboxBinding = "SANDBOX";
211
- const defaultCloudflareSandboxClassName = "Sandbox";
212
- const defaultCloudflareSandboxMaxInstances = 12;
213
- const require$1 = createRequire(import.meta.url);
214
- function resolveCloudflareSandboxEntrypoint() {
215
- try {
216
- return require$1.resolve("@cloudflare/sandbox");
217
- } catch {
218
- throw new Error("[vitehub] The Cloudflare Sandbox provider requires @cloudflare/sandbox. Install a supported version before building.");
219
- }
220
- }
221
- function resolveCloudflareSandboxVersion() {
222
- const pkg = require$1(join(resolveCloudflareSandboxEntrypoint(), "..", "..", "package.json"));
223
- if (typeof pkg?.version !== "string") throw new Error("[vitehub] Could not resolve the installed @cloudflare/sandbox version.");
224
- return pkg.version;
225
- }
226
- function resolveCloudflareSandboxEntrypointOptions(options = {}) {
227
- if (options.className === "ContainerProxy") throw new Error("[vitehub] Cloudflare Sandbox className \"ContainerProxy\" is reserved by @cloudflare/sandbox. Configure a different className.");
228
- return {
229
- binding: options.binding || "SANDBOX",
230
- className: options.className || "Sandbox",
231
- migrationTag: options.migrationTag || "v1",
232
- name: options.name || void 0
233
- };
234
- }
235
- function mergeRollupExternal(value, addition) {
236
- if (typeof value === "undefined") return [addition];
237
- if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
238
- if (typeof value === "string" || value instanceof RegExp) return [value, addition];
239
- if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
240
- return value;
241
- }
242
- function configureCloudflareSandbox(target, options = {}) {
243
- const { binding, className, migrationTag, name } = resolveCloudflareSandboxEntrypointOptions(options);
244
- 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.");
245
- const existingMigrations = target.cloudflare?.wrangler?.migrations;
246
- 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.`);
247
- 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.`);
248
- target.cloudflare ||= {};
249
- target.cloudflare.wrangler ||= {};
250
- target.cloudflare.wrangler.containers ||= [];
251
- target.cloudflare.wrangler.durable_objects ||= {};
252
- target.cloudflare.wrangler.durable_objects.bindings ||= [];
253
- target.cloudflare.wrangler.migrations ||= [];
254
- const containers = target.cloudflare.wrangler.containers;
255
- const image = "./Dockerfile";
256
- if (!containers.some((entry) => entry.class_name === className)) containers.push({
257
- class_name: className,
258
- image,
259
- instance_type: "lite",
260
- max_instances: defaultCloudflareSandboxMaxInstances,
261
- ...name ? { name } : {}
262
- });
263
- else {
264
- const container = containers.find((entry) => entry.class_name === className);
265
- container.image ??= image;
266
- if (typeof container.max_instances !== "number") container.max_instances = defaultCloudflareSandboxMaxInstances;
267
- if (name) container.name ??= name;
268
- }
269
- const bindings = target.cloudflare.wrangler.durable_objects.bindings;
270
- if (!bindings.some((entry) => entry.name === binding && entry.class_name === className)) bindings.push({
271
- name: binding,
272
- class_name: className
273
- });
274
- const migrations = target.cloudflare.wrangler.migrations;
275
- if (!migrations.some((entry) => Array.isArray(entry.new_sqlite_classes) && entry.new_sqlite_classes.includes(className))) migrations.push({
276
- tag: migrationTag,
277
- new_sqlite_classes: [className]
278
- });
279
- }
280
- function createCloudflareSandboxRollupPlugin(options = {}) {
281
- const { className } = resolveCloudflareSandboxEntrypointOptions(options);
282
- const cloudflareSandboxEntrypoint = resolveCloudflareSandboxEntrypoint();
283
- const moduleId = "virtual:vitehub-sandbox-cloudflare-exports";
284
- const resolvedModuleId = "\0virtual:vitehub-sandbox-cloudflare-exports";
285
- return {
286
- name: "vitehub-sandbox-cloudflare-exports",
287
- buildStart() {
288
- this.emitFile({
289
- type: "chunk",
290
- id: moduleId,
291
- fileName: "sandbox-cloudflare-exports.mjs"
292
- });
293
- },
294
- resolveId(id) {
295
- if (id === moduleId) return resolvedModuleId;
296
- if (id === "@cloudflare/sandbox") return cloudflareSandboxEntrypoint;
297
- },
298
- load(id) {
299
- if (id === resolvedModuleId) return [
300
- `import { Sandbox as CloudflareSandbox } from '@cloudflare/sandbox'`,
301
- `export { ContainerProxy } from '@cloudflare/sandbox'`,
302
- ``,
303
- `export class ${className} extends CloudflareSandbox {}`,
304
- ``
305
- ].join("\n");
306
- },
307
- renderChunk(code, chunk) {
308
- if (!chunk.isEntry) return null;
309
- const exportedNames = new Set(chunk.exports);
310
- const missingExports = [className, "ContainerProxy"].filter((name) => !exportedNames.has(name));
311
- if (!missingExports.length) return null;
312
- const exportsPath = relative(dirname(chunk.fileName), "sandbox-cloudflare-exports.mjs").replace(/\\/g, "/");
313
- const importPath = exportsPath.startsWith(".") ? exportsPath : `./${exportsPath}`;
314
- return {
315
- code: `${code}\nexport { ${missingExports.join(", ")} } from ${JSON.stringify(importPath)}\n`,
316
- map: null
317
- };
318
- }
319
- };
320
- }
321
- function installCloudflareSandboxEntrypoint(target, options = {}) {
322
- const { className } = resolveCloudflareSandboxEntrypointOptions(options);
323
- target.rollupConfig ||= {};
324
- const plugins = Array.isArray(target.rollupConfig.plugins) ? target.rollupConfig.plugins : target.rollupConfig.plugins ? [target.rollupConfig.plugins] : [];
325
- target.rollupConfig.plugins = plugins;
326
- if (plugins.some((plugin) => typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === `vitehub-sandbox-cloudflare-exports:${className}`)) return;
327
- const plugin = createCloudflareSandboxRollupPlugin({ className });
328
- plugin.name = `vitehub-sandbox-cloudflare-exports:${className}`;
329
- plugins.push(plugin);
330
- }
331
- async function writeCloudflareSandboxDockerfile(serverDir) {
332
- const dockerfilePath = join(serverDir, "Dockerfile");
333
- await writeFileIfChanged(dockerfilePath, `FROM docker.io/cloudflare/sandbox:${resolveCloudflareSandboxVersion()}\n`);
334
- return dockerfilePath;
335
- }
336
- function relativeWranglerPath(from, to) {
337
- const path = relative(from, to).replace(/\\/g, "/");
338
- return path.startsWith(".") ? path : `./${path}`;
339
- }
340
- async function configureCloudflareSandboxNitro(targetValue, rootDir, options = {}) {
341
- const target = targetValue || {};
342
- const serverDir = resolve(rootDir, target.output?.serverDir || ".output/server");
343
- const resolvedOptions = resolveCloudflareSandboxEntrypointOptions(options);
344
- const existingImage = (target.cloudflare?.wrangler?.containers?.find((entry) => entry.class_name === resolvedOptions.className))?.image?.replace(/\\/g, "/");
345
- configureCloudflareSandbox(target, resolvedOptions);
346
- const container = target.cloudflare.wrangler.containers.find((entry) => entry.class_name === resolvedOptions.className);
347
- if (typeof existingImage !== "string" || existingImage.endsWith("/.vitehub/sandbox/Dockerfile")) {
348
- container.image = relativeWranglerPath(serverDir, await writeCloudflareSandboxDockerfile(resolve(rootDir, ".vitehub/sandbox")));
349
- container.image_build_context = relativeWranglerPath(serverDir, rootDir);
350
- }
351
- const wrangler = target.cloudflare.wrangler;
352
- wrangler.compatibility_flags = Array.isArray(wrangler.compatibility_flags) ? [...wrangler.compatibility_flags] : [];
353
- if (!wrangler.compatibility_flags.includes("nodejs_compat")) wrangler.compatibility_flags.push("nodejs_compat");
354
- target.rollupConfig ||= {};
355
- target.rollupConfig.external = mergeRollupExternal(target.rollupConfig.external, "cloudflare:workers");
356
- installCloudflareSandboxEntrypoint(target, resolvedOptions);
357
- return target;
358
- }
359
- //#endregion
360
- //#region src/internal/shared/discovered-definition/bundler.ts
361
- const builtinModuleSet$1 = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
362
- function resolveDefinitionLoader(options) {
363
- let loader = options.loader;
364
- if (!loader) {
365
- const f = options.filename;
366
- if (f.endsWith(".tsx")) loader = "tsx";
367
- else if (f.endsWith(".jsx")) loader = "jsx";
368
- else if (f.endsWith(".js") || f.endsWith(".mjs") || f.endsWith(".cjs")) loader = "js";
369
- else loader = "ts";
370
- }
371
- return loader;
372
- }
373
- function isJsxDefinitionLoader(options) {
374
- const loader = resolveDefinitionLoader(options);
375
- return loader === "tsx" || loader === "jsx";
376
- }
377
- async function bundleDiscoveredDefinitionModule(options) {
378
- const output = (await build({
379
- alias: options.alias,
380
- stdin: {
381
- contents: options.source,
382
- loader: resolveDefinitionLoader(options),
383
- resolveDir: dirname(options.filename),
384
- sourcefile: options.filename
385
- },
386
- bundle: true,
387
- write: false,
388
- format: "esm",
389
- platform: "node",
390
- target: "es2022",
391
- logLevel: "silent",
392
- jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
393
- jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
394
- packages: options.packages === "external" ? "external" : void 0,
395
- external: [...builtinModuleSet$1, ...options.external || []],
396
- plugins: options.plugins
397
- })).outputFiles?.[0]?.text;
398
- if (!output) throw new Error(`[vitehub] Failed to bundle discovered definition "${options.filename}".`);
399
- return output;
400
- }
401
- async function bundleDiscoveredDefinitionModuleGraph(options) {
402
- const outdir = resolve(dirname(options.filename), ".vitehub-discovered-definition");
403
- const result = await build({
404
- alias: options.alias,
405
- stdin: {
406
- contents: options.source,
407
- loader: resolveDefinitionLoader(options),
408
- resolveDir: dirname(options.filename),
409
- sourcefile: options.filename
410
- },
411
- bundle: true,
412
- splitting: true,
413
- entryNames: "definition",
414
- chunkNames: "chunks/[name]-[hash]",
415
- outdir,
416
- write: false,
417
- format: "esm",
418
- platform: "node",
419
- target: "es2022",
420
- logLevel: "silent",
421
- jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
422
- jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
423
- packages: options.packages === "external" ? "external" : void 0,
424
- external: [...builtinModuleSet$1, ...options.external || []],
425
- plugins: options.plugins
426
- });
427
- const modules = Object.fromEntries((result.outputFiles || []).map((outputFile) => {
428
- return [relative(outdir, outputFile.path), outputFile.text];
429
- }));
430
- if (!modules["definition.js"]) throw new Error(`[vitehub] Failed to bundle discovered definition graph "${options.filename}".`);
431
- return {
432
- entry: "definition.js",
433
- modules
434
- };
435
- }
436
- //#endregion
437
- //#region src/internal/shared/discovered-definition/ast.ts
438
- const typescript$1 = createRequire(import.meta.url)("typescript");
439
- function resolveImportLocalName(entry) {
440
- return entry.as || entry.name;
441
- }
442
- function getScriptKind(id) {
443
- const scriptKind = typescript$1.ScriptKind;
444
- if (id.endsWith(".tsx")) return typescript$1.ScriptKind.TSX;
445
- if (id.endsWith(".jsx")) return typescript$1.ScriptKind.JSX;
446
- if (id.endsWith(".mts")) return scriptKind.MTS ?? typescript$1.ScriptKind.TS;
447
- if (id.endsWith(".cts")) return scriptKind.CTS ?? typescript$1.ScriptKind.TS;
448
- if (id.endsWith(".mjs")) return typescript$1.ScriptKind.JS;
449
- if (id.endsWith(".cjs")) return typescript$1.ScriptKind.JS;
450
- if (id.endsWith(".js")) return typescript$1.ScriptKind.JS;
451
- return typescript$1.ScriptKind.TS;
452
- }
453
- function createSourceFile(id, source) {
454
- return typescript$1.createSourceFile(id, source, typescript$1.ScriptTarget.Latest, true, getScriptKind(id));
455
- }
456
- function hasModifier(node, kind) {
457
- return typescript$1.canHaveModifiers(node) && (typescript$1.getModifiers(node)?.some((modifier) => modifier.kind === kind) ?? false);
458
- }
459
- function hasExportedType(source, id, name) {
460
- return createSourceFile(id, source).statements.some((statement) => {
461
- if ((typescript$1.isInterfaceDeclaration(statement) || typescript$1.isTypeAliasDeclaration(statement)) && statement.name.text === name) return hasModifier(statement, typescript$1.SyntaxKind.ExportKeyword);
462
- if (!typescript$1.isExportDeclaration(statement) || !statement.exportClause || !typescript$1.isNamedExports(statement.exportClause)) return false;
463
- return statement.exportClause.elements.some((element) => element.name.text === name && (statement.isTypeOnly || element.isTypeOnly));
464
- });
465
- }
466
- function collectRuntimeModuleSpecifiers(source, id) {
467
- const sourceFile = createSourceFile(id, source);
468
- const specifiers = [];
469
- let hasNonLiteralDynamicImport = false;
470
- function addSpecifier(node) {
471
- if (node && typescript$1.isStringLiteralLike(node)) specifiers.push({
472
- node,
473
- specifier: node.text
474
- });
475
- }
476
- function visit(node) {
477
- if (typescript$1.isImportDeclaration(node)) {
478
- const clause = node.importClause;
479
- const bindings = clause?.namedBindings;
480
- 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);
481
- } else if (typescript$1.isExportDeclaration(node)) {
482
- const clause = node.exportClause;
483
- if (!node.isTypeOnly && (!clause || typescript$1.isNamespaceExport(clause) || clause.elements.length === 0 || clause.elements.some((element) => !element.isTypeOnly))) addSpecifier(node.moduleSpecifier);
484
- } else if (typescript$1.isCallExpression(node) && node.expression.kind === typescript$1.SyntaxKind.ImportKeyword) {
485
- const argument = node.arguments[0];
486
- if (argument && typescript$1.isStringLiteralLike(argument)) addSpecifier(argument);
487
- else hasNonLiteralDynamicImport = true;
488
- }
489
- typescript$1.forEachChild(node, visit);
490
- }
491
- visit(sourceFile);
492
- return {
493
- hasNonLiteralDynamicImport,
494
- sourceFile,
495
- specifiers
496
- };
497
- }
498
- function findRuntimeModuleSpecifiers(source, id) {
499
- return collectRuntimeModuleSpecifiers(source, id).specifiers.map((entry) => entry.specifier);
500
- }
501
- function hasNonLiteralDynamicImport(source, id) {
502
- return collectRuntimeModuleSpecifiers(source, id).hasNonLiteralDynamicImport;
503
- }
504
- function propertyAccessRoot(expression) {
505
- const properties = [];
506
- let current = expression;
507
- while (typescript$1.isPropertyAccessExpression(current) || typescript$1.isElementAccessExpression(current)) {
508
- if (typescript$1.isPropertyAccessExpression(current)) {
509
- properties.unshift(current.name.text);
510
- current = current.expression;
511
- continue;
512
- }
513
- const argument = current.argumentExpression;
514
- properties.unshift(argument && typescript$1.isStringLiteralLike(argument) ? argument.text : "*");
515
- current = current.expression;
516
- }
517
- return {
518
- current,
519
- properties
520
- };
521
- }
522
- function findCommonJSImportEqualsSpecifiers(source, id) {
523
- const sourceFile = createSourceFile(id, source);
524
- const specifiers = [];
525
- function visit(node) {
526
- if (typescript$1.isImportEqualsDeclaration(node) && !node.isTypeOnly && typescript$1.isExternalModuleReference(node.moduleReference)) {
527
- const expression = node.moduleReference.expression;
528
- specifiers.push({
529
- path: id,
530
- specifier: expression && typescript$1.isStringLiteralLike(expression) ? expression.text : void 0,
531
- syntax: "import-equals"
532
- });
533
- }
534
- typescript$1.forEachChild(node, visit);
535
- }
536
- visit(sourceFile);
537
- return specifiers;
538
- }
539
- function isExecutableIdentifierReference(node) {
540
- const parent = node.parent;
541
- if (typescript$1.isImportClause(parent) || typescript$1.isImportSpecifier(parent) || typescript$1.isNamespaceImport(parent) || typescript$1.isNamespaceExport(parent)) return false;
542
- if (typescript$1.isExportSpecifier(parent)) {
543
- if (parent.parent.parent.moduleSpecifier) return false;
544
- return parent.propertyName ? parent.propertyName === node : parent.name === node;
545
- }
546
- if (typescript$1.isBindingElement(parent) && (parent.name === node || parent.propertyName === node)) return false;
547
- if (typescript$1.isPropertyAccessExpression(parent) && parent.name === node) return false;
548
- if (typescript$1.isLabeledStatement(parent) || typescript$1.isBreakStatement(parent) || typescript$1.isContinueStatement(parent)) return false;
549
- const namedParent = parent;
550
- if (!typescript$1.isShorthandPropertyAssignment(parent) && namedParent.name === node) return false;
551
- return parent.propertyName !== node;
552
- }
553
- function findExecutableCommonJSModuleSpecifiers(sources) {
554
- const executableSources = new Map([...sources].map(([path, source]) => [`/${path.replace(/^[/]+/, "")}`, source]));
555
- const options = {
556
- allowJs: true,
557
- checkJs: false,
558
- module: typescript$1.ModuleKind.ESNext,
559
- moduleDetection: typescript$1.ModuleDetectionKind.Force,
560
- noLib: true,
561
- noResolve: true,
562
- target: typescript$1.ScriptTarget.ES2022,
563
- types: []
564
- };
565
- const sourceFiles = /* @__PURE__ */ new Map();
566
- const program = typescript$1.createProgram({
567
- host: {
568
- fileExists: (fileName) => executableSources.has(fileName),
569
- getCanonicalFileName: (fileName) => fileName,
570
- getCurrentDirectory: () => "/",
571
- getDefaultLibFileName: () => "",
572
- getNewLine: () => "\n",
573
- getSourceFile(fileName, languageVersion) {
574
- const source = executableSources.get(fileName);
575
- if (source === void 0) return void 0;
576
- let sourceFile = sourceFiles.get(fileName);
577
- if (!sourceFile) {
578
- sourceFile = typescript$1.createSourceFile(fileName, source, languageVersion, true, typescript$1.ScriptKind.JS);
579
- sourceFiles.set(fileName, sourceFile);
580
- }
581
- return sourceFile;
582
- },
583
- readFile: (fileName) => executableSources.get(fileName),
584
- useCaseSensitiveFileNames: () => true,
585
- writeFile: () => {}
586
- },
587
- options,
588
- rootNames: [...executableSources.keys()]
589
- });
590
- const checker = program.getTypeChecker();
591
- const specifiers = [];
592
- function isRuntimeBindingDeclaration(node) {
593
- 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);
594
- }
595
- function isBound(node) {
596
- return (typescript$1.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node))?.declarations?.some(isRuntimeBindingDeclaration) ?? false;
597
- }
598
- function visit(sourceFile, node) {
599
- if (typescript$1.isCallExpression(node) && typescript$1.isIdentifier(node.expression) && node.expression.text === "require" && !isBound(node.expression)) {
600
- const argument = node.arguments[0];
601
- specifiers.push({
602
- path: sourceFile.fileName.slice(1),
603
- specifier: argument && typescript$1.isStringLiteralLike(argument) ? argument.text : void 0,
604
- syntax: "require"
605
- });
606
- } else if (typescript$1.isPropertyAccessExpression(node) || typescript$1.isElementAccessExpression(node)) {
607
- const { current, properties } = propertyAccessRoot(node);
608
- if (typescript$1.isIdentifier(current) && current.text === "require" && !isBound(current)) specifiers.push({
609
- path: sourceFile.fileName.slice(1),
610
- specifier: properties.join("."),
611
- syntax: "require-property"
612
- });
613
- } else if (typescript$1.isBinaryExpression(node) && node.operatorToken.kind >= typescript$1.SyntaxKind.FirstAssignment && node.operatorToken.kind <= typescript$1.SyntaxKind.LastAssignment) {
614
- const { current, properties } = propertyAccessRoot(node.left);
615
- if (typescript$1.isIdentifier(current) && current.text === "module" && !isBound(current) && properties[0] === "exports") specifiers.push({
616
- path: sourceFile.fileName.slice(1),
617
- syntax: "module-exports-assignment"
618
- });
619
- else if (typescript$1.isIdentifier(current) && current.text === "exports" && !isBound(current) && properties.length) specifiers.push({
620
- path: sourceFile.fileName.slice(1),
621
- syntax: "exports-assignment"
622
- });
623
- } else if (typescript$1.isIdentifier(node) && (node.text === "module" || node.text === "exports") && isExecutableIdentifierReference(node) && !isBound(node)) specifiers.push({
624
- path: sourceFile.fileName.slice(1),
625
- syntax: node.text === "module" ? "module-reference" : "exports-reference"
626
- });
627
- typescript$1.forEachChild(node, (child) => visit(sourceFile, child));
628
- }
629
- for (const sourceFile of program.getSourceFiles()) visit(sourceFile, sourceFile);
630
- return specifiers;
631
- }
632
- function rewriteRuntimeRelativeModuleSpecifiers(source, id, rewrite) {
633
- const { sourceFile, specifiers } = collectRuntimeModuleSpecifiers(source, id);
634
- const edits = [];
635
- for (const { node, specifier } of specifiers) {
636
- if (!/^\.\.?\//.test(specifier)) continue;
637
- const replacement = rewrite(specifier);
638
- if (replacement !== specifier) edits.push({
639
- start: node.getStart(sourceFile),
640
- end: node.getEnd(),
641
- replacement: JSON.stringify(replacement)
642
- });
643
- }
644
- return edits.sort((left, right) => right.start - left.start).reduce((contents, edit) => `${contents.slice(0, edit.start)}${edit.replacement}${contents.slice(edit.end)}`, source);
645
- }
646
- function collectExplicitImportNames(sourceFile) {
647
- const names = /* @__PURE__ */ new Set();
648
- for (const statement of sourceFile.statements) {
649
- if (!typescript$1.isImportDeclaration(statement)) continue;
650
- const clause = statement.importClause;
651
- if (!clause) continue;
652
- if (clause.name) names.add(clause.name.text);
653
- const bindings = clause.namedBindings;
654
- if (!bindings) continue;
655
- if (typescript$1.isNamespaceImport(bindings)) {
656
- names.add(bindings.name.text);
657
- continue;
658
- }
659
- for (const element of bindings.elements) names.add(element.name.text);
660
- }
661
- return names;
662
- }
663
- function collectDeclaredTypeNames(sourceFile) {
664
- const names = /* @__PURE__ */ new Set();
665
- function visit(node) {
666
- if ((typescript$1.isInterfaceDeclaration(node) || typescript$1.isTypeAliasDeclaration(node) || typescript$1.isClassDeclaration(node) || typescript$1.isEnumDeclaration(node)) && node.name) names.add(node.name.text);
667
- 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);
668
- typescript$1.forEachChild(node, visit);
669
- }
670
- visit(sourceFile);
671
- return names;
672
- }
673
- function collectTypeReferenceNames(sourceFile) {
674
- const names = /* @__PURE__ */ new Set();
675
- function addEntityName(name) {
676
- if (typescript$1.isIdentifier(name)) names.add(name.text);
677
- }
678
- function visit(node) {
679
- if (typescript$1.isImportTypeNode(node) || typescript$1.isTypeQueryNode(node)) return;
680
- if (typescript$1.isTypeReferenceNode(node)) {
681
- addEntityName(node.typeName);
682
- node.typeArguments?.forEach((argument) => visit(argument));
683
- return;
684
- }
685
- if (typescript$1.isExpressionWithTypeArguments(node)) {
686
- if (typescript$1.isIdentifier(node.expression)) names.add(node.expression.text);
687
- node.typeArguments?.forEach((argument) => visit(argument));
688
- return;
689
- }
690
- typescript$1.forEachChild(node, visit);
691
- }
692
- visit(sourceFile);
693
- return names;
694
- }
695
- function groupTypeImports(imports) {
696
- const grouped = /* @__PURE__ */ new Map();
697
- for (const entry of imports) {
698
- const from = entry.typeFrom || entry.from;
699
- const entries = grouped.get(from);
700
- if (entries) {
701
- entries.push(entry);
702
- continue;
703
- }
704
- grouped.set(from, [entry]);
705
- }
706
- return grouped;
707
- }
708
- function stringifyTypeImport(entry) {
709
- const localName = resolveImportLocalName(entry);
710
- if (localName === entry.name) return entry.name;
711
- return `${entry.name} as ${localName}`;
712
- }
713
- function injectTypeImports(source, imports, id) {
714
- if (!imports.length) return source;
715
- const importStatements = createSourceFile(id, source).statements.filter(typescript$1.isImportDeclaration);
716
- const groupedImports = groupTypeImports(imports);
717
- const block = Array.from(groupedImports.entries()).map(([from, entries]) => `import type { ${entries.map(stringifyTypeImport).join(", ")} } from ${JSON.stringify(from)}`).join("\n");
718
- if (!block) return source;
719
- const insertAt = importStatements.at(-1)?.end ?? (source.startsWith("#!") ? source.indexOf("\n") + 1 : 0);
720
- const prefix = source.slice(0, insertAt);
721
- const suffix = source.slice(insertAt);
722
- const needsLeadingNewline = insertAt > 0 && !prefix.endsWith("\n");
723
- const needsTrailingNewline = suffix.length > 0 && !suffix.startsWith("\n");
724
- return `${prefix}${needsLeadingNewline ? "\n" : ""}${block}${needsTrailingNewline ? "\n" : ""}${suffix}`;
725
- }
726
- async function injectTypeImportsFromUnimport(source, id, imports) {
727
- const sourceFile = createSourceFile(id, source);
728
- const explicitImports = collectExplicitImportNames(sourceFile);
729
- const declaredTypes = collectDeclaredTypeNames(sourceFile);
730
- const usedTypes = collectTypeReferenceNames(sourceFile);
731
- const pendingImports = [];
732
- for (const entry of imports) {
733
- if (!entry.type || entry.disabled) continue;
734
- const localName = resolveImportLocalName(entry);
735
- if (!usedTypes.has(localName)) continue;
736
- if (explicitImports.has(localName) || declaredTypes.has(localName)) continue;
737
- pendingImports.push(entry);
738
- explicitImports.add(localName);
739
- }
740
- return injectTypeImports(source, pendingImports, id);
741
- }
742
- //#endregion
743
- //#region src/internal/shared/server-imports.ts
744
- function isServerAutoImportEnabled(imports) {
745
- return imports !== false && imports?.autoImport !== false;
746
- }
747
- //#endregion
748
- //#region src/internal/shared/discovered-definition.ts
749
- function normalizeDir(rootDir, dir) {
750
- if (typeof dir === "string") return isAbsolute(dir) ? dir : resolve(rootDir, dir);
751
- return {
752
- ...dir,
753
- glob: isAbsolute(dir.glob) ? dir.glob : resolve(rootDir, dir.glob)
754
- };
755
- }
756
- function normalizePresetImport(from, entry) {
757
- if (typeof entry === "string") return {
758
- from,
759
- name: entry
760
- };
761
- return {
762
- from,
763
- name: entry.name,
764
- ...entry.as ? { as: entry.as } : {},
765
- ...entry.type ? { type: true } : {}
766
- };
767
- }
768
- function normalizeServerImport(entry) {
769
- return {
770
- from: entry.from,
771
- name: entry.name,
772
- ...entry.as ? { as: entry.as } : {},
773
- ...entry.type ? { type: true } : {}
774
- };
775
- }
776
- function resolveDefaultImportDirs(rootDir, scanRoots) {
777
- return scanRoots.flatMap((scanRoot) => [normalizeDir(rootDir, join(scanRoot, "server/utils/**/*")), normalizeDir(rootDir, join(scanRoot, "shared/types/**/*"))]);
778
- }
779
- function isInlinePreset(value) {
780
- return !!value && typeof value === "object" && typeof value.from === "string" && Array.isArray(value.imports);
781
- }
782
- function isPresetImport(value) {
783
- return !!value && typeof value === "object" && typeof value.name === "string";
784
- }
785
- function normalizePresetImports(presets = []) {
786
- const normalized = [];
787
- function collect(from, entry) {
788
- if (typeof entry === "string") {
789
- normalized.push(normalizePresetImport(from, entry));
790
- return;
791
- }
792
- if (isInlinePreset(entry)) {
793
- for (const nested of entry.imports) collect(entry.from, nested);
794
- return;
795
- }
796
- if (isPresetImport(entry)) normalized.push(normalizePresetImport(from, entry));
797
- }
798
- for (const preset of presets) {
799
- if (!isInlinePreset(preset)) continue;
800
- for (const entry of preset.imports) collect(preset.from, entry);
801
- }
802
- return normalized;
803
- }
804
- async function createInitializedUnimport(options) {
805
- const serverImports = options.serverImports !== false ? options.serverImports : void 0;
806
- const unimport = createUnimport({
807
- imports: [...normalizePresetImports(serverImports?.presets), ...(options.featureImports || []).map(normalizeServerImport)],
808
- dirs: [...resolveDefaultImportDirs(options.rootDir, options.scanRoots), ...(serverImports?.dirs || []).map((dir) => normalizeDir(options.rootDir, dir))]
809
- });
810
- await unimport.init();
811
- return unimport;
812
- }
813
- async function createDiscoveredDefinitionCompiler(options = {}) {
814
- const resolvedOptions = {
815
- rootDir: options.rootDir || process.cwd(),
816
- scanRoots: options.scanRoots || [],
817
- serverImports: options.serverImports,
818
- featureImports: options.featureImports || []
819
- };
820
- if (!isServerAutoImportEnabled(resolvedOptions.serverImports)) return {
821
- enabled: false,
822
- async injectSource(source) {
823
- return source;
824
- },
825
- async readSource(id) {
826
- return await readFile(id, "utf8");
827
- },
828
- async bundleModule(bundleOptions) {
829
- return await bundleDiscoveredDefinitionModule(bundleOptions);
830
- }
831
- };
832
- const unimport = await createInitializedUnimport(resolvedOptions);
833
- const injectSource = async (source, id) => {
834
- return await injectTypeImportsFromUnimport((await unimport.injectImports(source, id)).code, id, await unimport.getImports());
835
- };
836
- return {
837
- enabled: true,
838
- injectSource,
839
- async readSource(id) {
840
- return await injectSource(await readFile(id, "utf8"), id);
841
- },
842
- async bundleModule(bundleOptions) {
843
- return await bundleDiscoveredDefinitionModule(bundleOptions);
844
- }
845
- };
846
- }
847
- //#endregion
848
- //#region src/internal/shared/feature-definitions.ts
849
- function toTemplateSafeName(name) {
850
- return name.replace(/[^a-z0-9/_:-]/gi, "_").replace(/\//g, "__").replace(/:/g, "__");
851
- }
852
- //#endregion
853
- //#region src/internal/shared/module-resolve.ts
854
- function normalizePaths(paths) {
855
- if (paths?.length) return paths;
856
- if (typeof process !== "undefined") return [process.cwd()];
857
- return [];
858
- }
859
- function tryResolveFromRuntime(id) {
860
- const requireResolver = globalThis.require?.resolve;
861
- if (typeof requireResolver !== "function") return void 0;
862
- try {
863
- return requireResolver(id);
864
- } catch {
865
- return false;
866
- }
867
- }
868
- function tryResolveModule(id, options = {}) {
869
- const paths = normalizePaths(options.paths);
870
- const runtimeResolved = tryResolveFromRuntime(id);
871
- if (runtimeResolved === false) return [/* @__PURE__ */ new Error(`Unable to resolve module "${id}" using the active runtime resolver`), void 0];
872
- if (runtimeResolved) return [null, runtimeResolved];
873
- const resolved = resolveModule(id, { paths });
874
- if (resolved) return [null, resolved];
875
- for (const url of paths) try {
876
- return [null, resolvePathSync(id, { url })];
877
- } catch {
878
- continue;
879
- }
880
- 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];
881
- }
882
- //#endregion
883
- //#region src/internal/shared/feature-runtime-path.ts
884
- function resolveExistingModulePath(path) {
885
- if (existsSync(path)) return path;
886
- for (const extension of [
887
- ".ts",
888
- ".mts",
889
- ".js",
890
- ".mjs"
891
- ]) {
892
- const withExtension = `${path}${extension}`;
893
- if (existsSync(withExtension)) return withExtension;
894
- }
895
- }
896
- function resolveFeatureRuntimePath(importMetaUrl, packageId, sourceRelativePath, distRelativePath) {
897
- const importerDir = dirname(fileURLToPath(importMetaUrl));
898
- const sourcePath = resolve(importerDir, sourceRelativePath);
899
- const importerUsesDist = importerDir.split(sep).includes("dist");
900
- const targetsSourceTree = /(?:^|\/)\.\.\/src(?:\/|$)|^\.\/*src(?:\/|$)/.test(sourceRelativePath);
901
- const resolvedSourcePath = resolveExistingModulePath(sourcePath);
902
- if ((!importerUsesDist || !targetsSourceTree) && resolvedSourcePath) return resolvedSourcePath;
903
- const [packageJsonError, packageJsonPath] = tryResolveModule(`${packageId}/package.json`);
904
- if (!packageJsonError) {
905
- const resolvedPackageSourcePath = resolveExistingModulePath(join(dirname(packageJsonPath), "src", sourceRelativePath.replace(/^(\.\.\/)+src\//, "").replace(/^\.\//, "")));
906
- if ((!importerUsesDist || !targetsSourceTree) && resolvedPackageSourcePath) return resolvedPackageSourcePath;
907
- return join(dirname(packageJsonPath), "dist", distRelativePath);
908
- }
909
- const [packageError, packagePath] = tryResolveModule(packageId);
910
- if (!packageError) return join(dirname(packagePath), distRelativePath);
911
- return sourcePath;
912
- }
913
- //#endregion
914
- //#region src/project.ts
915
- const maxTimeout = 2147483647;
916
- const lockfiles = [
917
- {
918
- file: "pnpm-lock.yaml",
919
- manager: "pnpm"
920
- },
921
- {
922
- file: "package-lock.json",
923
- manager: "npm"
924
- },
925
- {
926
- file: "yarn.lock",
927
- manager: "yarn"
928
- },
929
- {
930
- file: "bun.lock",
931
- manager: "bun"
932
- }
933
- ];
934
- const projectFileExcludes = [
935
- "node_modules/**",
936
- ".git/**",
937
- "**/.env",
938
- "**/.env.*",
939
- "**/.npmrc",
940
- "bun.lockb"
941
- ];
942
- function isInside(root, path) {
943
- const next = relative$1(root, path);
944
- return next === "" || !next.startsWith("..") && !next.startsWith("/");
945
- }
946
- async function isFile(path, root) {
947
- if (!await stat(path).then((value) => value.isFile(), () => false)) return false;
948
- if (!isInside(root, await realpath(path))) throw new Error(`[vitehub] Sandbox project file escapes its scan root: ${path}`);
949
- return true;
950
- }
951
- function ancestors(start, root) {
952
- const paths = [];
953
- let current = start;
954
- while (isInside(root, current)) {
955
- paths.push(current);
956
- if (current === root) break;
957
- const parent = dirname$1(current);
958
- if (parent === current) break;
959
- current = parent;
960
- }
961
- return paths;
962
- }
963
- function packageManagerFromField(value) {
964
- if (typeof value !== "string") return void 0;
965
- const name = value.split("@", 1)[0];
966
- return name === "pnpm" || name === "npm" || name === "yarn" || name === "bun" ? name : void 0;
967
- }
968
- function packageManagerMajor(value) {
969
- if (typeof value !== "string") return void 0;
970
- const version = value.slice(value.indexOf("@") + 1);
971
- const major = Number.parseInt(version, 10);
972
- return Number.isFinite(major) ? major : void 0;
973
- }
974
- function installArgs(manager, hasLockfile, declaredMajor) {
975
- if (manager === "npm") return hasLockfile ? ["ci"] : ["install"];
976
- if (manager === "yarn") return hasLockfile ? ["install", declaredMajor === 1 ? "--frozen-lockfile" : "--immutable"] : ["install"];
977
- return hasLockfile ? ["install", "--frozen-lockfile"] : ["install"];
978
- }
979
- function parseManifest(source, path) {
980
- try {
981
- return JSON.parse(source);
982
- } catch (error) {
983
- throw new Error(`[vitehub] Sandbox package manifest is invalid JSON: ${path}`, { cause: error });
984
- }
985
- }
986
- function isPlainObject$1(value) {
987
- return !!value && typeof value === "object" && !Array.isArray(value);
988
- }
989
- function parseSandboxProjectOptions(manifest, path) {
990
- if (typeof manifest.vitehub === "undefined") return void 0;
991
- if (!isPlainObject$1(manifest.vitehub)) throw new Error(`[vitehub] Sandbox package manifest "vitehub" must be an object: ${path}`);
992
- const sandbox = manifest.vitehub.sandbox;
993
- if (typeof sandbox === "undefined") return void 0;
994
- if (!isPlainObject$1(sandbox)) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox" must be an object: ${path}`);
995
- const unsupported = Object.keys(sandbox).filter((key) => key !== "timeout");
996
- if (unsupported.length) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox" has unsupported keys: ${unsupported.join(", ")}.`);
997
- const timeout = sandbox.timeout;
998
- if (typeof timeout === "undefined") return void 0;
999
- if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout <= 0 || timeout > maxTimeout) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox.timeout" must be a positive integer no greater than ${maxTimeout}.`);
1000
- return { timeout };
1001
- }
1002
- function parsePnpmWorkspacePackages(source) {
1003
- const patterns = [];
1004
- let packagesIndent;
1005
- for (const line of source.split(/\r?\n/)) {
1006
- if (packagesIndent === void 0) {
1007
- const inline = /^\s*packages\s*:\s*\[(.*)\]\s*(?:#.*)?$/.exec(line);
1008
- if (inline) return inline[1].split(",").map((value) => value.trim().replace(/^(['"])(.*)\1$/, "$2")).filter(Boolean);
1009
- const match = /^(\s*)packages\s*:\s*(?:#.*)?$/.exec(line);
1010
- if (match) packagesIndent = match[1].length;
1011
- continue;
1012
- }
1013
- if (!line.trim() || /^\s*#/.test(line)) continue;
1014
- if ((/^\s*/.exec(line)?.[0].length || 0) <= packagesIndent) break;
1015
- const item = /^\s*-\s*(.+?)\s*$/.exec(line)?.[1];
1016
- if (!item) continue;
1017
- const value = item.replace(/\s+#.*$/, "").trim().replace(/^(['"])(.*)\1$/, "$2");
1018
- if (value) patterns.push(value.replaceAll("\\", "/").replace(/\/$/, ""));
1019
- }
1020
- return patterns;
1021
- }
1022
- function isWorkspacePackage(path, patterns) {
1023
- return patterns.filter((pattern) => !pattern.startsWith("!")).some((pattern) => matchesGlob(path, pattern)) && !patterns.filter((pattern) => pattern.startsWith("!")).some((pattern) => matchesGlob(path, pattern.slice(1)));
1024
- }
1025
- async function findPnpmWorkspaceRoot(packageRoot, root) {
1026
- for (const directory of ancestors(packageRoot, root)) {
1027
- const file = resolve$1(directory, "pnpm-workspace.yaml");
1028
- if (!await isFile(file, root)) continue;
1029
- const source = await readFile(file, "utf8");
1030
- const packagePath = relative$1(directory, packageRoot).replaceAll("\\", "/") || ".";
1031
- if (directory === packageRoot || isWorkspacePackage(packagePath, parsePnpmWorkspacePackages(source))) return {
1032
- directory,
1033
- file,
1034
- source
1035
- };
1036
- }
1037
- }
1038
- async function addProjectFile(files, installRoot, path, scanRoot) {
1039
- if (!await isFile(path, scanRoot)) return;
1040
- const mode = (await stat(path)).mode & 511;
1041
- files[relative$1(installRoot, path).replaceAll("\\", "/")] = {
1042
- contents: (await readFile(path)).toString("base64"),
1043
- encoding: "base64",
1044
- ...mode & 73 ? { mode } : {}
1045
- };
1046
- }
1047
- function workspaceDependencyNames(manifest) {
1048
- const sections = [
1049
- manifest.dependencies,
1050
- manifest.devDependencies,
1051
- manifest.optionalDependencies,
1052
- manifest.peerDependencies
1053
- ];
1054
- return [...new Set(sections.flatMap((section) => Object.entries(section || {})).filter(([, specifier]) => specifier.startsWith("workspace:")).map(([name]) => name))];
1055
- }
1056
- async function addPnpmWorkspaceDependencies(files, workspaceRoot, scanRoot, patterns, selectedManifest) {
1057
- const packages = /* @__PURE__ */ new Map();
1058
- for (const pattern of patterns.filter((pattern) => !pattern.startsWith("!"))) for await (const match of glob(`${pattern}/package.json`, {
1059
- cwd: workspaceRoot,
1060
- exclude: ["**/node_modules/**", "**/.git/**"]
1061
- })) {
1062
- const manifestPath = resolve$1(workspaceRoot, match);
1063
- if (!await isFile(manifestPath, scanRoot)) continue;
1064
- if (!isWorkspacePackage(relative$1(workspaceRoot, dirname$1(manifestPath)).replaceAll("\\", "/") || ".", patterns)) continue;
1065
- const manifest = parseManifest(await readFile(manifestPath, "utf8"), manifestPath);
1066
- if (manifest.name) packages.set(manifest.name, {
1067
- manifest,
1068
- root: dirname$1(manifestPath)
1069
- });
1070
- }
1071
- const pending = workspaceDependencyNames(selectedManifest);
1072
- const included = /* @__PURE__ */ new Set();
1073
- while (pending.length) {
1074
- const name = pending.shift();
1075
- if (included.has(name)) continue;
1076
- const dependency = packages.get(name);
1077
- if (!dependency) throw new Error(`[vitehub] Sandbox package references missing pnpm workspace dependency "${name}".`);
1078
- included.add(name);
1079
- pending.push(...workspaceDependencyNames(dependency.manifest));
1080
- for await (const match of glob("**/*", {
1081
- cwd: dependency.root,
1082
- exclude: projectFileExcludes
1083
- })) await addProjectFile(files, workspaceRoot, resolve$1(dependency.root, match), scanRoot);
1084
- }
1085
- }
1086
- async function resolveSandboxProject(definitionFile, scanRoot, options = {}) {
1087
- const root = await realpath(resolve$1(scanRoot));
1088
- const definition = await realpath(resolve$1(definitionFile));
1089
- if (!isInside(root, definition)) throw new Error(`[vitehub] Sandbox Definition is outside its scan root: ${definitionFile}`);
1090
- const packageRoot = await firstDirectoryWithFile(ancestors(dirname$1(definition), root), "package.json", root);
1091
- if (!packageRoot) throw new Error(`[vitehub] Sandbox Definition "${definitionFile}" requires a package.json between its directory and "${root}".`);
1092
- const manifestPath = resolve$1(packageRoot, "package.json");
1093
- const manifest = parseManifest(await readFile(manifestPath, "utf8"), manifestPath);
1094
- const sandboxOptions = options.readSandboxOptions ? parseSandboxProjectOptions(manifest, manifestPath) : void 0;
1095
- const declaredManager = packageManagerFromField(manifest.packageManager);
1096
- const declaredMajor = packageManagerMajor(manifest.packageManager);
1097
- const workspace = declaredManager && declaredManager !== "pnpm" ? void 0 : await findPnpmWorkspaceRoot(packageRoot, root);
1098
- const installRoot = workspace?.directory || packageRoot;
1099
- const packageLock = await findLockfile([installRoot], root, workspace ? "pnpm" : declaredManager);
1100
- const manager = declaredManager || packageLock?.manager || (workspace ? "pnpm" : "npm");
1101
- const lock = packageLock?.manager === manager ? packageLock : void 0;
1102
- const lockfileMajor = manager === "yarn" && lock && declaredMajor === void 0 ? (await readFile(lock.path, "utf8")).includes("__metadata:") ? 2 : 1 : void 0;
1103
- const files = {};
1104
- for await (const match of glob("**/*", {
1105
- cwd: packageRoot,
1106
- exclude: projectFileExcludes
1107
- })) await addProjectFile(files, installRoot, resolve$1(packageRoot, match), root);
1108
- if (installRoot !== packageRoot) await addProjectFile(files, installRoot, resolve$1(installRoot, "package.json"), root);
1109
- if (workspace) {
1110
- await addProjectFile(files, installRoot, workspace.file, root);
1111
- await addPnpmWorkspaceDependencies(files, installRoot, root, parsePnpmWorkspacePackages(workspace.source), manifest);
1112
- }
1113
- if (lock) await addProjectFile(files, installRoot, lock.path, root);
1114
- const packagePath = relative$1(installRoot, packageRoot).replaceAll("\\", "/") || ".";
1115
- const identity = JSON.stringify({
1116
- files,
1117
- manager,
1118
- packagePath
1119
- });
1120
- return {
1121
- digest: createHash("sha256").update(identity).digest("hex"),
1122
- files,
1123
- install: {
1124
- args: installArgs(manager, Boolean(lock), declaredManager === manager ? declaredMajor : lockfileMajor),
1125
- command: manager,
1126
- cwd: "."
1127
- },
1128
- ...sandboxOptions ? { options: sandboxOptions } : {},
1129
- packagePath
1130
- };
1131
- }
1132
- async function firstDirectoryWithFile(directories, file, root) {
1133
- for (const directory of directories) if (await isFile(resolve$1(directory, file), root)) return directory;
1134
- }
1135
- async function findLockfile(directories, root, manager) {
1136
- const candidates = manager ? lockfiles.filter((lock) => lock.manager === manager) : lockfiles;
1137
- for (const directory of directories) for (const candidate of candidates) {
1138
- const path = resolve$1(directory, candidate.file);
1139
- if (await isFile(path, root)) return {
1140
- directory,
1141
- manager: candidate.manager,
1142
- path
1143
- };
1144
- }
1145
- }
1146
- //#endregion
1147
- //#region src/internal/package-entry.ts
1148
- const typescript = createRequire(import.meta.url)("typescript");
1149
- const runtimeExportConditions = new Set([
1150
- "default",
1151
- "import",
1152
- "module-sync",
1153
- "node",
1154
- "node-addons"
1155
- ]);
1156
- function isExecutableTypeScriptModule(path) {
1157
- return /\.(?:ts|mts)$/.test(path) && !/\.d\.(?:ts|mts)$/.test(path);
1158
- }
1159
- function executablePackageModulePath(path) {
1160
- const suffixIndex = path.search(/[?#]/);
1161
- const modulePath = suffixIndex === -1 ? path : path.slice(0, suffixIndex);
1162
- const suffix = suffixIndex === -1 ? "" : path.slice(suffixIndex);
1163
- return isExecutableTypeScriptModule(modulePath) ? `${modulePath}.mjs${suffix}` : path;
1164
- }
1165
- function projectFileSource(project, path) {
1166
- const file = project.files[path];
1167
- if (!file) throw new Error(`[vitehub] Sandbox package project is missing required file: ${path}`);
1168
- return Buffer.from(file.contents, file.encoding).toString();
1169
- }
1170
- function parseRuntimeManifest(project, path) {
1171
- try {
1172
- return JSON.parse(projectFileSource(project, path));
1173
- } catch (error) {
1174
- throw new Error(`[vitehub] Sandbox package manifest is invalid JSON: ${path}`, { cause: error });
1175
- }
1176
- }
1177
- function selectedPackageManifest(project) {
1178
- const path = project.packagePath === "." ? "package.json" : `${project.packagePath}/package.json`;
1179
- const manifest = parseRuntimeManifest(project, path);
1180
- if (manifest.type !== "module") throw new Error(`[vitehub] Sandbox package manifest "${path}" must set "type" to "module". Canonical Sandbox package entrypoints are ESM.`);
1181
- return manifest;
1182
- }
1183
- function declaredWorkspaceDependencyNames(manifest) {
1184
- return [...new Set([
1185
- manifest.dependencies,
1186
- manifest.devDependencies,
1187
- manifest.optionalDependencies,
1188
- manifest.peerDependencies
1189
- ].flatMap((section) => Object.entries(section || {})).filter(([, specifier]) => specifier.startsWith("workspace:")).map(([name]) => name))];
1190
- }
1191
- function runtimeExportTargets(value, patternMatch, allowPackageTarget = false) {
1192
- if (typeof value === "string") {
1193
- const target = patternMatch === void 0 ? value : value.replaceAll("*", patternMatch);
1194
- return target.startsWith("./") || allowPackageTarget ? [target] : [];
1195
- }
1196
- if (Array.isArray(value)) {
1197
- for (const target of value) {
1198
- const targets = runtimeExportTargets(target, patternMatch, allowPackageTarget);
1199
- if (targets.length) return targets;
1200
- }
1201
- return [];
1202
- }
1203
- if (!value || typeof value !== "object") return [];
1204
- for (const [condition, target] of Object.entries(value)) if (runtimeExportConditions.has(condition)) {
1205
- const targets = runtimeExportTargets(target, patternMatch, allowPackageTarget);
1206
- if (targets.length) return targets;
1207
- }
1208
- return [];
1209
- }
1210
- function runtimeTargetsForPackageSpecifier(manifest, packageName, specifier) {
1211
- if (manifest.exports !== void 0) {
1212
- let selected = manifest.exports;
1213
- let patternMatch;
1214
- if (selected && typeof selected === "object" && !Array.isArray(selected)) {
1215
- const entries = selected;
1216
- if (Object.keys(entries).some((key) => key.startsWith("."))) {
1217
- const subpath = specifier === packageName ? "." : `.${specifier.slice(packageName.length)}`;
1218
- if (Object.hasOwn(entries, subpath)) selected = entries[subpath];
1219
- else {
1220
- const pattern = Object.keys(entries).filter((key) => {
1221
- const star = key.indexOf("*");
1222
- if (star === -1) return false;
1223
- return subpath.startsWith(key.slice(0, star)) && subpath.endsWith(key.slice(star + 1));
1224
- }).sort((left, right) => {
1225
- const leftStar = left.indexOf("*");
1226
- return right.indexOf("*") - leftStar || right.length - left.length;
1227
- })[0];
1228
- if (pattern) {
1229
- const star = pattern.indexOf("*");
1230
- patternMatch = subpath.slice(star, subpath.length - (pattern.length - star - 1));
1231
- selected = entries[pattern];
1232
- } else selected = void 0;
1233
- }
1234
- } else if (specifier !== packageName) selected = void 0;
1235
- } else if (specifier !== packageName) selected = void 0;
1236
- return runtimeExportTargets(selected, patternMatch);
1237
- }
1238
- if (specifier !== packageName) return [`.${specifier.slice(packageName.length)}`];
1239
- return typeof manifest.main === "string" ? [manifest.main] : ["./index.js"];
1240
- }
1241
- function runtimeTargetsForPackageImport(manifest, specifier) {
1242
- if (!manifest.imports || typeof manifest.imports !== "object" || Array.isArray(manifest.imports)) return [];
1243
- const entries = manifest.imports;
1244
- let selected = entries[specifier];
1245
- let patternMatch;
1246
- if (selected === void 0) {
1247
- const pattern = Object.keys(entries).filter((key) => {
1248
- const star = key.indexOf("*");
1249
- if (star === -1) return false;
1250
- return specifier.startsWith(key.slice(0, star)) && specifier.endsWith(key.slice(star + 1));
1251
- }).sort((left, right) => {
1252
- const leftStar = left.indexOf("*");
1253
- return right.indexOf("*") - leftStar || right.length - left.length;
1254
- })[0];
1255
- if (!pattern) return [];
1256
- const star = pattern.indexOf("*");
1257
- patternMatch = specifier.slice(star, specifier.length - (pattern.length - star - 1));
1258
- selected = entries[pattern];
1259
- }
1260
- return runtimeExportTargets(selected, patternMatch, true);
1261
- }
1262
- function isTypeScriptRuntimeTarget(path) {
1263
- const target = path.replace(/[?#].*$/, "");
1264
- return /\.[cm]?tsx?$/.test(target) && !/\.d\.[cm]?ts$/.test(target);
1265
- }
1266
- function validateWorkspaceJavaScriptGraph(project, packageName, manifest, manifestPath, targets) {
1267
- const pending = targets.filter((target) => /\.(?:js|mjs)$/.test(target.replace(/[?#].*$/, ""))).map((target) => normalize$1(join$1(dirname$2(manifestPath), target.replace(/[?#].*$/, ""))));
1268
- const visited = /* @__PURE__ */ new Set();
1269
- const runtimePackages = /* @__PURE__ */ new Set();
1270
- while (pending.length) {
1271
- const path = pending.shift();
1272
- if (visited.has(path) || !Object.hasOwn(project.files, path)) continue;
1273
- visited.add(path);
1274
- const source = projectFileSource(project, path);
1275
- for (const specifier of findRuntimeModuleSpecifiers(source, path)) {
1276
- if (specifier.startsWith("#")) {
1277
- for (const aliasTarget of runtimeTargetsForPackageImport(manifest, specifier)) {
1278
- if (!/^\.\.?\//.test(aliasTarget)) {
1279
- runtimePackages.add(aliasTarget);
1280
- continue;
1281
- }
1282
- const target = normalize$1(join$1(dirname$2(manifestPath), aliasTarget.replace(/[?#].*$/, "")));
1283
- 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.`);
1284
- if (/\.(?:js|mjs)$/.test(target)) pending.push(target);
1285
- }
1286
- continue;
1287
- }
1288
- if (!/^\.\.?\//.test(specifier)) {
1289
- if (!specifier.startsWith("node:")) runtimePackages.add(specifier);
1290
- continue;
1291
- }
1292
- const target = normalize$1(join$1(dirname$2(path), specifier.replace(/[?#].*$/, "")));
1293
- 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.`);
1294
- if (/\.(?:js|mjs)$/.test(target)) pending.push(target);
1295
- }
1296
- }
1297
- return runtimePackages;
1298
- }
1299
- function validateWorkspaceRuntimeExports(project, runtimePackages, declaredWorkspacePackages) {
1300
- const pending = [...runtimePackages];
1301
- if (!pending.length) return;
1302
- const workspacePackages = new Set(declaredWorkspacePackages);
1303
- if (!workspacePackages.size) return;
1304
- const workspaceFile = project.files["pnpm-workspace.yaml"];
1305
- if (!workspaceFile) return;
1306
- const workspacePatterns = parsePnpmWorkspacePackages(Buffer.from(workspaceFile.contents, workspaceFile.encoding).toString());
1307
- const manifests = /* @__PURE__ */ new Map();
1308
- for (const path of Object.keys(project.files).filter((path) => path === "package.json" || path.endsWith("/package.json") && isWorkspacePackage(dirname$2(path), workspacePatterns))) {
1309
- let manifest;
1310
- try {
1311
- const value = JSON.parse(projectFileSource(project, path));
1312
- if (!value || typeof value !== "object" || Array.isArray(value)) continue;
1313
- manifest = value;
1314
- } catch {
1315
- continue;
1316
- }
1317
- if (typeof manifest.name === "string") manifests.set(manifest.name, {
1318
- manifest,
1319
- path
1320
- });
1321
- }
1322
- const visited = /* @__PURE__ */ new Set();
1323
- while (pending.length) {
1324
- const specifier = pending.shift();
1325
- if (visited.has(specifier)) continue;
1326
- visited.add(specifier);
1327
- const packageName = barePackageName(specifier);
1328
- if (!workspacePackages.has(packageName)) continue;
1329
- const dependency = manifests.get(packageName);
1330
- if (!dependency) continue;
1331
- const targets = runtimeTargetsForPackageSpecifier(dependency.manifest, packageName, specifier);
1332
- const target = targets.find(isTypeScriptRuntimeTarget);
1333
- 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.`);
1334
- const runtimePackageEdges = validateWorkspaceJavaScriptGraph(project, packageName, dependency.manifest, dependency.path, targets);
1335
- for (const name of declaredWorkspaceDependencyNames(dependency.manifest)) workspacePackages.add(name);
1336
- pending.push(...runtimePackageEdges);
1337
- }
1338
- }
1339
- function isInsideSelectedPackage(project, path) {
1340
- if (project.packagePath === ".") return path !== ".." && !path.startsWith("../");
1341
- return path.startsWith(`${project.packagePath}/`);
1342
- }
1343
- function removeTypeOnlyModuleDeclarations(context) {
1344
- return (sourceFile) => context.factory.updateSourceFile(sourceFile, sourceFile.statements.filter((statement) => {
1345
- if (typescript.isImportDeclaration(statement)) {
1346
- const clause = statement.importClause;
1347
- const bindings = clause?.namedBindings;
1348
- return !(clause && !clause.name && bindings && typescript.isNamedImports(bindings) && bindings.elements.length > 0 && bindings.elements.every((element) => element.isTypeOnly));
1349
- }
1350
- if (typescript.isExportDeclaration(statement)) {
1351
- const clause = statement.exportClause;
1352
- return !(clause && typescript.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly));
1353
- }
1354
- return true;
1355
- }));
1356
- }
1357
- function transpilePackageModule(source, path) {
1358
- const result = typescript.transpileModule(source, {
1359
- compilerOptions: {
1360
- module: typescript.ModuleKind.ESNext,
1361
- target: typescript.ScriptTarget.ES2022,
1362
- verbatimModuleSyntax: true
1363
- },
1364
- fileName: path,
1365
- reportDiagnostics: true,
1366
- transformers: { before: [removeTypeOnlyModuleDeclarations] }
1367
- });
1368
- const errors = result.diagnostics?.filter((diagnostic) => diagnostic.category === typescript.DiagnosticCategory.Error) || [];
1369
- if (errors.length) {
1370
- const details = errors.map((diagnostic) => typescript.flattenDiagnosticMessageText(diagnostic.messageText, "\n")).join("\n");
1371
- throw new Error(`[vitehub] Sandbox package module "${path}" could not be transpiled:\n${details}`);
1372
- }
1373
- return result.outputText;
1374
- }
1375
- function barePackageName(specifier) {
1376
- const [scopeOrName, name] = specifier.split("/");
1377
- return scopeOrName.startsWith("@") && name ? `${scopeOrName}/${name}` : scopeOrName;
1378
- }
1379
- function isUnsupportedExternalModuleSpecifier(specifier) {
1380
- return specifier.startsWith("/") || specifier.startsWith("\\") || /^[A-Za-z][A-Za-z\d+.-]*:/.test(specifier) && !specifier.startsWith("node:");
1381
- }
1382
- function throwCommonJSSyntax(path, commonJS) {
1383
- const syntax = {
1384
- "exports-assignment": "exports assignment",
1385
- "exports-reference": "exports reference",
1386
- "import-equals": "import = require()",
1387
- "module-exports-assignment": "module.exports assignment",
1388
- "module-reference": "module reference",
1389
- require: "require()",
1390
- "require-property": commonJS.specifier ? `require.${commonJS.specifier}` : "require property access"
1391
- }[commonJS.syntax];
1392
- const target = commonJS.specifier && commonJS.syntax !== "require-property" ? ` for "${commonJS.specifier}"` : "";
1393
- throw new Error(`[vitehub] Sandbox package module "${path}" uses CommonJS ${syntax}${target}. Canonical Sandbox package entrypoints are ESM; use import or export syntax.`);
1394
- }
1395
- function validatePackageModuleSpecifiers(project, entry, packageName) {
1396
- const pending = [entry];
1397
- const runtimePackages = /* @__PURE__ */ new Set();
1398
- const visited = /* @__PURE__ */ new Set();
1399
- while (pending.length) {
1400
- const path = pending.shift();
1401
- if (visited.has(path)) continue;
1402
- visited.add(path);
1403
- const source = projectFileSource(project, path);
1404
- 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.`);
1405
- const importEquals = findCommonJSImportEqualsSpecifiers(source, path)[0];
1406
- if (importEquals) throwCommonJSSyntax(path, importEquals);
1407
- const moduleSpecifiers = findRuntimeModuleSpecifiers(source, path);
1408
- for (const specifier of moduleSpecifiers) {
1409
- 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.`);
1410
- 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.`);
1411
- 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.`);
1412
- if (!/^\.\.?\//.test(specifier) && !specifier.startsWith("node:")) runtimePackages.add(specifier);
1413
- }
1414
- for (const specifier of moduleSpecifiers.filter((specifier) => /^\.\.?\//.test(specifier))) {
1415
- const target = normalize$1(join$1(dirname$2(path), specifier.replace(/[?#].*$/, "")));
1416
- 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.`);
1417
- 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.`);
1418
- 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.`);
1419
- 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.`);
1420
- 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.`);
1421
- if (/\.(?:js|mjs|ts|mts)$/.test(target)) pending.push(target);
1422
- }
1423
- }
1424
- return {
1425
- modulePaths: visited,
1426
- runtimePackages
1427
- };
1428
- }
1429
- function prepareExecutablePackageProject(project, entry) {
1430
- const manifest = selectedPackageManifest(project);
1431
- const { modulePaths, runtimePackages } = validatePackageModuleSpecifiers(project, entry, typeof manifest.name === "string" ? manifest.name : void 0);
1432
- validateWorkspaceRuntimeExports(project, runtimePackages, declaredWorkspaceDependencyNames(manifest));
1433
- const generatedFiles = {};
1434
- const executableSources = /* @__PURE__ */ new Map();
1435
- const originalPaths = /* @__PURE__ */ new Map();
1436
- const files = { ...project.files };
1437
- for (const path of modulePaths) {
1438
- const file = project.files[path];
1439
- const source = Buffer.from(file.contents, file.encoding).toString();
1440
- const rewritten = rewriteRuntimeRelativeModuleSpecifiers(source, path, executablePackageModulePath);
1441
- if (isExecutableTypeScriptModule(path)) {
1442
- const executablePath = executablePackageModulePath(path);
1443
- if (Object.hasOwn(project.files, executablePath)) throw new Error(`[vitehub] Sandbox package module "${path}" conflicts with generated executable "${executablePath}". Rename the existing file.`);
1444
- const executableSource = transpilePackageModule(rewritten, path);
1445
- executableSources.set(executablePath, executableSource);
1446
- originalPaths.set(executablePath, path);
1447
- generatedFiles[executablePath] = {
1448
- contents: Buffer.from(executableSource).toString("base64"),
1449
- encoding: "base64"
1450
- };
1451
- } else {
1452
- executableSources.set(path, rewritten);
1453
- originalPaths.set(path, path);
1454
- if (rewritten !== source) generatedFiles[path] = {
1455
- ...file,
1456
- contents: Buffer.from(rewritten).toString("base64")
1457
- };
1458
- }
1459
- }
1460
- const commonJS = findExecutableCommonJSModuleSpecifiers(executableSources)[0];
1461
- if (commonJS) throwCommonJSSyntax(originalPaths.get(commonJS.path) || commonJS.path, commonJS);
1462
- if (!Object.keys(generatedFiles).length) return {
1463
- entry,
1464
- project
1465
- };
1466
- Object.assign(files, generatedFiles);
1467
- const digest = createHash("sha256").update(JSON.stringify({
1468
- generatedFiles,
1469
- project: project.digest
1470
- })).digest("hex");
1471
- return {
1472
- entry: executablePackageModulePath(entry),
1473
- project: {
1474
- ...project,
1475
- digest,
1476
- files
1477
- }
1478
- };
1479
- }
1480
- //#endregion
1481
- //#region src/bundle.ts
1482
- const SHIM_NAMESPACE = "vitehub-sandbox-runtime-shim";
1483
- async function bundleSandboxDefinition(source, file, options = {}) {
1484
- if (options.execution === "module" && options.project) {
1485
- const entry = `${options.project.packagePath === "." ? "" : `${options.project.packagePath}/`}${basename(file)}`;
1486
- const executable = prepareExecutablePackageProject(options.project, entry);
1487
- return {
1488
- entry: executable.entry,
1489
- execution: "module",
1490
- modules: {},
1491
- project: executable.project
1492
- };
1493
- }
1494
- const bundle = await bundleDiscoveredDefinitionModuleGraph({
1495
- alias: options.alias,
1496
- filename: file,
1497
- packages: options.project ? "external" : "bundle",
1498
- source,
1499
- plugins: [{
1500
- name: SHIM_NAMESPACE,
1501
- setup(pluginBuild) {
1502
- pluginBuild.onResolve({ filter: /^@vite-hub\/sandbox(?:\/runtime\/public)?$/ }, () => ({
1503
- path: "sandbox-runtime-shim",
1504
- namespace: SHIM_NAMESPACE
1505
- }));
1506
- pluginBuild.onLoad({
1507
- filter: /.*/,
1508
- namespace: SHIM_NAMESPACE
1509
- }, () => ({
1510
- contents: [
1511
- "function hasStandardValidator(value) {",
1512
- " return !!value && typeof value === \"object\" && !!value[\"~standard\"] && typeof value[\"~standard\"].validate === \"function\"",
1513
- "}",
1514
- "",
1515
- "function createValidationError(cause) {",
1516
- " if (cause instanceof Error)",
1517
- " return cause",
1518
- " const message = cause && typeof cause === \"object\" && typeof cause.message === \"string\"",
1519
- " ? cause.message",
1520
- " : \"Validation failed\"",
1521
- " return Object.assign(new Error(message), cause && typeof cause === \"object\" ? cause : {})",
1522
- "}",
1523
- "",
1524
- "export async function readValidatedPayload(payload, validate) {",
1525
- " if (hasStandardValidator(validate)) {",
1526
- " const result = await validate[\"~standard\"].validate(payload)",
1527
- " if (result.issues?.length)",
1528
- " throw createValidationError({ message: \"Validation failed\", issues: result.issues })",
1529
- " return result.value",
1530
- " }",
1531
- " try {",
1532
- " const result = await validate(payload)",
1533
- " if (result === false)",
1534
- " throw createValidationError({ message: \"Validation failed\" })",
1535
- " return result === true || result == null ? payload : result",
1536
- " }",
1537
- " catch (error) {",
1538
- " throw createValidationError(error)",
1539
- " }",
1540
- "}",
1541
- "",
1542
- "export function defineSandbox(input) {",
1543
- " const { run, ...options } = input",
1544
- " return { run, options: Object.keys(options).length ? options : undefined }",
1545
- "}"
1546
- ].join("\n"),
1547
- loader: "js"
1548
- }));
1549
- }
1550
- }]
1551
- });
1552
- if (!options.project) return {
1553
- ...bundle,
1554
- ...options.execution ? { execution: options.execution } : {}
1555
- };
1556
- const prefix = options.project.packagePath === "." ? ".vitehub-sandbox" : `${options.project.packagePath}/.vitehub-sandbox`;
1557
- const modules = {
1558
- [`${prefix}/package.json`]: JSON.stringify({
1559
- private: true,
1560
- type: "module"
1561
- }),
1562
- ...Object.fromEntries(Object.entries(bundle.modules).map(([path, contents]) => [`${prefix}/${path}`, contents]))
1563
- };
1564
- const digest = createHash("sha256").update(JSON.stringify({
1565
- modules,
1566
- packagePath: options.project.packagePath,
1567
- project: options.project.digest
1568
- })).digest("hex");
1569
- return {
1570
- entry: `${prefix}/${bundle.entry}`,
1571
- ...options.execution ? { execution: options.execution } : {},
1572
- modules,
1573
- project: {
1574
- ...options.project,
1575
- digest
1576
- }
1577
- };
1578
- }
1579
- //#endregion
1580
- //#region src/definition-options.ts
1581
- const require = createRequire(import.meta.url);
1582
- const sandboxDefinitionSyntax = "`defineSandbox({ run, ...options })`";
1583
- function getTypeScript() {
1584
- return require("typescript");
1585
- }
1586
- function readStaticValue(node) {
1587
- const ts = getTypeScript();
1588
- if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
1589
- if (ts.isNumericLiteral(node)) return Number(node.text);
1590
- if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
1591
- if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
1592
- if (node.kind === ts.SyntaxKind.NullKeyword) return null;
1593
- if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(node.operand)) return -Number(node.operand.text);
1594
- if (ts.isParenthesizedExpression(node)) return readStaticValue(node.expression);
1595
- if (ts.isArrayLiteralExpression(node)) return node.elements.map((element) => {
1596
- if (!ts.isExpression(element)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options arrays must use static values.`);
1597
- return readStaticValue(element);
1598
- });
1599
- if (ts.isObjectLiteralExpression(node)) {
1600
- const value = {};
1601
- for (const property of node.properties) {
1602
- if (!ts.isPropertyAssignment(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use plain object literals.`);
1603
- const key = ts.isIdentifier(property.name) ? property.name.text : ts.isStringLiteral(property.name) ? property.name.text : void 0;
1604
- if (!key) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options only support identifier or string-literal keys.`);
1605
- value[key] = readStaticValue(property.initializer);
1606
- }
1607
- return value;
1608
- }
1609
- throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use static JSON-serializable values.`);
1610
- }
1611
- function readDefinitionObject(sourceFile) {
1612
- const ts = getTypeScript();
1613
- for (const statement of sourceFile.statements) {
1614
- if (!ts.isExportAssignment(statement)) continue;
1615
- const expression = statement.expression;
1616
- if (!ts.isCallExpression(expression) || !ts.isIdentifier(expression.expression) || expression.expression.text !== "defineSandbox") continue;
1617
- if (expression.arguments.length !== 1 || !ts.isObjectLiteralExpression(expression.arguments[0])) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires one direct object literal.`);
1618
- return expression.arguments[0];
1619
- }
1620
- }
1621
- function propertyName(property) {
1622
- const ts = getTypeScript();
1623
- if (!("name" in property) || !property.name) return void 0;
1624
- return ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : void 0;
1625
- }
1626
- async function extractSandboxDefinitionOptions(file) {
1627
- const source = await readFile(file, "utf8");
1628
- const ts = getTypeScript();
1629
- const input = readDefinitionObject(ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS));
1630
- if (!input) return void 0;
1631
- const options = {};
1632
- let hasRun = false;
1633
- for (const property of input.properties) {
1634
- const key = propertyName(property);
1635
- if (key === "run" && ts.isShorthandPropertyAssignment(property)) {
1636
- hasRun = true;
1637
- continue;
1638
- }
1639
- if (!key || !ts.isPropertyAssignment(property) && !ts.isMethodDeclaration(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires explicit object properties.`);
1640
- if (key === "run") {
1641
- hasRun = true;
1642
- continue;
1643
- }
1644
- if (!ts.isPropertyAssignment(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use static values.`);
1645
- options[key] = readStaticValue(property.initializer);
1646
- }
1647
- if (!hasRun) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires a \`run\` handler.`);
1648
- return Object.keys(options).length ? options : void 0;
1649
- }
1650
- //#endregion
1651
- //#region src/type-template.ts
1652
- function createDefinitionContract(definition) {
1653
- const module = `typeof import(${JSON.stringify(definition.handler)})`;
1654
- if (definition.kind === "definition") return `{ payload: Parameters<${module}['default']['run']>[0], result: Awaited<ReturnType<${module}['default']['run']>> }`;
1655
- return `SandboxPackageContract<${module}['default'], ${definition.hasPayloadType ? `import(${JSON.stringify(definition.handler)}).SandboxPayload` : "unknown"}>`;
1656
- }
1657
- function createSandboxTypeTemplateContents(definitions) {
1658
- return [
1659
- `declare module '#vitehub-sandbox-registry' {`,
1660
- ` type SandboxPackageContract<TDefault, TFallbackPayload> = TDefault extends (...args: infer TArgs) => infer TResult`,
1661
- ` ? { payload: TArgs extends [] ? unknown : TArgs[0], result: Awaited<TResult> }`,
1662
- ` : { payload: TFallbackPayload, result: Awaited<TDefault> }`,
1663
- ` export interface SandboxDefinitionModules {`,
1664
- ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: ${createDefinitionContract(definition)},`),
1665
- ` }`,
1666
- ` const sandboxRegistry: {`,
1667
- ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: () => Promise<{ default?: { bundle: import('@vite-hub/sandbox').SandboxDefinitionBundle, options?: import('@vite-hub/sandbox').SandboxDefinitionOptions } }>,`),
1668
- ` }`,
1669
- ` export default sandboxRegistry`,
1670
- `}`,
1671
- ``
1672
- ].join("\n");
1673
- }
1674
- //#endregion
1675
- //#region src/feature.ts
1676
- const sandboxRuntimeDependencyByProvider = {
1677
- cloudflare: "@cloudflare/sandbox",
1678
- vercel: "@vercel/sandbox"
1679
- };
1680
- function resolveSandboxProviderLoaderTarget(provider, deps) {
1681
- if (provider) return provider;
1682
- const hasCloudflareSandbox = Boolean(deps["@cloudflare/sandbox"]);
1683
- if (hasCloudflareSandbox === Boolean(deps["@vercel/sandbox"])) return void 0;
1684
- return hasCloudflareSandbox ? "cloudflare" : "vercel";
1685
- }
1686
- const sandboxProviderLoaderSpecifiers = [
1687
- "vitehub-sandbox-provider-loader",
1688
- "@vite-hub/sandbox/runtime/provider-loader",
1689
- "virtual:vitehub-sandbox-provider-loader",
1690
- "#vitehub-sandbox-provider-loader"
1691
- ];
1692
- function createSandboxProviderLoaderAliases(defaultProviderName) {
1693
- const keys = sandboxProviderLoaderSpecifiers;
1694
- if (defaultProviderName) return keys.map((key) => ({
1695
- key,
1696
- artifactKey: "sandbox-provider-loader"
1697
- }));
1698
- const providerLoaderPath = resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./runtime/provider-loader", "runtime/provider-loader.js");
1699
- return keys.map((key) => ({
1700
- key,
1701
- value: providerLoaderPath
1702
- }));
1703
- }
1704
- function createSandboxManifest(aliasPath, typeTemplate) {
1705
- return {
1706
- alias: "@vite-hub/sandbox",
1707
- aliasPath,
1708
- imports: [
1709
- {
1710
- name: "defineSandbox",
1711
- from: "@vite-hub/sandbox",
1712
- meta: { description: "Define a free-form sandbox resource." }
1713
- },
1714
- {
1715
- name: "readValidatedPayload",
1716
- as: "readValidatedSandboxPayload",
1717
- from: "@vite-hub/sandbox",
1718
- meta: { description: "Validate sandbox payload input before execution." }
1719
- },
1720
- {
1721
- name: "runSandbox",
1722
- from: "@vite-hub/sandbox",
1723
- meta: { description: "Run a named sandbox definition." }
1724
- },
1725
- {
1726
- name: "SandboxDefinition",
1727
- as: "SandboxDefinition",
1728
- from: "@vite-hub/sandbox",
1729
- type: true
1730
- },
1731
- {
1732
- name: "SandboxRunResult",
1733
- as: "SandboxRunResult",
1734
- from: "@vite-hub/sandbox",
1735
- type: true
1736
- }
1737
- ],
1738
- typeTemplate: {
1739
- filename: "runtime/sandbox.d.ts",
1740
- contents: typeTemplate
1741
- }
1742
- };
1743
- }
1744
- function normalizeSandboxDefinitionOptions(name, options) {
1745
- if (!options) return void 0;
1746
- try {
1747
- return JSON.parse(JSON.stringify(options));
1748
- } catch (error) {
1749
- throw new Error(`[vitehub] Sandbox definition "${name}" options must be JSON-serializable.`, { cause: error });
1750
- }
1751
- }
1752
- async function loadSandboxDefinitionMetadata(definitions, rootDir) {
1753
- return await Promise.all(definitions.map(async (definition) => {
1754
- const project = await resolveSandboxProject(definition.handler, rootDir, { readSandboxOptions: definition.kind === "package-entry" });
1755
- const source = definition.kind === "package-entry" ? await readFile(definition.handler, "utf8") : void 0;
1756
- return {
1757
- hasPayloadType: source ? hasExportedType(source, definition.handler, "SandboxPayload") : false,
1758
- kind: definition.kind,
1759
- name: definition.name,
1760
- options: definition.kind === "package-entry" ? project.options : normalizeSandboxDefinitionOptions(definition.name, await extractSandboxDefinitionOptions(definition.handler)),
1761
- project
1762
- };
1763
- }));
1764
- }
1765
- function createSandboxRegistryContents(definitions) {
1766
- return [
1767
- "const registry = {",
1768
- ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: async () => import(${JSON.stringify(definition.definitionModulePath)}),`),
1769
- "}",
1770
- "export default registry",
1771
- ""
1772
- ].join("\n");
1773
- }
1774
- function createSandboxProviderLoaderContents(provider) {
1775
- const providerExport = sandboxProviderRuntimeExport(provider);
1776
- const providerLoaderPath = resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", `./runtime/providers/${provider}`, `runtime/providers/${provider}.js`);
1777
- return [
1778
- `import { ${providerExport} as resolveSandboxBox } from ${JSON.stringify(providerLoaderPath)}`,
1779
- "",
1780
- "export async function loadSandboxRuntimeProvider(selectedProvider) {",
1781
- ` if (selectedProvider !== ${JSON.stringify(provider)})`,
1782
- " throw new Error(`[vitehub] Unsupported sandbox provider for this hosted build: ${selectedProvider}`)",
1783
- " return {",
1784
- " resolveSandboxBox,",
1785
- " }",
1786
- "}",
1787
- ""
1788
- ].join("\n");
1789
- }
1790
- function sandboxProviderRuntimeExport(provider) {
1791
- return provider === "cloudflare" ? "resolveCloudflareSandboxBox" : "resolveVercelSandboxBox";
1792
- }
1793
- function resolveSandboxFeatureConfig(sandboxConfig, hosting) {
1794
- if (getSandboxFeatureProvider(sandboxConfig)?.provider) return { ...sandboxConfig };
1795
- const config = { ...sandboxConfig };
1796
- const hostedProvider = getSupportedHostingProvider(hosting, ["cloudflare", "vercel"]);
1797
- if (hostedProvider) return {
1798
- ...config,
1799
- provider: hostedProvider
1800
- };
1801
- const unsupportedHostedProvider = deploymentPresetFromNitro(hosting);
1802
- if (unsupportedHostedProvider) throw new TypeError("[vitehub] Sandbox hosting inference does not support " + unsupportedHostedProvider + ". An explicit `sandbox.provider` is required.");
1803
- return config;
1804
- }
1805
- async function createSandboxFeaturePlan(sandboxConfig, definitions, paths, deps, hosting, discoveredDefinitionOptions = {}) {
1806
- const resolvedConfig = definitions.length > 0 ? resolveSandboxFeatureConfig(sandboxConfig, hosting) : { ...sandboxConfig };
1807
- const sandboxDefinitions = definitions.map((definition) => ({
1808
- ...definition,
1809
- definitionArtifactKey: `sandbox-definition:${definition.name}`,
1810
- definitionFilename: `runtime/sandbox-definitions/${toTemplateSafeName(definition.name)}.mjs`
1811
- }));
1812
- const definitionFileByName = /* @__PURE__ */ new Map();
1813
- for (const definition of sandboxDefinitions) {
1814
- const existing = definitionFileByName.get(definition.definitionFilename);
1815
- if (existing) throw new Error(`[vitehub] Sandbox definitions "${existing}" and "${definition.name}" generate the same artifact path "${definition.definitionFilename}".`);
1816
- definitionFileByName.set(definition.definitionFilename, definition.name);
1817
- }
1818
- const definitionMetadata = await loadSandboxDefinitionMetadata(definitions, discoveredDefinitionOptions.rootDir || process.cwd());
1819
- const metadataByName = new Map(definitionMetadata.map((definition) => [definition.name, definition]));
1820
- const manifest = createSandboxManifest(paths.aliasPath, createSandboxTypeTemplateContents(definitions.map((definition) => {
1821
- const metadata = metadataByName.get(definition.name);
1822
- return {
1823
- handler: definition.handler,
1824
- hasPayloadType: metadata?.hasPayloadType ?? false,
1825
- kind: definition.kind,
1826
- name: definition.name
1827
- };
1828
- })));
1829
- const { bundleAlias, featureImports = manifest.imports, ...definitionCompilerOptions } = discoveredDefinitionOptions;
1830
- const definitionCompiler = await createDiscoveredDefinitionCompiler({
1831
- ...definitionCompilerOptions,
1832
- featureImports
1833
- });
1834
- const defaultProvider = getSandboxFeatureProvider(resolvedConfig);
1835
- const defaultProviderName = defaultProvider?.provider;
1836
- const sandboxArtifacts = sandboxDefinitions.map((definition) => ({
1837
- key: definition.definitionArtifactKey,
1838
- filename: definition.definitionFilename,
1839
- async getContents() {
1840
- const source = await definitionCompiler.readSource(definition._meta.sourcePath);
1841
- const metadata = metadataByName.get(definition.name);
1842
- const bundle = await bundleSandboxDefinition(source, definition._meta.sourcePath, {
1843
- alias: bundleAlias,
1844
- execution: metadata?.kind === "package-entry" ? "module" : "definition",
1845
- project: metadata?.project
1846
- });
1847
- return `export default ${JSON.stringify({
1848
- bundle,
1849
- options: metadata?.options
1850
- })}\n`;
1851
- }
1852
- }));
1853
- const providerLoaderTarget = resolveSandboxProviderLoaderTarget(defaultProviderName, deps);
1854
- const cloudflareOptions = defaultProvider?.provider === "cloudflare" ? {
1855
- binding: typeof defaultProvider.binding === "string" ? defaultProvider.binding : defaultCloudflareSandboxBinding,
1856
- className: typeof defaultProvider.className === "string" ? defaultProvider.className : defaultCloudflareSandboxClassName,
1857
- migrationTag: typeof defaultProvider.migrationTag === "string" ? defaultProvider.migrationTag : "v1",
1858
- name: typeof defaultProvider.name === "string" ? defaultProvider.name : void 0
1859
- } : void 0;
1860
- return {
1861
- manifest,
1862
- aliases: [{
1863
- key: "#vitehub-sandbox-registry",
1864
- artifactKey: "sandbox-registry"
1865
- }, ...createSandboxProviderLoaderAliases(providerLoaderTarget)],
1866
- artifacts: [
1867
- ...sandboxArtifacts,
1868
- {
1869
- key: "sandbox-registry",
1870
- filename: "runtime/sandbox-registry.mjs",
1871
- getContents(emitted) {
1872
- return createSandboxRegistryContents(sandboxDefinitions.map((definition) => {
1873
- const artifact = emitted.get(definition.definitionArtifactKey);
1874
- if (!artifact) throw new Error(`[vitehub] Missing generated sandbox definition module for "${definition.name}".`);
1875
- return {
1876
- name: definition.name,
1877
- definitionModulePath: artifact.dst
1878
- };
1879
- }));
1880
- }
1881
- },
1882
- ...providerLoaderTarget ? [{
1883
- key: "sandbox-provider-loader",
1884
- filename: "runtime/sandbox-provider-loader.mjs",
1885
- getContents: () => createSandboxProviderLoaderContents(providerLoaderTarget)
1886
- }] : []
1887
- ],
1888
- cloudflare: cloudflareOptions
1889
- };
1890
- }
1891
- //#endregion
1892
- //#region ../internal/src/object.ts
1893
- function isPlainObject(value) {
1894
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1895
- }
1896
- //#endregion
1897
- //#region src/discovery.ts
1898
- const sandboxSuffixPattern = /\.sandbox\.(?:c|m)?[jt]s$/i;
1899
- const sandboxEntrypointFilenames = [
1900
- "index.ts",
1901
- "index.mts",
1902
- "index.js",
1903
- "index.mjs"
1904
- ];
1905
- function createDiscoveredSandboxDefinition(source, kind) {
1906
- return (context) => ({
1907
- handler: context.file,
1908
- kind,
1909
- name: context.name,
1910
- source,
1911
- _meta: {
1912
- filename: context.name,
1913
- sourcePath: context.file
1914
- }
1915
- });
1916
- }
1917
- function isServerSandboxFile(rootDir, file) {
1918
- const path = relative(rootDir, file).replace(/\\/g, "/");
1919
- return path.startsWith("server/sandboxes/") || path.startsWith("src/server/sandboxes/");
1920
- }
1921
- function normalizeSuffixSandboxName(rootDir, file) {
1922
- if (isServerSandboxFile(rootDir, file)) return void 0;
1923
- return normalizeSuffixDefinitionName(rootDir, file, sandboxSuffixPattern, { stripPrefix: "src/" });
1924
- }
1925
- function normalizeDirectorySandboxName(directory, file) {
1926
- return normalizePathDefinitionName(directory, file).replace(/\.sandbox$/, "");
1927
- }
1928
- function isNestedDirectory(parent, candidate) {
1929
- const path = relative(parent, candidate).replace(/\\/g, "/");
1930
- return path !== "" && path !== ".." && !path.startsWith("../");
1931
- }
1932
- function discoverServerSandboxDefinitions(scanDirs) {
1933
- const definitions = /* @__PURE__ */ new Map();
1934
- const createDefinition = createDiscoveredSandboxDefinition("server-sandboxes", "package-entry");
1935
- for (const scanDir of scanDirs) {
1936
- const directory = resolve(scanDir, "sandboxes");
1937
- const packageRoots = listMatchingFiles(directory, (name) => name === "package.json").map((manifest) => dirname(manifest)).sort((left, right) => {
1938
- return relative(directory, left).split(/[\\/]/).length - relative(directory, right).split(/[\\/]/).length || left.localeCompare(right);
1939
- });
1940
- const entrypoints = new Map(packageRoots.map((packageRoot) => [packageRoot, sandboxEntrypointFilenames.map((filename) => resolve(packageRoot, filename)).filter((file) => existsSync(file))]));
1941
- const selectedRoots = [];
1942
- for (const packageRoot of packageRoots) {
1943
- if (selectedRoots.some((root) => isNestedDirectory(root, packageRoot))) continue;
1944
- const packageEntrypoints = entrypoints.get(packageRoot);
1945
- if (packageEntrypoints.length > 1) throw new Error(`[vitehub] Sandbox package "${packageRoot}" has multiple entrypoints: ${packageEntrypoints.join(", ")}.`);
1946
- if (packageEntrypoints.length === 0) continue;
1947
- const file = packageEntrypoints[0];
1948
- registerDefinition(definitions, createDefinition({
1949
- file,
1950
- name: normalizeDirectorySandboxName(directory, file)
1951
- }), "sandbox");
1952
- selectedRoots.push(packageRoot);
1953
- }
1954
- for (const packageRoot of packageRoots) {
1955
- if (entrypoints.get(packageRoot).length > 0) continue;
1956
- if (selectedRoots.some((root) => isNestedDirectory(packageRoot, root) || isNestedDirectory(root, packageRoot))) continue;
1957
- throw new Error(`[vitehub] Sandbox package "${packageRoot}" requires one ESM entrypoint: ${sandboxEntrypointFilenames.join(", ")}.`);
1958
- }
1959
- }
1960
- return sortDefinitions(definitions);
1961
- }
1962
- function discoverSandboxDefinitions(options) {
1963
- if (options.mode === "server-sandboxes") return discoverServerSandboxDefinitions(options.scanDirs);
1964
- const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
1965
- const serverScanDirs = roots.map((root) => resolve(root, "server"));
1966
- return mergeDefinitions("sandbox", discoverDefinitions("sandbox", [createSuffixDefinitionSource("vite-suffix", roots, sandboxSuffixPattern, normalizeSuffixSandboxName, { createDefinition: createDiscoveredSandboxDefinition("vite-suffix", "definition") })]), discoverServerSandboxDefinitions(serverScanDirs));
1967
- }
1968
- //#endregion
1969
- //#region src/internal/runtime-preparation.ts
1970
- const SANDBOX_PACKAGE_ID$1 = "@vite-hub/sandbox";
1971
- const SANDBOX_REGISTRY_ID = "#vitehub-sandbox-registry";
1972
- const builtinModuleSet = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
1973
- function normalizeSandboxOptions(options) {
1974
- if (options === false) return false;
1975
- if (!isPlainObject(options)) throw new TypeError("[vitehub] `sandbox` must be a plain object.");
1976
- return { ...options };
1977
- }
1978
- function createSandboxRuntimeConfig(config, hosting) {
1979
- const provider = getSandboxFeatureProvider(config);
1980
- const sandbox = provider?.provider === "vercel" ? {
1981
- ...config,
1982
- token: provider.token ?? "",
1983
- teamId: provider.teamId ?? "",
1984
- projectId: provider.projectId ?? ""
1985
- } : config;
1986
- return {
1987
- ...hosting ? { hosting } : {},
1988
- sandbox
1989
- };
1990
- }
1991
- async function readSandboxWorkspaceDeps(rootDir) {
1992
- const packageJson = JSON.parse(await readFile(resolve(rootDir, "package.json"), "utf8"));
1993
- return {
1994
- ...packageJson.dependencies,
1995
- ...packageJson.devDependencies
1996
- };
1997
- }
1998
- async function resolveSandboxViteContext(integrationOptions, userConfig, env, hasDefinitions) {
1999
- const configOptions = userConfig.sandbox;
2000
- const options = normalizeSandboxOptions(typeof configOptions === "undefined" ? integrationOptions ?? {} : configOptions);
2001
- const nitro = isPlainObject(userConfig.nitro) ? userConfig.nitro : {};
2002
- 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;
2003
- const config = options === false ? false : hasDefinitions ? resolveSandboxFeatureConfig(options, hosting) : { ...options };
2004
- const runtimeSandboxConfig = config !== false && (hasDefinitions || getSandboxFeatureProvider(config)?.provider) ? config : false;
2005
- const rootDir = resolve(process.cwd(), typeof userConfig.root === "string" ? userConfig.root : ".");
2006
- return {
2007
- rootDir,
2008
- config,
2009
- deps: hasDefinitions ? await readSandboxWorkspaceDeps(rootDir) : {},
2010
- runtimeConfig: createSandboxRuntimeConfig(runtimeSandboxConfig, hosting),
2011
- hosting,
2012
- command: env.command,
2013
- mode: env.mode
2014
- };
2015
- }
2016
- function createSandboxStateModuleContents(context) {
2017
- const state = {
2018
- config: context.config,
2019
- runtimeConfig: context.runtimeConfig,
2020
- hosting: context.hosting,
2021
- rootDir: context.rootDir,
2022
- mode: context.mode,
2023
- command: context.command
2024
- };
2025
- return [
2026
- `const state = ${JSON.stringify(state, null, 2)}`,
2027
- "export const config = state.config",
2028
- "export const runtimeConfig = state.runtimeConfig",
2029
- "export const hosting = state.hosting",
2030
- "export const rootDir = state.rootDir",
2031
- "export const mode = state.mode",
2032
- "export const command = state.command",
2033
- "export default state",
2034
- ""
2035
- ].join("\n");
2036
- }
2037
- function readAliasEntries(alias) {
2038
- if (Array.isArray(alias)) return alias;
2039
- if (!alias || typeof alias !== "object") return [];
2040
- return Object.entries(alias).filter((entry) => typeof entry[1] === "string").map(([find, replacement]) => ({
2041
- find,
2042
- replacement
2043
- }));
2044
- }
2045
- function resolveStringAliases(alias) {
2046
- const aliases = {};
2047
- for (const entry of readAliasEntries(alias)) {
2048
- if (typeof entry.find !== "string" || typeof entry.replacement !== "string") continue;
2049
- const find = entry.find.replace(/\/$/, "");
2050
- if (builtinModuleSet.has(entry.find) || builtinModuleSet.has(find)) continue;
2051
- if (!find) continue;
2052
- aliases[find] = entry.replacement;
2053
- }
2054
- return aliases;
2055
- }
2056
- function readResolveOptions(config) {
2057
- if (!config || typeof config !== "object" || !("resolve" in config)) return {};
2058
- const resolveOptions = config.resolve;
2059
- return resolveOptions && typeof resolveOptions === "object" ? resolveOptions : {};
2060
- }
2061
- function createSandboxRuntimeFacadeContents(file, runtimeConfig, registryFile) {
2062
- const stateFile = resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID$1, "./runtime/state", "runtime/state.js");
2063
- const packageIndexFile = resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID$1, "./index", "index.js");
2064
- return [
2065
- `import sandboxRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
2066
- `import { setSandboxRuntimeConfig, setSandboxRuntimeRegistry } from ${JSON.stringify(createImportPath(file, stateFile))}`,
2067
- "",
2068
- `setSandboxRuntimeConfig(${JSON.stringify(runtimeConfig, null, 2)})`,
2069
- "setSandboxRuntimeRegistry(sandboxRegistry)",
2070
- "",
2071
- `export * from ${JSON.stringify(createImportPath(file, packageIndexFile))}`,
2072
- ""
2073
- ].join("\n");
2074
- }
2075
- function createGeneratedAliasMap(rootDir, plan) {
2076
- const generatedDir = ensureGeneratedDir(rootDir, "sandbox");
2077
- const artifactPaths = new Map((plan.artifacts || []).map((artifact) => [artifact.key, resolve(generatedDir, artifact.filename)]));
2078
- const aliases = { [SANDBOX_PACKAGE_ID$1]: plan.manifest.aliasPath };
2079
- for (const alias of plan.aliases || []) {
2080
- if (alias.value) {
2081
- aliases[alias.key] = alias.value;
2082
- continue;
2083
- }
2084
- if (alias.artifactKey && artifactPaths.has(alias.artifactKey)) aliases[alias.key] = artifactPaths.get(alias.artifactKey);
2085
- }
2086
- return aliases;
2087
- }
2088
- async function writeSandboxArtifacts(rootDir, plan) {
2089
- const generatedDir = ensureGeneratedDir(rootDir, "sandbox");
2090
- const emitted = /* @__PURE__ */ new Map();
2091
- const typeTemplate = plan.manifest.typeTemplate;
2092
- if (typeTemplate) await writeFileIfChanged(resolve(generatedDir, typeTemplate.filename), typeTemplate.contents);
2093
- for (const artifact of plan.artifacts || []) {
2094
- const dst = resolve(generatedDir, artifact.filename);
2095
- const contents = artifact.contents ?? await artifact.getContents?.(emitted);
2096
- if (typeof contents !== "string") throw new Error(`[vitehub] Sandbox generated artifact "${artifact.key}" did not return contents.`);
2097
- emitted.set(artifact.key, {
2098
- ...artifact,
2099
- contents,
2100
- dst
2101
- });
2102
- await writeFileIfChanged(dst, contents);
2103
- }
2104
- return emitted;
2105
- }
2106
- async function prepareSandboxRuntime(options) {
2107
- const rootDir = options.resolvedConfig?.root || resolve(process.cwd(), typeof options.userConfig.root === "string" ? options.userConfig.root : ".");
2108
- const configOptions = options.userConfig.sandbox;
2109
- const definitions = (typeof configOptions === "undefined" ? options.integrationOptions === false : configOptions === false) ? [] : discoverSandboxDefinitions({ rootDir });
2110
- const resolvedNitro = options.resolvedConfig?.nitro;
2111
- const context = await resolveSandboxViteContext(options.integrationOptions, {
2112
- ...options.userConfig,
2113
- ...isPlainObject(resolvedNitro) ? { nitro: resolvedNitro } : {},
2114
- root: rootDir
2115
- }, options.env, definitions.length > 0);
2116
- const stateModule = createSandboxStateModuleContents(context);
2117
- if (!context.config) return {
2118
- aliases: {},
2119
- definitions: [],
2120
- files: [],
2121
- hosting: context.hosting,
2122
- provider: void 0,
2123
- stateModule
2124
- };
2125
- const facadeFile = resolve(ensureGeneratedDir(rootDir, "sandbox"), "runtime/sandbox.mjs");
2126
- const plan = await createSandboxFeaturePlan(context.config, definitions, { aliasPath: facadeFile }, context.deps, context.hosting, {
2127
- bundleAlias: resolveStringAliases(options.resolvedConfig?.resolve.alias ?? readResolveOptions(options.userConfig).alias),
2128
- rootDir,
2129
- scanRoots: [rootDir],
2130
- serverImports: { presets: [] }
2131
- });
2132
- const aliases = createGeneratedAliasMap(rootDir, plan);
2133
- if (options.writeArtifacts === false) return {
2134
- aliases,
2135
- cloudflare: plan.cloudflare,
2136
- definitions,
2137
- files: [],
2138
- hosting: context.hosting,
2139
- provider: getSandboxFeatureProvider(context.config)?.provider,
2140
- stateModule
2141
- };
2142
- const emitted = await writeSandboxArtifacts(rootDir, plan);
2143
- await writeFileIfChanged(facadeFile, createSandboxRuntimeFacadeContents(facadeFile, context.runtimeConfig.sandbox, aliases[SANDBOX_REGISTRY_ID]));
2144
- return {
2145
- aliases,
2146
- cloudflare: plan.cloudflare,
2147
- definitions,
2148
- files: [facadeFile, ...Array.from(emitted.values(), (artifact) => artifact.dst)],
2149
- hosting: context.hosting,
2150
- provider: getSandboxFeatureProvider(context.config)?.provider,
2151
- stateModule
2152
- };
2153
- }
2154
- //#endregion
2155
- //#region src/vite.ts
2156
- const SANDBOX_PACKAGE_ID = "@vite-hub/sandbox";
2157
- const SANDBOX_PROVIDER_LOADER_ID = "vitehub-sandbox-provider-loader";
2158
- const SANDBOX_STATE_ID = "#vitehub/sandbox";
2159
- const RESOLVED_SANDBOX_STATE_ID = "\0vitehub:sandbox:state";
2160
- function mergeSandboxNitroProviderAliases(nitro, aliases) {
2161
- const providerAliases = Object.fromEntries(sandboxProviderLoaderSpecifiers.flatMap((specifier) => {
2162
- const replacement = aliases[specifier];
2163
- return replacement ? [[specifier, replacement]] : [];
2164
- }));
2165
- if (!Object.keys(providerAliases).length) return;
2166
- nitro.alias = {
2167
- ...nitro.alias && typeof nitro.alias === "object" && !Array.isArray(nitro.alias) ? nitro.alias : {},
2168
- ...providerAliases
2169
- };
2170
- }
2171
- function mergeSandboxNitroNoExternals(nitro, provider) {
2172
- if (provider !== "cloudflare" && provider !== "vercel") return;
2173
- const existing = nitro.noExternals;
2174
- if (existing === true) return;
2175
- const existingEntries = Array.isArray(existing) ? existing : [];
2176
- const additions = [SANDBOX_PACKAGE_ID, sandboxRuntimeDependencyByProvider[provider]];
2177
- nitro.noExternals = [...existingEntries, ...additions.filter((addition) => !existingEntries.includes(addition))];
2178
- }
2179
- function sandboxProviderLoaderFallback() {
2180
- return resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./runtime/provider-loader", "runtime/provider-loader.js");
2181
- }
2182
- function sandboxPackageRuntime() {
2183
- return dirname(resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./index", "index.js"));
2184
- }
2185
- function toSandboxAliasEntries(aliases) {
2186
- return Object.entries(aliases).map(([find, replacement]) => ({
2187
- find: find === SANDBOX_PACKAGE_ID ? /^@vite-hub\/sandbox$/ : find,
2188
- replacement
2189
- }));
2190
- }
2191
- function withoutSandboxPackageAlias(aliases) {
2192
- const { [SANDBOX_PACKAGE_ID]: _sandboxAlias, ...rest } = aliases;
2193
- return rest;
2194
- }
2195
- function isSandboxSourceFile(file) {
2196
- return /\.(?:c|m)?[jt]s$/i.test(file) && !/\.d\.(?:c|m)?[jt]s$/i.test(file);
2197
- }
2198
- function isLocalSourceFile(file, rootDir) {
2199
- if (!rootDir) return false;
2200
- const path = normalize(relative(rootDir, file));
2201
- return path !== "" && !path.startsWith("../") && !path.startsWith("/") && !path.startsWith("node_modules/") && !path.startsWith(".vitehub/");
2202
- }
2203
- function isSandboxProjectManifestUpdate(file, rootDir) {
2204
- if (basename(file) !== "package.json" || !isLocalSourceFile(file, rootDir)) return false;
2205
- const path = normalize(relative(rootDir, file));
2206
- return /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(path);
2207
- }
2208
- function isSandboxProjectFileUpdate(file, rootDir) {
2209
- if (!isLocalSourceFile(file, rootDir)) return false;
2210
- const path = normalize(relative(rootDir, file));
2211
- return /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(path) || /^(?:pnpm-workspace\.yaml|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lock)$/.test(path);
2212
- }
2213
- function isSandboxDefinitionUpdate(file, definitions, generatedFiles, rootDir) {
2214
- const changedFile = normalize(file);
2215
- if (definitions.some((definition) => normalize(definition.handler) === changedFile)) return true;
2216
- if (generatedFiles.some((file) => normalize(file) === changedFile)) return false;
2217
- if (isSandboxProjectManifestUpdate(changedFile, rootDir)) return true;
2218
- if (isSandboxProjectFileUpdate(changedFile, rootDir)) return true;
2219
- if (!isSandboxSourceFile(changedFile)) return false;
2220
- return /\.sandbox\.(?:c|m)?[jt]s$/i.test(changedFile) || /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(changedFile) || isLocalSourceFile(changedFile, rootDir);
2221
- }
2222
- function invalidateGeneratedSandboxModules(files, moduleGraph) {
2223
- for (const file of new Set(files.map((file) => normalize(file)))) {
2224
- const module = moduleGraph.getModuleById(file);
2225
- if (module) moduleGraph.invalidateModule(module);
2226
- }
2227
- }
2228
- function hubSandbox(options) {
2229
- const internalOptions = options;
2230
- const integrationOptions = options && typeof options === "object" ? Object.fromEntries(Object.entries(options).filter(([key]) => key !== "providerImportAliases" && key !== "providerImportSpecifier")) : options;
2231
- const mergeSandboxNoExternal = createNoExternalMerger("@vite-hub/sandbox");
2232
- let generatedAliases = {};
2233
- let generatedFiles = [];
2234
- let definitions = [];
2235
- let sandboxStateModule;
2236
- let rawConfig = {};
2237
- let rawEnv = {
2238
- command: "serve",
2239
- mode: "development"
2240
- };
2241
- let resolvedConfig;
2242
- let selectedProvider;
2243
- let earlyNitroTarget;
2244
- let earlyNitroSnapshot;
2245
- let composedCloudflareEarly = false;
2246
- const sandboxNitroModule = (nitro) => {
2247
- mergeSandboxNitroNoExternals(nitro.options, selectedProvider);
2248
- if (selectedProvider) mergeSandboxNitroProviderAliases(nitro.options, generatedAliases);
2249
- nitro.hooks.hook("build:before", () => {
2250
- mergeSandboxNitroNoExternals(nitro.options, selectedProvider);
2251
- if (selectedProvider) mergeSandboxNitroProviderAliases(nitro.options, generatedAliases);
2252
- });
2253
- };
2254
- function cloneConfigValue(value) {
2255
- if (Array.isArray(value)) return value.map(cloneConfigValue);
2256
- if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cloneConfigValue(entry)]));
2257
- return value;
2258
- }
2259
- async function prepareCurrentSandboxRuntime(writeArtifacts = true) {
2260
- const prepared = await prepareSandboxRuntime({
2261
- integrationOptions,
2262
- userConfig: rawConfig,
2263
- env: rawEnv,
2264
- resolvedConfig,
2265
- writeArtifacts
2266
- });
2267
- sandboxStateModule = prepared.stateModule;
2268
- return prepared;
2269
- }
2270
- async function refreshSandboxRuntime() {
2271
- const prepared = await prepareCurrentSandboxRuntime();
2272
- generatedAliases = prepared.aliases;
2273
- generatedFiles = prepared.files;
2274
- definitions = prepared.definitions;
2275
- if (internalOptions?.providerImportAliases && internalOptions.providerImportSpecifier) {
2276
- const facade = generatedAliases[SANDBOX_PACKAGE_ID];
2277
- if (facade) {
2278
- internalOptions.providerImportAliases[internalOptions.providerImportSpecifier] = facade;
2279
- internalOptions.providerImportAliases[SANDBOX_PACKAGE_ID] = sandboxPackageRuntime();
2280
- } else {
2281
- delete internalOptions.providerImportAliases[internalOptions.providerImportSpecifier];
2282
- delete internalOptions.providerImportAliases[SANDBOX_PACKAGE_ID];
2283
- }
2284
- for (const specifier of sandboxProviderLoaderSpecifiers) {
2285
- const providerLoader = generatedAliases[specifier];
2286
- if (providerLoader) internalOptions.providerImportAliases[specifier] = providerLoader;
2287
- else delete internalOptions.providerImportAliases[specifier];
2288
- }
2289
- }
2290
- return prepared;
2291
- }
2292
- async function composeCloudflareSandbox(config, prepared) {
2293
- if (!prepared.cloudflare || !hasNitroConfigContext(config) || getHostingProvider(prepared.hosting) !== "cloudflare") return false;
2294
- config.nitro = await configureCloudflareSandboxNitro(config.nitro, typeof config.root === "string" ? config.root : process.cwd(), prepared.cloudflare);
2295
- return true;
2296
- }
2297
- return {
2298
- name: "@vite-hub/sandbox/vite",
2299
- enforce: "pre",
2300
- nitro: {
2301
- name: "@vite-hub/sandbox/provider-runtime",
2302
- setup: sandboxNitroModule
2303
- },
2304
- async config(config, env) {
2305
- rawConfig = config;
2306
- rawEnv = env;
2307
- const prepared = await prepareCurrentSandboxRuntime(false);
2308
- generatedAliases = prepared.aliases;
2309
- generatedFiles = prepared.files;
2310
- definitions = prepared.definitions;
2311
- selectedProvider = prepared.provider;
2312
- const nitro = config.nitro;
2313
- if (nitro && typeof nitro === "object") {
2314
- earlyNitroTarget = nitro;
2315
- earlyNitroSnapshot = cloneConfigValue(earlyNitroTarget);
2316
- }
2317
- composedCloudflareEarly = await composeCloudflareSandbox(config, prepared);
2318
- return { resolve: { alias: toSandboxAliasEntries({
2319
- [SANDBOX_PROVIDER_LOADER_ID]: sandboxProviderLoaderFallback(),
2320
- ...withoutSandboxPackageAlias(generatedAliases)
2321
- }) } };
2322
- },
2323
- resolveId(id) {
2324
- if (!sandboxStateModule) return;
2325
- if (id === SANDBOX_STATE_ID) return RESOLVED_SANDBOX_STATE_ID;
2326
- if (id === RESOLVED_SANDBOX_STATE_ID) return id;
2327
- },
2328
- load(id) {
2329
- if (id === SANDBOX_STATE_ID || id === RESOLVED_SANDBOX_STATE_ID) return sandboxStateModule;
2330
- },
2331
- async configResolved(config) {
2332
- resolvedConfig = config;
2333
- const prepared = await refreshSandboxRuntime();
2334
- selectedProvider = prepared.provider;
2335
- if (!await composeCloudflareSandbox(config, prepared) && composedCloudflareEarly && earlyNitroTarget && earlyNitroSnapshot) for (const key of ["cloudflare", "rollupConfig"]) if (key in earlyNitroSnapshot) earlyNitroTarget[key] = earlyNitroSnapshot[key];
2336
- else delete earlyNitroTarget[key];
2337
- },
2338
- async handleHotUpdate(context) {
2339
- if (!isSandboxDefinitionUpdate(context.file, definitions, generatedFiles, resolvedConfig?.root)) return;
2340
- const previousFiles = [...generatedFiles, ...Object.values(generatedAliases)];
2341
- const prepared = await refreshSandboxRuntime();
2342
- selectedProvider = prepared.provider;
2343
- if (resolvedConfig) await composeCloudflareSandbox(resolvedConfig, prepared);
2344
- invalidateGeneratedSandboxModules([
2345
- ...previousFiles,
2346
- ...generatedFiles,
2347
- ...Object.values(generatedAliases)
2348
- ], context.server.moduleGraph);
2349
- },
2350
- configEnvironment(name, config) {
2351
- const result = config.consumer === "server" ? { define: { __VITEHUB_ENVIRONMENT_SANDBOX__: JSON.stringify(name) } } : void 0;
2352
- if (!isServerEnvironment(name, config)) return result;
2353
- return {
2354
- ...result,
2355
- resolve: {
2356
- alias: toSandboxAliasEntries({
2357
- [SANDBOX_PROVIDER_LOADER_ID]: sandboxProviderLoaderFallback(),
2358
- ...generatedAliases
2359
- }),
2360
- noExternal: mergeSandboxNoExternal(config.resolve?.noExternal)
2361
- }
2362
- };
2363
- }
2364
- };
2365
- }
2366
- //#endregion
2367
- export { hubSandbox };