@vite-hub/sandbox 0.0.3 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +97 -24
- package/dist/{cloudflare-env-2NctU8i7.js → cloudflare-env-QQV4uzCT.js} +4 -2
- package/dist/index.d.ts +8 -4
- package/dist/index.js +34 -23
- package/dist/{module-types-DfXe133f.d.ts → module-types-DKYItiOu.d.ts} +2 -0
- package/dist/{provider-loader-hL7uHVWp.d.ts → provider-loader-D0UihePq.d.ts} +1 -1
- package/dist/runtime/provider-loader.d.ts +1 -1
- package/dist/runtime/providers/cloudflare.d.ts +1 -1
- package/dist/runtime/providers/cloudflare.js +1 -1
- package/dist/runtime/providers/vercel.d.ts +11 -2
- package/dist/runtime/state.d.ts +11 -2
- package/dist/runtime/state.js +52 -1
- package/dist/vite.d.ts +26 -2
- package/dist/vite.js +1089 -132
- package/package.json +17 -4
package/dist/vite.js
CHANGED
|
@@ -1,24 +1,20 @@
|
|
|
1
1
|
import { t as getSandboxFeatureProvider } from "./module-types-Dj1MFmHT.js";
|
|
2
2
|
import { builtinModules, createRequire } from "node:module";
|
|
3
3
|
import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from "pathe";
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
5
|
import { existsSync, readdirSync, realpathSync } from "node:fs";
|
|
6
|
+
import { hostname } from "node:os";
|
|
5
7
|
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 { copyFile, glob, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
8
9
|
import { createUnimport } from "unimport";
|
|
10
|
+
import { findDynamicImports, resolvePathSync } from "mlly";
|
|
9
11
|
import { build } from "esbuild";
|
|
10
12
|
import { resolveModule } from "local-pkg";
|
|
11
|
-
import {
|
|
12
|
-
import { createHash } from "node:crypto";
|
|
13
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
13
14
|
import { dirname as dirname$2, join as join$1, normalize as normalize$1 } from "node:path/posix";
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
".cts",
|
|
18
|
-
".js",
|
|
19
|
-
".mjs",
|
|
20
|
-
".cjs"
|
|
21
|
-
].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
|
|
15
|
+
import { parse } from "yaml";
|
|
16
|
+
import { setTimeout } from "node:timers/promises";
|
|
17
|
+
//#region ../internal/src/build/vite.ts
|
|
22
18
|
function createNoExternalMerger(packageName) {
|
|
23
19
|
return (current) => {
|
|
24
20
|
if (current === true) return true;
|
|
@@ -30,6 +26,7 @@ function createNoExternalMerger(packageName) {
|
|
|
30
26
|
function isServerEnvironment(name, config) {
|
|
31
27
|
return name === "ssr" || config.consumer === "server";
|
|
32
28
|
}
|
|
29
|
+
const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
|
|
33
30
|
function includesNitroVitePlugin(value) {
|
|
34
31
|
if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
|
|
35
32
|
if (!value || typeof value !== "object") return false;
|
|
@@ -67,6 +64,23 @@ function getSupportedHostingProvider(hosting, supportedProviders) {
|
|
|
67
64
|
return provider;
|
|
68
65
|
}
|
|
69
66
|
//#endregion
|
|
67
|
+
//#region ../internal/src/object.ts
|
|
68
|
+
function isPlainObject$1(value) {
|
|
69
|
+
if (value === null || Object(value) !== value || Array.isArray(value)) return false;
|
|
70
|
+
try {
|
|
71
|
+
Function.prototype.toString.call(value);
|
|
72
|
+
return false;
|
|
73
|
+
} catch {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function isPlainRecord(value) {
|
|
78
|
+
if (!isPlainObject$1(value)) return false;
|
|
79
|
+
const prototype = Object.getPrototypeOf(value);
|
|
80
|
+
if (prototype === null) return true;
|
|
81
|
+
return Object.getPrototypeOf(prototype) === null && Object.hasOwn(prototype, "constructor") && prototype.constructor?.name === "Object";
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
70
84
|
//#region ../internal/src/build/paths.ts
|
|
71
85
|
function generatedDirSegments(productName) {
|
|
72
86
|
return [".vitehub", productName];
|
|
@@ -119,11 +133,15 @@ function readDirEntries(root) {
|
|
|
119
133
|
throw error;
|
|
120
134
|
}
|
|
121
135
|
}
|
|
136
|
+
function isGitRepositoryDirectory(directory) {
|
|
137
|
+
return existsSync(resolve(directory, ".git"));
|
|
138
|
+
}
|
|
122
139
|
function listMatchingFiles(root, predicate, options = {}) {
|
|
123
140
|
const files = [];
|
|
124
141
|
for (const entry of readDirEntries(root)) {
|
|
125
142
|
const absolute = resolve(root, entry.name);
|
|
126
143
|
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
144
|
+
if (isGitRepositoryDirectory(absolute)) continue;
|
|
127
145
|
if (entry.name.startsWith(".")) continue;
|
|
128
146
|
if (ignoredDirs.has(entry.name)) continue;
|
|
129
147
|
files.push(...listMatchingFiles(absolute, predicate, options));
|
|
@@ -206,6 +224,106 @@ async function writeFileIfChanged(file, contents) {
|
|
|
206
224
|
await writeFile(file, contents, "utf8");
|
|
207
225
|
}
|
|
208
226
|
//#endregion
|
|
227
|
+
//#region src/internal/shared/cloudflare-wrangler.ts
|
|
228
|
+
function compareNumericStrings(left, right) {
|
|
229
|
+
return left.localeCompare(right, void 0, { numeric: true });
|
|
230
|
+
}
|
|
231
|
+
function isSameKVNamespace(left, right) {
|
|
232
|
+
return left.binding === right.binding && left.id === right.id && left.preview_id === right.preview_id && left.experimental_remote === right.experimental_remote;
|
|
233
|
+
}
|
|
234
|
+
function isSameContainer(left, right) {
|
|
235
|
+
return left.class_name === right.class_name && left.image === right.image && left.image_build_context === right.image_build_context && left.instance_type === right.instance_type && left.max_instances === right.max_instances && left.name === right.name;
|
|
236
|
+
}
|
|
237
|
+
function isSameDurableObjectBinding(left, right) {
|
|
238
|
+
return left.name === right.name && left.class_name === right.class_name && left.script_name === right.script_name && left.environment === right.environment;
|
|
239
|
+
}
|
|
240
|
+
function isSameWorkerLoader(left, right) {
|
|
241
|
+
return left.binding === right.binding;
|
|
242
|
+
}
|
|
243
|
+
function isSameAnalyticsEngineDataset(left, right) {
|
|
244
|
+
return left.binding === right.binding && left.dataset === right.dataset;
|
|
245
|
+
}
|
|
246
|
+
function isSameWorkflow(left, right) {
|
|
247
|
+
return left.binding === right.binding && left.name === right.name && left.class_name === right.class_name;
|
|
248
|
+
}
|
|
249
|
+
function dedupeByKey(entries, getKey, equals, conflictLabel) {
|
|
250
|
+
if (!entries?.length) return void 0;
|
|
251
|
+
const unique = /* @__PURE__ */ new Map();
|
|
252
|
+
for (const entry of entries) {
|
|
253
|
+
const key = getKey(entry);
|
|
254
|
+
const existing = unique.get(key);
|
|
255
|
+
if (!existing) {
|
|
256
|
+
unique.set(key, entry);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (!equals(existing, entry)) throw new Error(`[vitehub] Conflicting Cloudflare ${conflictLabel} "${key}".`);
|
|
260
|
+
}
|
|
261
|
+
return [...unique.values()];
|
|
262
|
+
}
|
|
263
|
+
function mergeMigrations(migrations) {
|
|
264
|
+
if (!migrations?.length) return void 0;
|
|
265
|
+
const byTag = /* @__PURE__ */ new Map();
|
|
266
|
+
for (const migration of migrations) {
|
|
267
|
+
const existing = byTag.get(migration.tag);
|
|
268
|
+
if (!existing) {
|
|
269
|
+
byTag.set(migration.tag, migration);
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
const mergeStrings = (left, right) => {
|
|
273
|
+
const values = new Set([...left || [], ...right || []]);
|
|
274
|
+
return values.size ? [...values] : void 0;
|
|
275
|
+
};
|
|
276
|
+
const mergeObjects = (left, right) => {
|
|
277
|
+
const values = /* @__PURE__ */ new Map();
|
|
278
|
+
for (const value of [...left || [], ...right || []]) values.set(JSON.stringify(value), value);
|
|
279
|
+
return values.size ? [...values.values()] : void 0;
|
|
280
|
+
};
|
|
281
|
+
const deletedClasses = mergeStrings(existing.deleted_classes, migration.deleted_classes);
|
|
282
|
+
const newClasses = mergeStrings(existing.new_classes, migration.new_classes);
|
|
283
|
+
const newSqliteClasses = mergeStrings(existing.new_sqlite_classes, migration.new_sqlite_classes);
|
|
284
|
+
const renamedClasses = mergeObjects(existing.renamed_classes, migration.renamed_classes);
|
|
285
|
+
const transferredClasses = mergeObjects(existing.transferred_classes, migration.transferred_classes);
|
|
286
|
+
byTag.set(migration.tag, {
|
|
287
|
+
...existing,
|
|
288
|
+
...deletedClasses ? { deleted_classes: deletedClasses } : {},
|
|
289
|
+
...newClasses ? { new_classes: newClasses } : {},
|
|
290
|
+
...newSqliteClasses ? { new_sqlite_classes: newSqliteClasses } : {},
|
|
291
|
+
...renamedClasses ? { renamed_classes: renamedClasses } : {},
|
|
292
|
+
...transferredClasses ? { transferred_classes: transferredClasses } : {}
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
return [...byTag.values()];
|
|
296
|
+
}
|
|
297
|
+
function validateDurableObjectMigrations(wrangler) {
|
|
298
|
+
const bindings = wrangler.durable_objects?.bindings;
|
|
299
|
+
if (!bindings?.length) return;
|
|
300
|
+
const declaredClasses = /* @__PURE__ */ new Set();
|
|
301
|
+
for (const migration of wrangler.migrations || []) {
|
|
302
|
+
for (const className of [...migration.new_sqlite_classes || [], ...migration.new_classes || []]) declaredClasses.add(className);
|
|
303
|
+
for (const entry of migration.renamed_classes || []) {
|
|
304
|
+
declaredClasses.delete(entry.from);
|
|
305
|
+
declaredClasses.add(entry.to);
|
|
306
|
+
}
|
|
307
|
+
for (const className of migration.deleted_classes || []) declaredClasses.delete(className);
|
|
308
|
+
for (const entry of migration.transferred_classes || []) declaredClasses.add(entry.to);
|
|
309
|
+
}
|
|
310
|
+
const missingClasses = [...new Set(bindings.filter((binding) => !binding.script_name).map((binding) => binding.class_name))].filter((className) => !declaredClasses.has(className)).sort(compareNumericStrings);
|
|
311
|
+
if (missingClasses.length) throw new Error(`[vitehub] Missing Cloudflare durable object migration entries for: ${missingClasses.join(", ")}.`);
|
|
312
|
+
}
|
|
313
|
+
function finalizeCloudflareWranglerConfig(target) {
|
|
314
|
+
const wrangler = target.cloudflare?.wrangler;
|
|
315
|
+
if (!wrangler) return;
|
|
316
|
+
wrangler.kv_namespaces = dedupeByKey(wrangler.kv_namespaces, (namespace) => namespace.binding, isSameKVNamespace, "KV namespace binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
|
|
317
|
+
wrangler.containers = dedupeByKey(wrangler.containers, (container) => container.class_name, isSameContainer, "container")?.sort((left, right) => compareNumericStrings(left.class_name, right.class_name));
|
|
318
|
+
wrangler.worker_loaders = dedupeByKey(wrangler.worker_loaders, (loader) => loader.binding, isSameWorkerLoader, "worker loader binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
|
|
319
|
+
wrangler.analytics_engine_datasets = dedupeByKey(wrangler.analytics_engine_datasets, (dataset) => dataset.binding, isSameAnalyticsEngineDataset, "analytics engine dataset binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
|
|
320
|
+
wrangler.durable_objects ||= {};
|
|
321
|
+
wrangler.durable_objects.bindings = dedupeByKey(wrangler.durable_objects.bindings, (binding) => binding.name, isSameDurableObjectBinding, "durable object binding")?.sort((left, right) => compareNumericStrings(left.name, right.name));
|
|
322
|
+
wrangler.workflows = dedupeByKey(wrangler.workflows, (workflow) => workflow.binding, isSameWorkflow, "workflow binding")?.sort((left, right) => compareNumericStrings(left.binding, right.binding));
|
|
323
|
+
wrangler.migrations = mergeMigrations(wrangler.migrations);
|
|
324
|
+
validateDurableObjectMigrations(wrangler);
|
|
325
|
+
}
|
|
326
|
+
//#endregion
|
|
209
327
|
//#region src/cloudflare.ts
|
|
210
328
|
const defaultCloudflareSandboxBinding = "SANDBOX";
|
|
211
329
|
const defaultCloudflareSandboxClassName = "Sandbox";
|
|
@@ -330,14 +448,18 @@ function installCloudflareSandboxEntrypoint(target, options = {}) {
|
|
|
330
448
|
}
|
|
331
449
|
async function writeCloudflareSandboxDockerfile(serverDir) {
|
|
332
450
|
const dockerfilePath = join(serverDir, "Dockerfile");
|
|
333
|
-
await writeFileIfChanged(dockerfilePath,
|
|
451
|
+
await writeFileIfChanged(dockerfilePath, [
|
|
452
|
+
`FROM docker.io/cloudflare/sandbox:${resolveCloudflareSandboxVersion()}`,
|
|
453
|
+
"RUN npm install --global corepack@0.34.5 && corepack enable pnpm yarn",
|
|
454
|
+
""
|
|
455
|
+
].join("\n"));
|
|
334
456
|
return dockerfilePath;
|
|
335
457
|
}
|
|
336
458
|
function relativeWranglerPath(from, to) {
|
|
337
459
|
const path = relative(from, to).replace(/\\/g, "/");
|
|
338
460
|
return path.startsWith(".") ? path : `./${path}`;
|
|
339
461
|
}
|
|
340
|
-
async function configureCloudflareSandboxNitro(targetValue, rootDir, options = {}) {
|
|
462
|
+
async function configureCloudflareSandboxNitro(targetValue, rootDir, options = {}, finalizeWrangler = true) {
|
|
341
463
|
const target = targetValue || {};
|
|
342
464
|
const serverDir = resolve(rootDir, target.output?.serverDir || ".output/server");
|
|
343
465
|
const resolvedOptions = resolveCloudflareSandboxEntrypointOptions(options);
|
|
@@ -354,11 +476,12 @@ async function configureCloudflareSandboxNitro(targetValue, rootDir, options = {
|
|
|
354
476
|
target.rollupConfig ||= {};
|
|
355
477
|
target.rollupConfig.external = mergeRollupExternal(target.rollupConfig.external, "cloudflare:workers");
|
|
356
478
|
installCloudflareSandboxEntrypoint(target, resolvedOptions);
|
|
479
|
+
if (finalizeWrangler) finalizeCloudflareWranglerConfig(target);
|
|
357
480
|
return target;
|
|
358
481
|
}
|
|
359
482
|
//#endregion
|
|
360
483
|
//#region src/internal/shared/discovered-definition/bundler.ts
|
|
361
|
-
const builtinModuleSet$
|
|
484
|
+
const builtinModuleSet$2 = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
362
485
|
function resolveDefinitionLoader(options) {
|
|
363
486
|
let loader = options.loader;
|
|
364
487
|
if (!loader) {
|
|
@@ -374,6 +497,9 @@ function isJsxDefinitionLoader(options) {
|
|
|
374
497
|
const loader = resolveDefinitionLoader(options);
|
|
375
498
|
return loader === "tsx" || loader === "jsx";
|
|
376
499
|
}
|
|
500
|
+
function usesRuntimeModuleResolution(contents) {
|
|
501
|
+
return findDynamicImports(contents).some((imported) => !imported.expression.startsWith("\"")) || /\bimport\.meta\.resolve\s*\(/.test(contents) || /\bcreateRequire\b/.test(contents);
|
|
502
|
+
}
|
|
377
503
|
async function bundleDiscoveredDefinitionModule(options) {
|
|
378
504
|
const output = (await build({
|
|
379
505
|
alias: options.alias,
|
|
@@ -392,7 +518,7 @@ async function bundleDiscoveredDefinitionModule(options) {
|
|
|
392
518
|
jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
|
|
393
519
|
jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
|
|
394
520
|
packages: options.packages === "external" ? "external" : void 0,
|
|
395
|
-
external: [...builtinModuleSet$
|
|
521
|
+
external: [...builtinModuleSet$2, ...options.external || []],
|
|
396
522
|
plugins: options.plugins
|
|
397
523
|
})).outputFiles?.[0]?.text;
|
|
398
524
|
if (!output) throw new Error(`[vitehub] Failed to bundle discovered definition "${options.filename}".`);
|
|
@@ -417,11 +543,12 @@ async function bundleDiscoveredDefinitionModuleGraph(options) {
|
|
|
417
543
|
format: "esm",
|
|
418
544
|
platform: "node",
|
|
419
545
|
target: "es2022",
|
|
546
|
+
metafile: true,
|
|
420
547
|
logLevel: "silent",
|
|
421
548
|
jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
|
|
422
549
|
jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
|
|
423
550
|
packages: options.packages === "external" ? "external" : void 0,
|
|
424
|
-
external: [...builtinModuleSet$
|
|
551
|
+
external: [...builtinModuleSet$2, ...options.external || []],
|
|
425
552
|
plugins: options.plugins
|
|
426
553
|
});
|
|
427
554
|
const modules = Object.fromEntries((result.outputFiles || []).map((outputFile) => {
|
|
@@ -430,12 +557,31 @@ async function bundleDiscoveredDefinitionModuleGraph(options) {
|
|
|
430
557
|
if (!modules["definition.js"]) throw new Error(`[vitehub] Failed to bundle discovered definition graph "${options.filename}".`);
|
|
431
558
|
return {
|
|
432
559
|
entry: "definition.js",
|
|
560
|
+
externalImports: [...new Set(Object.values(result.metafile.outputs).flatMap((output) => output.imports).filter((imported) => imported.external).map((imported) => imported.path))].sort(),
|
|
561
|
+
hasRuntimeModuleResolution: Object.values(modules).some(usesRuntimeModuleResolution),
|
|
433
562
|
modules
|
|
434
563
|
};
|
|
435
564
|
}
|
|
436
565
|
//#endregion
|
|
437
566
|
//#region src/internal/shared/discovered-definition/ast.ts
|
|
438
567
|
const typescript$1 = createRequire(import.meta.url)("typescript");
|
|
568
|
+
const filesystemModuleSpecifiers = new Set([
|
|
569
|
+
"child_process",
|
|
570
|
+
"fs",
|
|
571
|
+
"fs/promises",
|
|
572
|
+
"node:child_process",
|
|
573
|
+
"node:fs",
|
|
574
|
+
"node:fs/promises",
|
|
575
|
+
"node:sqlite",
|
|
576
|
+
"node:worker_threads",
|
|
577
|
+
"worker_threads"
|
|
578
|
+
]);
|
|
579
|
+
const pathModuleSpecifiers = new Set([
|
|
580
|
+
"node:path",
|
|
581
|
+
"node:path/posix",
|
|
582
|
+
"path",
|
|
583
|
+
"path/posix"
|
|
584
|
+
]);
|
|
439
585
|
function resolveImportLocalName(entry) {
|
|
440
586
|
return entry.as || entry.name;
|
|
441
587
|
}
|
|
@@ -453,16 +599,6 @@ function getScriptKind(id) {
|
|
|
453
599
|
function createSourceFile(id, source) {
|
|
454
600
|
return typescript$1.createSourceFile(id, source, typescript$1.ScriptTarget.Latest, true, getScriptKind(id));
|
|
455
601
|
}
|
|
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
602
|
function collectRuntimeModuleSpecifiers(source, id) {
|
|
467
603
|
const sourceFile = createSourceFile(id, source);
|
|
468
604
|
const specifiers = [];
|
|
@@ -501,6 +637,188 @@ function findRuntimeModuleSpecifiers(source, id) {
|
|
|
501
637
|
function hasNonLiteralDynamicImport(source, id) {
|
|
502
638
|
return collectRuntimeModuleSpecifiers(source, id).hasNonLiteralDynamicImport;
|
|
503
639
|
}
|
|
640
|
+
function findFilesystemPathReferences(source, id) {
|
|
641
|
+
const sourceFile = createSourceFile(id, source);
|
|
642
|
+
const directBindings = /* @__PURE__ */ new Set();
|
|
643
|
+
const directBindingOperations = /* @__PURE__ */ new Map();
|
|
644
|
+
const namespaceBindings = /* @__PURE__ */ new Set();
|
|
645
|
+
const pathFunctionBindings = /* @__PURE__ */ new Set();
|
|
646
|
+
const pathNamespaceBindings = /* @__PURE__ */ new Set();
|
|
647
|
+
const requireBindings = new Set(["require"]);
|
|
648
|
+
const createRequireBindings = /* @__PURE__ */ new Set();
|
|
649
|
+
const variableInitializers = /* @__PURE__ */ new Map();
|
|
650
|
+
const ambiguousVariables = /* @__PURE__ */ new Set();
|
|
651
|
+
const references = [];
|
|
652
|
+
function filesystemRequireSpecifier(expression) {
|
|
653
|
+
if (expression && (typescript$1.isPropertyAccessExpression(expression) || typescript$1.isElementAccessExpression(expression))) return filesystemRequireSpecifier(expression.expression);
|
|
654
|
+
const loader = expression && typescript$1.isCallExpression(expression) ? expression.expression : void 0;
|
|
655
|
+
const isFilesystemLoader = loader && (typescript$1.isIdentifier(loader) && requireBindings.has(loader.text) || typescript$1.isPropertyAccessExpression(loader) && typescript$1.isIdentifier(loader.expression) && loader.expression.text === "process" && loader.name.text === "getBuiltinModule");
|
|
656
|
+
if (!expression || !typescript$1.isCallExpression(expression) || !isFilesystemLoader) return;
|
|
657
|
+
const [specifier] = expression.arguments;
|
|
658
|
+
return specifier && typescript$1.isStringLiteralLike(specifier) && filesystemModuleSpecifiers.has(specifier.text) ? specifier.text : void 0;
|
|
659
|
+
}
|
|
660
|
+
function addCommonJSBinding(name) {
|
|
661
|
+
if (typescript$1.isIdentifier(name)) {
|
|
662
|
+
directBindings.add(name.text);
|
|
663
|
+
namespaceBindings.add(name.text);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
for (const element of name.elements) if (!typescript$1.isOmittedExpression(element)) addCommonJSBinding(element.name);
|
|
667
|
+
}
|
|
668
|
+
for (const statement of sourceFile.statements) {
|
|
669
|
+
if (typescript$1.isImportDeclaration(statement) && typescript$1.isStringLiteralLike(statement.moduleSpecifier) && (statement.moduleSpecifier.text === "node:module" || statement.moduleSpecifier.text === "module") && !statement.importClause?.isTypeOnly) {
|
|
670
|
+
const bindings = statement.importClause?.namedBindings;
|
|
671
|
+
if (bindings && typescript$1.isNamedImports(bindings)) {
|
|
672
|
+
for (const binding of bindings.elements) if (!binding.isTypeOnly && (binding.propertyName?.text ?? binding.name.text) === "createRequire") createRequireBindings.add(binding.name.text);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
if (typescript$1.isImportEqualsDeclaration(statement) && !statement.isTypeOnly && typescript$1.isExternalModuleReference(statement.moduleReference) && statement.moduleReference.expression && typescript$1.isStringLiteralLike(statement.moduleReference.expression) && filesystemModuleSpecifiers.has(statement.moduleReference.expression.text)) {
|
|
676
|
+
namespaceBindings.add(statement.name.text);
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
if (!typescript$1.isImportDeclaration(statement) || !typescript$1.isStringLiteralLike(statement.moduleSpecifier) || !filesystemModuleSpecifiers.has(statement.moduleSpecifier.text) || statement.importClause?.isTypeOnly) continue;
|
|
680
|
+
const clause = statement.importClause;
|
|
681
|
+
if (clause?.name) namespaceBindings.add(clause.name.text);
|
|
682
|
+
const bindings = clause?.namedBindings;
|
|
683
|
+
if (bindings && typescript$1.isNamespaceImport(bindings)) namespaceBindings.add(bindings.name.text);
|
|
684
|
+
else if (bindings && typescript$1.isNamedImports(bindings)) {
|
|
685
|
+
for (const binding of bindings.elements) if (!binding.isTypeOnly) {
|
|
686
|
+
directBindings.add(binding.name.text);
|
|
687
|
+
directBindingOperations.set(binding.name.text, binding.propertyName?.text ?? binding.name.text);
|
|
688
|
+
namespaceBindings.add(binding.name.text);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
for (const statement of sourceFile.statements) {
|
|
693
|
+
if (!typescript$1.isImportDeclaration(statement) || !typescript$1.isStringLiteralLike(statement.moduleSpecifier) || !pathModuleSpecifiers.has(statement.moduleSpecifier.text) || statement.importClause?.isTypeOnly) continue;
|
|
694
|
+
const clause = statement.importClause;
|
|
695
|
+
if (clause?.name) pathNamespaceBindings.add(clause.name.text);
|
|
696
|
+
const bindings = clause?.namedBindings;
|
|
697
|
+
if (bindings && typescript$1.isNamespaceImport(bindings)) pathNamespaceBindings.add(bindings.name.text);
|
|
698
|
+
else if (bindings && typescript$1.isNamedImports(bindings)) for (const binding of bindings.elements) {
|
|
699
|
+
const importedName = binding.propertyName?.text ?? binding.name.text;
|
|
700
|
+
if (!binding.isTypeOnly && (importedName === "join" || importedName === "resolve")) pathFunctionBindings.add(binding.name.text);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
function collectCommonJSBindings(node) {
|
|
704
|
+
if (typescript$1.isVariableDeclaration(node)) {
|
|
705
|
+
if (typescript$1.isIdentifier(node.name) && node.initializer && typescript$1.isCallExpression(node.initializer) && typescript$1.isIdentifier(node.initializer.expression) && createRequireBindings.has(node.initializer.expression.text)) requireBindings.add(node.name.text);
|
|
706
|
+
if (node.initializer && typescript$1.isIdentifier(node.name) && typescript$1.isVariableDeclarationList(node.parent) && node.parent.flags & typescript$1.NodeFlags.Const) {
|
|
707
|
+
if (variableInitializers.has(node.name.text)) {
|
|
708
|
+
variableInitializers.delete(node.name.text);
|
|
709
|
+
ambiguousVariables.add(node.name.text);
|
|
710
|
+
} else if (!ambiguousVariables.has(node.name.text)) variableInitializers.set(node.name.text, node.initializer);
|
|
711
|
+
}
|
|
712
|
+
if (filesystemRequireSpecifier(node.initializer)) addCommonJSBinding(node.name);
|
|
713
|
+
}
|
|
714
|
+
typescript$1.forEachChild(node, collectCommonJSBindings);
|
|
715
|
+
}
|
|
716
|
+
collectCommonJSBindings(sourceFile);
|
|
717
|
+
function filesystemOperation(expression) {
|
|
718
|
+
if (typescript$1.isIdentifier(expression)) return directBindingOperations.get(expression.text) ?? (directBindings.has(expression.text) ? expression.text : void 0);
|
|
719
|
+
const root = propertyAccessRoot(expression);
|
|
720
|
+
if (typescript$1.isIdentifier(root.current) && namespaceBindings.has(root.current.text)) return root.properties.at(-1);
|
|
721
|
+
if (filesystemRequireSpecifier(expression)) return root.properties.at(-1);
|
|
722
|
+
}
|
|
723
|
+
function derivedFilesystemOperation(expression) {
|
|
724
|
+
const value = unwrapExpression(expression);
|
|
725
|
+
const directOperation = filesystemOperation(value);
|
|
726
|
+
if (directOperation) return directOperation;
|
|
727
|
+
if (!typescript$1.isCallExpression(value) || filesystemOperation(value.expression)) return;
|
|
728
|
+
const operations = new Set(value.arguments.map(derivedFilesystemOperation).filter((operation) => Boolean(operation)));
|
|
729
|
+
if (operations.size === 1) return [...operations][0];
|
|
730
|
+
return operations.size ? "wrapped-filesystem-operation" : void 0;
|
|
731
|
+
}
|
|
732
|
+
let foundWrappedBinding = true;
|
|
733
|
+
while (foundWrappedBinding) {
|
|
734
|
+
foundWrappedBinding = false;
|
|
735
|
+
for (const [name, initializer] of variableInitializers) {
|
|
736
|
+
if (directBindings.has(name)) continue;
|
|
737
|
+
const operation = derivedFilesystemOperation(initializer);
|
|
738
|
+
if (!operation) continue;
|
|
739
|
+
directBindings.add(name);
|
|
740
|
+
directBindingOperations.set(name, operation);
|
|
741
|
+
foundWrappedBinding = true;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
function isPathFunction(expression) {
|
|
745
|
+
if (typescript$1.isIdentifier(expression)) return pathFunctionBindings.has(expression.text);
|
|
746
|
+
const root = propertyAccessRoot(expression);
|
|
747
|
+
return typescript$1.isIdentifier(root.current) && pathNamespaceBindings.has(root.current.text) && ["join", "resolve"].includes(root.properties.at(-1) || "");
|
|
748
|
+
}
|
|
749
|
+
function unwrapExpression(expression) {
|
|
750
|
+
if (typescript$1.isAwaitExpression(expression) || typescript$1.isParenthesizedExpression(expression) || typescript$1.isAsExpression(expression) || typescript$1.isTypeAssertionExpression(expression) || typescript$1.isNonNullExpression(expression) || typescript$1.isSatisfiesExpression(expression)) return unwrapExpression(expression.expression);
|
|
751
|
+
return expression;
|
|
752
|
+
}
|
|
753
|
+
function isTrackedFilesystemBindingUse(node) {
|
|
754
|
+
if (typescript$1.isImportSpecifier(node.parent) || typescript$1.isImportClause(node.parent) || typescript$1.isNamespaceImport(node.parent) || typescript$1.isImportEqualsDeclaration(node.parent)) return true;
|
|
755
|
+
let invokedExpression = node;
|
|
756
|
+
while ((typescript$1.isPropertyAccessExpression(invokedExpression.parent) || typescript$1.isElementAccessExpression(invokedExpression.parent)) && invokedExpression.parent.expression === invokedExpression) invokedExpression = invokedExpression.parent;
|
|
757
|
+
if ((typescript$1.isCallExpression(invokedExpression.parent) || typescript$1.isNewExpression(invokedExpression.parent)) && invokedExpression.parent.expression === invokedExpression && filesystemOperation(invokedExpression)) return true;
|
|
758
|
+
let current = node;
|
|
759
|
+
while (current.parent && !typescript$1.isVariableDeclaration(current.parent)) current = current.parent;
|
|
760
|
+
if (!current.parent || !typescript$1.isVariableDeclaration(current.parent) || current.parent.initializer !== current || !typescript$1.isIdentifier(current.parent.name)) return false;
|
|
761
|
+
return directBindings.has(current.parent.name.text) && Boolean(derivedFilesystemOperation(current.parent.initializer));
|
|
762
|
+
}
|
|
763
|
+
function resolveFilesystemPath(argument, seen = /* @__PURE__ */ new Set()) {
|
|
764
|
+
if (!argument) return;
|
|
765
|
+
const expression = unwrapExpression(argument);
|
|
766
|
+
if (typescript$1.isStringLiteralLike(expression)) return {
|
|
767
|
+
path: expression.text,
|
|
768
|
+
relativeTo: "working-directory"
|
|
769
|
+
};
|
|
770
|
+
if (typescript$1.isIdentifier(expression)) {
|
|
771
|
+
if (seen.has(expression.text)) return;
|
|
772
|
+
const initializer = variableInitializers.get(expression.text);
|
|
773
|
+
if (!initializer) return;
|
|
774
|
+
return resolveFilesystemPath(initializer, new Set(seen).add(expression.text));
|
|
775
|
+
}
|
|
776
|
+
if (typescript$1.isNewExpression(expression) && typescript$1.isIdentifier(expression.expression) && expression.expression.text === "URL") {
|
|
777
|
+
const [path, base] = expression.arguments || [];
|
|
778
|
+
if (path && typescript$1.isStringLiteralLike(path) && base && typescript$1.isPropertyAccessExpression(base) && base.name.text === "url" && typescript$1.isMetaProperty(base.expression) && base.expression.keywordToken === typescript$1.SyntaxKind.ImportKeyword) return {
|
|
779
|
+
path: path.text,
|
|
780
|
+
relativeTo: "module"
|
|
781
|
+
};
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
if (!typescript$1.isCallExpression(expression)) return;
|
|
785
|
+
if (filesystemOperation(expression.expression) === "mkdtemp") return "runtime";
|
|
786
|
+
if (!isPathFunction(expression.expression)) return;
|
|
787
|
+
const paths = expression.arguments.map((value) => resolveFilesystemPath(value, seen));
|
|
788
|
+
if (!paths.length) return;
|
|
789
|
+
const resolvedPaths = [];
|
|
790
|
+
for (const path of paths) {
|
|
791
|
+
if (path === "runtime") return "runtime";
|
|
792
|
+
if (!path || path.relativeTo !== "working-directory" || path.path === void 0) return;
|
|
793
|
+
resolvedPaths.push(path);
|
|
794
|
+
}
|
|
795
|
+
return {
|
|
796
|
+
path: join(...resolvedPaths.map((path) => path.path)),
|
|
797
|
+
relativeTo: "working-directory"
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
function visit(node) {
|
|
801
|
+
if (typescript$1.isIdentifier(node) && (directBindings.has(node.text) || namespaceBindings.has(node.text)) && !isTrackedFilesystemBindingUse(node)) references.push({ relativeTo: "working-directory" });
|
|
802
|
+
if (typescript$1.isCallExpression(node) && node.expression.kind === typescript$1.SyntaxKind.ImportKeyword && node.arguments[0] && typescript$1.isStringLiteralLike(node.arguments[0]) && filesystemModuleSpecifiers.has(node.arguments[0].text)) references.push({ relativeTo: "working-directory" });
|
|
803
|
+
if (typescript$1.isCallExpression(node) || typescript$1.isNewExpression(node)) {
|
|
804
|
+
const operation = filesystemOperation(node.expression);
|
|
805
|
+
if (operation) {
|
|
806
|
+
const hasChildProcessArguments = [
|
|
807
|
+
"execFile",
|
|
808
|
+
"execFileSync",
|
|
809
|
+
"fork",
|
|
810
|
+
"spawn",
|
|
811
|
+
"spawnSync"
|
|
812
|
+
].includes(operation) && Boolean(node.arguments && node.arguments.length > 1);
|
|
813
|
+
const reference = operation === "exec" || operation === "execSync" ? void 0 : resolveFilesystemPath(node.arguments?.[0]);
|
|
814
|
+
if (operation !== "mkdtemp" && reference !== "runtime") references.push(hasChildProcessArguments ? { relativeTo: "working-directory" } : reference ?? { relativeTo: "working-directory" });
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
typescript$1.forEachChild(node, visit);
|
|
818
|
+
}
|
|
819
|
+
visit(sourceFile);
|
|
820
|
+
return references;
|
|
821
|
+
}
|
|
504
822
|
function propertyAccessRoot(expression) {
|
|
505
823
|
const properties = [];
|
|
506
824
|
let current = expression;
|
|
@@ -546,9 +864,8 @@ function isExecutableIdentifierReference(node) {
|
|
|
546
864
|
if (typescript$1.isBindingElement(parent) && (parent.name === node || parent.propertyName === node)) return false;
|
|
547
865
|
if (typescript$1.isPropertyAccessExpression(parent) && parent.name === node) return false;
|
|
548
866
|
if (typescript$1.isLabeledStatement(parent) || typescript$1.isBreakStatement(parent) || typescript$1.isContinueStatement(parent)) return false;
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
return parent.propertyName !== node;
|
|
867
|
+
if (!typescript$1.isShorthandPropertyAssignment(parent) && "name" in parent && parent.name === node) return false;
|
|
868
|
+
return !("propertyName" in parent) || parent.propertyName !== node;
|
|
552
869
|
}
|
|
553
870
|
function findExecutableCommonJSModuleSpecifiers(sources) {
|
|
554
871
|
const executableSources = new Map([...sources].map(([path, source]) => [`/${path.replace(/^[/]+/, "")}`, source]));
|
|
@@ -850,6 +1167,11 @@ function toTemplateSafeName(name) {
|
|
|
850
1167
|
return name.replace(/[^a-z0-9/_:-]/gi, "_").replace(/\//g, "__").replace(/:/g, "__");
|
|
851
1168
|
}
|
|
852
1169
|
//#endregion
|
|
1170
|
+
//#region src/internal/shared/file-import-specifier.ts
|
|
1171
|
+
function createFileImportSpecifier(file, platform = process.platform) {
|
|
1172
|
+
return pathToFileURL(file, { windows: platform === "win32" }).href;
|
|
1173
|
+
}
|
|
1174
|
+
//#endregion
|
|
853
1175
|
//#region src/internal/shared/module-resolve.ts
|
|
854
1176
|
function normalizePaths(paths) {
|
|
855
1177
|
if (paths?.length) return paths;
|
|
@@ -912,6 +1234,10 @@ function resolveFeatureRuntimePath(importMetaUrl, packageId, sourceRelativePath,
|
|
|
912
1234
|
}
|
|
913
1235
|
//#endregion
|
|
914
1236
|
//#region src/project.ts
|
|
1237
|
+
const sandboxProjectSourceFiles = /* @__PURE__ */ new WeakMap();
|
|
1238
|
+
function getSandboxProjectSourceFiles(project) {
|
|
1239
|
+
return sandboxProjectSourceFiles.get(project) || [];
|
|
1240
|
+
}
|
|
915
1241
|
const maxTimeout = 2147483647;
|
|
916
1242
|
const lockfiles = [
|
|
917
1243
|
{
|
|
@@ -983,21 +1309,32 @@ function parseManifest(source, path) {
|
|
|
983
1309
|
throw new Error(`[vitehub] Sandbox package manifest is invalid JSON: ${path}`, { cause: error });
|
|
984
1310
|
}
|
|
985
1311
|
}
|
|
986
|
-
function isPlainObject
|
|
1312
|
+
function isPlainObject(value) {
|
|
987
1313
|
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
988
1314
|
}
|
|
989
1315
|
function parseSandboxProjectOptions(manifest, path) {
|
|
990
1316
|
if (typeof manifest.vitehub === "undefined") return void 0;
|
|
991
|
-
if (!isPlainObject
|
|
1317
|
+
if (!isPlainObject(manifest.vitehub)) throw new Error(`[vitehub] Sandbox package manifest "vitehub" must be an object: ${path}`);
|
|
992
1318
|
const sandbox = manifest.vitehub.sandbox;
|
|
993
1319
|
if (typeof sandbox === "undefined") return void 0;
|
|
994
|
-
if (!isPlainObject
|
|
1320
|
+
if (!isPlainObject(sandbox)) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox" must be an object: ${path}`);
|
|
995
1321
|
const unsupported = Object.keys(sandbox).filter((key) => key !== "timeout");
|
|
996
1322
|
if (unsupported.length) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox" has unsupported keys: ${unsupported.join(", ")}.`);
|
|
997
1323
|
const timeout = sandbox.timeout;
|
|
998
|
-
if (
|
|
999
|
-
|
|
1000
|
-
|
|
1324
|
+
if (timeout === void 0) return void 0;
|
|
1325
|
+
const numericTimeout = Number(timeout);
|
|
1326
|
+
if (numericTimeout !== timeout || !Number.isInteger(numericTimeout) || numericTimeout <= 0 || numericTimeout > maxTimeout) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox.timeout" must be a positive integer no greater than ${maxTimeout}.`);
|
|
1327
|
+
return { timeout: numericTimeout };
|
|
1328
|
+
}
|
|
1329
|
+
function pnpmPatchPaths(manifest) {
|
|
1330
|
+
if (!isPlainObject(manifest.pnpm) || !isPlainObject(manifest.pnpm.patchedDependencies)) return [];
|
|
1331
|
+
return Object.values(manifest.pnpm.patchedDependencies).filter((value) => typeof value === "string");
|
|
1332
|
+
}
|
|
1333
|
+
function parsePnpmWorkspacePatchPaths(source) {
|
|
1334
|
+
const workspace = parse(source);
|
|
1335
|
+
const patchedDependencies = isPlainObject(workspace) ? Reflect.get(workspace, "patchedDependencies") : void 0;
|
|
1336
|
+
if (!isPlainObject(patchedDependencies)) return [];
|
|
1337
|
+
return Object.values(patchedDependencies).filter((value) => value === String(value)).map(String);
|
|
1001
1338
|
}
|
|
1002
1339
|
function parsePnpmWorkspacePackages(source) {
|
|
1003
1340
|
const patterns = [];
|
|
@@ -1110,6 +1447,16 @@ async function resolveSandboxProject(definitionFile, scanRoot, options = {}) {
|
|
|
1110
1447
|
await addProjectFile(files, installRoot, workspace.file, root);
|
|
1111
1448
|
await addPnpmWorkspaceDependencies(files, installRoot, root, parsePnpmWorkspacePackages(workspace.source), manifest);
|
|
1112
1449
|
}
|
|
1450
|
+
const installManifestPath = resolve$1(installRoot, "package.json");
|
|
1451
|
+
const installManifest = installRoot === packageRoot ? manifest : await isFile(installManifestPath, root) ? parseManifest(await readFile(installManifestPath, "utf8"), installManifestPath) : void 0;
|
|
1452
|
+
for (const patchPath of pnpmPatchPaths(installManifest || {})) {
|
|
1453
|
+
if (!isInside(installRoot, resolve$1(installRoot, patchPath))) throw new Error(`[vitehub] Sandbox pnpm patch must stay inside its install root: ${patchPath}`);
|
|
1454
|
+
await addProjectFile(files, installRoot, resolve$1(installRoot, patchPath), root);
|
|
1455
|
+
}
|
|
1456
|
+
if (workspace) for (const patchPath of parsePnpmWorkspacePatchPaths(workspace.source)) {
|
|
1457
|
+
if (!isInside(installRoot, resolve$1(installRoot, patchPath))) throw new Error(`[vitehub] Sandbox pnpm patch must stay inside its install root: ${patchPath}`);
|
|
1458
|
+
await addProjectFile(files, installRoot, resolve$1(installRoot, patchPath), root);
|
|
1459
|
+
}
|
|
1113
1460
|
if (lock) await addProjectFile(files, installRoot, lock.path, root);
|
|
1114
1461
|
const packagePath = relative$1(installRoot, packageRoot).replaceAll("\\", "/") || ".";
|
|
1115
1462
|
const identity = JSON.stringify({
|
|
@@ -1117,7 +1464,7 @@ async function resolveSandboxProject(definitionFile, scanRoot, options = {}) {
|
|
|
1117
1464
|
manager,
|
|
1118
1465
|
packagePath
|
|
1119
1466
|
});
|
|
1120
|
-
|
|
1467
|
+
const project = {
|
|
1121
1468
|
digest: createHash("sha256").update(identity).digest("hex"),
|
|
1122
1469
|
files,
|
|
1123
1470
|
install: {
|
|
@@ -1128,6 +1475,8 @@ async function resolveSandboxProject(definitionFile, scanRoot, options = {}) {
|
|
|
1128
1475
|
...sandboxOptions ? { options: sandboxOptions } : {},
|
|
1129
1476
|
packagePath
|
|
1130
1477
|
};
|
|
1478
|
+
sandboxProjectSourceFiles.set(project, Object.keys(files).map((path) => resolve$1(installRoot, path)));
|
|
1479
|
+
return project;
|
|
1131
1480
|
}
|
|
1132
1481
|
async function firstDirectoryWithFile(directories, file, root) {
|
|
1133
1482
|
for (const directory of directories) if (await isFile(resolve$1(directory, file), root)) return directory;
|
|
@@ -1480,10 +1829,42 @@ function prepareExecutablePackageProject(project, entry) {
|
|
|
1480
1829
|
//#endregion
|
|
1481
1830
|
//#region src/bundle.ts
|
|
1482
1831
|
const SHIM_NAMESPACE = "vitehub-sandbox-runtime-shim";
|
|
1832
|
+
const builtinModuleSet$1 = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
1833
|
+
function isRelativeFilesystemPath(path) {
|
|
1834
|
+
return !!path && !/^[/\\]/.test(path) && !/^[A-Za-z]:[/\\]/.test(path) && !/^[A-Za-z][A-Za-z\d+.-]*:/.test(path);
|
|
1835
|
+
}
|
|
1836
|
+
function findDefinitionProjectPath(file, project) {
|
|
1837
|
+
const normalizedFile = normalize(file.replaceAll("\\", "/"));
|
|
1838
|
+
return Object.keys(project.files).filter((path) => normalizedFile.endsWith(`/${normalize(path)}`)).sort((left, right) => right.length - left.length)[0];
|
|
1839
|
+
}
|
|
1840
|
+
function containsProjectPath(projectPaths, path) {
|
|
1841
|
+
if (path.startsWith("../")) return false;
|
|
1842
|
+
if (!path || path === ".") return projectPaths.size > 0;
|
|
1843
|
+
return projectPaths.has(path) || [...projectPaths].some((projectPath) => projectPath.startsWith(`${path}/`));
|
|
1844
|
+
}
|
|
1845
|
+
function hasProjectAssetReference(modules, file, project, source) {
|
|
1846
|
+
const projectPaths = new Set(Object.keys(project.files).map((path) => normalize(path)));
|
|
1847
|
+
const packagePath = project.packagePath === "." ? "" : normalize(project.packagePath);
|
|
1848
|
+
const definitionPath = findDefinitionProjectPath(file, project);
|
|
1849
|
+
return [[file, source], ...Object.entries(modules)].some(([modulePath, contents]) => {
|
|
1850
|
+
return findFilesystemPathReferences(contents, modulePath).some((reference) => {
|
|
1851
|
+
if (reference.path === void 0) return true;
|
|
1852
|
+
if (!isRelativeFilesystemPath(reference.path)) return false;
|
|
1853
|
+
const relativePath = normalize(reference.path.replaceAll("\\", "/"));
|
|
1854
|
+
if (reference.relativeTo === "working-directory") return containsProjectPath(projectPaths, normalize(join(packagePath, relativePath)));
|
|
1855
|
+
if (definitionPath) {
|
|
1856
|
+
if (containsProjectPath(projectPaths, normalize(join(dirname(definitionPath), relativePath)))) return true;
|
|
1857
|
+
}
|
|
1858
|
+
const suffix = relativePath.replace(/^(?:\.\.\/)+/, "").replace(/^\.\//, "");
|
|
1859
|
+
return !!suffix && [...projectPaths].some((path) => path === suffix || path.endsWith(`/${suffix}`) || path.startsWith(`${suffix}/`) || path.includes(`/${suffix}/`));
|
|
1860
|
+
});
|
|
1861
|
+
});
|
|
1862
|
+
}
|
|
1483
1863
|
async function bundleSandboxDefinition(source, file, options = {}) {
|
|
1484
|
-
if (options.
|
|
1485
|
-
|
|
1486
|
-
|
|
1864
|
+
if (options.includeProject === true && !options.project) throw new Error(`[vitehub] Sandbox Definition ${file} declares project: true but no project was resolved.`);
|
|
1865
|
+
const project = options.includeProject === false ? void 0 : options.project;
|
|
1866
|
+
if (options.execution === "module" && project) {
|
|
1867
|
+
const executable = prepareExecutablePackageProject(project, `${project.packagePath === "." ? "" : `${project.packagePath}/`}${basename(file)}`);
|
|
1487
1868
|
return {
|
|
1488
1869
|
entry: executable.entry,
|
|
1489
1870
|
execution: "module",
|
|
@@ -1491,10 +1872,10 @@ async function bundleSandboxDefinition(source, file, options = {}) {
|
|
|
1491
1872
|
project: executable.project
|
|
1492
1873
|
};
|
|
1493
1874
|
}
|
|
1494
|
-
const bundle = await bundleDiscoveredDefinitionModuleGraph({
|
|
1875
|
+
const { externalImports, hasRuntimeModuleResolution, ...bundle } = await bundleDiscoveredDefinitionModuleGraph({
|
|
1495
1876
|
alias: options.alias,
|
|
1496
1877
|
filename: file,
|
|
1497
|
-
packages:
|
|
1878
|
+
packages: project ? "external" : "bundle",
|
|
1498
1879
|
source,
|
|
1499
1880
|
plugins: [{
|
|
1500
1881
|
name: SHIM_NAMESPACE,
|
|
@@ -1540,7 +1921,7 @@ async function bundleSandboxDefinition(source, file, options = {}) {
|
|
|
1540
1921
|
"}",
|
|
1541
1922
|
"",
|
|
1542
1923
|
"export function defineSandbox(input) {",
|
|
1543
|
-
" const { run, ...options } = input",
|
|
1924
|
+
" const { project: _project, run, ...options } = input",
|
|
1544
1925
|
" return { run, options: Object.keys(options).length ? options : undefined }",
|
|
1545
1926
|
"}"
|
|
1546
1927
|
].join("\n"),
|
|
@@ -1549,11 +1930,14 @@ async function bundleSandboxDefinition(source, file, options = {}) {
|
|
|
1549
1930
|
}
|
|
1550
1931
|
}]
|
|
1551
1932
|
});
|
|
1552
|
-
|
|
1933
|
+
const hasUnbundledRuntimeDependency = hasRuntimeModuleResolution || externalImports.some((specifier) => !builtinModuleSet$1.has(specifier));
|
|
1934
|
+
if (options.includeProject === false && hasUnbundledRuntimeDependency) throw new Error(`[vitehub] Sandbox Definition ${file} declares project: false but has a runtime dependency that could not be bundled.`);
|
|
1935
|
+
const requiresProject = options.includeProject === true || options.includeProject !== false && (hasUnbundledRuntimeDependency || !!project && hasProjectAssetReference(bundle.modules, file, project, source));
|
|
1936
|
+
if (!project || !requiresProject) return {
|
|
1553
1937
|
...bundle,
|
|
1554
1938
|
...options.execution ? { execution: options.execution } : {}
|
|
1555
1939
|
};
|
|
1556
|
-
const prefix =
|
|
1940
|
+
const prefix = project.packagePath === "." ? ".vitehub-sandbox" : `${project.packagePath}/.vitehub-sandbox`;
|
|
1557
1941
|
const modules = {
|
|
1558
1942
|
[`${prefix}/package.json`]: JSON.stringify({
|
|
1559
1943
|
private: true,
|
|
@@ -1563,15 +1947,15 @@ async function bundleSandboxDefinition(source, file, options = {}) {
|
|
|
1563
1947
|
};
|
|
1564
1948
|
const digest = createHash("sha256").update(JSON.stringify({
|
|
1565
1949
|
modules,
|
|
1566
|
-
packagePath:
|
|
1567
|
-
project:
|
|
1950
|
+
packagePath: project.packagePath,
|
|
1951
|
+
project: project.digest
|
|
1568
1952
|
})).digest("hex");
|
|
1569
1953
|
return {
|
|
1570
1954
|
entry: `${prefix}/${bundle.entry}`,
|
|
1571
1955
|
...options.execution ? { execution: options.execution } : {},
|
|
1572
1956
|
modules,
|
|
1573
1957
|
project: {
|
|
1574
|
-
...
|
|
1958
|
+
...project,
|
|
1575
1959
|
digest
|
|
1576
1960
|
}
|
|
1577
1961
|
};
|
|
@@ -1608,12 +1992,58 @@ function readStaticValue(node) {
|
|
|
1608
1992
|
}
|
|
1609
1993
|
throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use static JSON-serializable values.`);
|
|
1610
1994
|
}
|
|
1995
|
+
function readSandboxDefinitionFactories(sourceFile) {
|
|
1996
|
+
const ts = getTypeScript();
|
|
1997
|
+
const names = new Set(["defineSandbox"]);
|
|
1998
|
+
const namespaces = /* @__PURE__ */ new Set();
|
|
1999
|
+
for (const statement of sourceFile.statements) {
|
|
2000
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== "@vite-hub/sandbox" || !statement.importClause?.namedBindings) continue;
|
|
2001
|
+
const bindings = statement.importClause.namedBindings;
|
|
2002
|
+
if (ts.isNamespaceImport(bindings)) {
|
|
2003
|
+
namespaces.add(bindings.name.text);
|
|
2004
|
+
continue;
|
|
2005
|
+
}
|
|
2006
|
+
for (const element of bindings.elements) if ((element.propertyName ?? element.name).text === "defineSandbox") names.add(element.name.text);
|
|
2007
|
+
}
|
|
2008
|
+
return {
|
|
2009
|
+
names,
|
|
2010
|
+
namespaces
|
|
2011
|
+
};
|
|
2012
|
+
}
|
|
1611
2013
|
function readDefinitionObject(sourceFile) {
|
|
1612
2014
|
const ts = getTypeScript();
|
|
2015
|
+
const factories = readSandboxDefinitionFactories(sourceFile);
|
|
2016
|
+
const immutableBindings = /* @__PURE__ */ new Map();
|
|
2017
|
+
for (const statement of sourceFile.statements) {
|
|
2018
|
+
if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;
|
|
2019
|
+
for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.initializer) immutableBindings.set(declaration.name.text, declaration.initializer);
|
|
2020
|
+
}
|
|
1613
2021
|
for (const statement of sourceFile.statements) {
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
if (
|
|
2022
|
+
let expression;
|
|
2023
|
+
if (ts.isExportAssignment(statement)) expression = statement.expression;
|
|
2024
|
+
else if (ts.isExportDeclaration(statement) && !statement.moduleSpecifier && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
|
|
2025
|
+
const defaultExport = statement.exportClause.elements.find((element) => element.name.text === "default");
|
|
2026
|
+
const binding = defaultExport && (defaultExport.propertyName ?? defaultExport.name);
|
|
2027
|
+
if (binding) expression = immutableBindings.get(binding.text);
|
|
2028
|
+
}
|
|
2029
|
+
if (!expression) continue;
|
|
2030
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2031
|
+
while (expression) {
|
|
2032
|
+
if (ts.isParenthesizedExpression(expression)) {
|
|
2033
|
+
expression = expression.expression;
|
|
2034
|
+
continue;
|
|
2035
|
+
}
|
|
2036
|
+
if (ts.isIdentifier(expression) && !seen.has(expression.text)) {
|
|
2037
|
+
seen.add(expression.text);
|
|
2038
|
+
expression = immutableBindings.get(expression.text);
|
|
2039
|
+
continue;
|
|
2040
|
+
}
|
|
2041
|
+
break;
|
|
2042
|
+
}
|
|
2043
|
+
if (!expression) continue;
|
|
2044
|
+
if (!ts.isCallExpression(expression)) continue;
|
|
2045
|
+
const factory = expression.expression;
|
|
2046
|
+
if (!(ts.isIdentifier(factory) ? factories.names.has(factory.text) : ts.isPropertyAccessExpression(factory) && ts.isIdentifier(factory.expression) && factories.namespaces.has(factory.expression.text) && factory.name.text === "defineSandbox")) continue;
|
|
1617
2047
|
if (expression.arguments.length !== 1 || !ts.isObjectLiteralExpression(expression.arguments[0])) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires one direct object literal.`);
|
|
1618
2048
|
return expression.arguments[0];
|
|
1619
2049
|
}
|
|
@@ -1623,12 +2053,13 @@ function propertyName(property) {
|
|
|
1623
2053
|
if (!("name" in property) || !property.name) return void 0;
|
|
1624
2054
|
return ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : void 0;
|
|
1625
2055
|
}
|
|
1626
|
-
async function
|
|
2056
|
+
async function extractSandboxDefinitionMetadata(file) {
|
|
1627
2057
|
const source = await readFile(file, "utf8");
|
|
1628
2058
|
const ts = getTypeScript();
|
|
1629
2059
|
const input = readDefinitionObject(ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS));
|
|
1630
2060
|
if (!input) return void 0;
|
|
1631
2061
|
const options = {};
|
|
2062
|
+
let project;
|
|
1632
2063
|
let hasRun = false;
|
|
1633
2064
|
for (const property of input.properties) {
|
|
1634
2065
|
const key = propertyName(property);
|
|
@@ -1642,24 +2073,32 @@ async function extractSandboxDefinitionOptions(file) {
|
|
|
1642
2073
|
continue;
|
|
1643
2074
|
}
|
|
1644
2075
|
if (!ts.isPropertyAssignment(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use static values.`);
|
|
1645
|
-
|
|
2076
|
+
const value = readStaticValue(property.initializer);
|
|
2077
|
+
if (key === "project") {
|
|
2078
|
+
if (value !== true && value !== false) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} project must be a boolean.`);
|
|
2079
|
+
project = value;
|
|
2080
|
+
} else options[key] = value;
|
|
1646
2081
|
}
|
|
1647
2082
|
if (!hasRun) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires a \`run\` handler.`);
|
|
1648
|
-
|
|
2083
|
+
const runtimeOptions = Object.keys(options).length ? options : void 0;
|
|
2084
|
+
return runtimeOptions || project !== void 0 ? {
|
|
2085
|
+
...runtimeOptions ? { options: runtimeOptions } : {},
|
|
2086
|
+
...project !== void 0 ? { project } : {}
|
|
2087
|
+
} : void 0;
|
|
1649
2088
|
}
|
|
1650
2089
|
//#endregion
|
|
1651
2090
|
//#region src/type-template.ts
|
|
1652
2091
|
function createDefinitionContract(definition) {
|
|
1653
2092
|
const module = `typeof import(${JSON.stringify(definition.handler)})`;
|
|
1654
2093
|
if (definition.kind === "definition") return `{ payload: Parameters<${module}['default']['run']>[0], result: Awaited<ReturnType<${module}['default']['run']>> }`;
|
|
1655
|
-
return `SandboxPackageContract<${module}['default']
|
|
2094
|
+
return `SandboxPackageContract<${module}['default']>`;
|
|
1656
2095
|
}
|
|
1657
2096
|
function createSandboxTypeTemplateContents(definitions) {
|
|
1658
2097
|
return [
|
|
1659
2098
|
`declare module '#vitehub-sandbox-registry' {`,
|
|
1660
|
-
` type SandboxPackageContract<TDefault
|
|
2099
|
+
` type SandboxPackageContract<TDefault extends (...args: any[]) => any> = TDefault extends (...args: infer TArgs) => infer TResult`,
|
|
1661
2100
|
` ? { payload: TArgs extends [] ? unknown : TArgs[0], result: Awaited<TResult> }`,
|
|
1662
|
-
` :
|
|
2101
|
+
` : never`,
|
|
1663
2102
|
` export interface SandboxDefinitionModules {`,
|
|
1664
2103
|
...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: ${createDefinitionContract(definition)},`),
|
|
1665
2104
|
` }`,
|
|
@@ -1673,6 +2112,12 @@ function createSandboxTypeTemplateContents(definitions) {
|
|
|
1673
2112
|
}
|
|
1674
2113
|
//#endregion
|
|
1675
2114
|
//#region src/feature.ts
|
|
2115
|
+
const sandboxRuntimeStateSpecifier = "@vite-hub/sandbox/runtime/state";
|
|
2116
|
+
const sandboxRuntimeSpecifier = "@vite-hub/sandbox/_internal/runtime";
|
|
2117
|
+
const sandboxRuntimeProviderSpecifiers = {
|
|
2118
|
+
cloudflare: `${sandboxRuntimeSpecifier}/providers/cloudflare`,
|
|
2119
|
+
vercel: `${sandboxRuntimeSpecifier}/providers/vercel`
|
|
2120
|
+
};
|
|
1676
2121
|
const sandboxRuntimeDependencyByProvider = {
|
|
1677
2122
|
cloudflare: "@cloudflare/sandbox",
|
|
1678
2123
|
vercel: "@vercel/sandbox"
|
|
@@ -1751,29 +2196,37 @@ function normalizeSandboxDefinitionOptions(name, options) {
|
|
|
1751
2196
|
}
|
|
1752
2197
|
async function loadSandboxDefinitionMetadata(definitions, rootDir) {
|
|
1753
2198
|
return await Promise.all(definitions.map(async (definition) => {
|
|
1754
|
-
const
|
|
1755
|
-
const
|
|
2199
|
+
const sourceMetadata = definition.kind === "package-entry" ? void 0 : await extractSandboxDefinitionMetadata(definition.handler);
|
|
2200
|
+
const project = sourceMetadata?.project === false ? void 0 : await resolveSandboxProject(definition.handler, rootDir, { readSandboxOptions: definition.kind === "package-entry" });
|
|
1756
2201
|
return {
|
|
1757
|
-
hasPayloadType: source ? hasExportedType(source, definition.handler, "SandboxPayload") : false,
|
|
1758
2202
|
kind: definition.kind,
|
|
1759
2203
|
name: definition.name,
|
|
1760
|
-
options: definition.kind === "package-entry" ? project
|
|
1761
|
-
project
|
|
2204
|
+
options: definition.kind === "package-entry" ? project?.options : normalizeSandboxDefinitionOptions(definition.name, sourceMetadata?.options),
|
|
2205
|
+
project,
|
|
2206
|
+
projectMode: sourceMetadata?.project
|
|
1762
2207
|
};
|
|
1763
2208
|
}));
|
|
1764
2209
|
}
|
|
1765
|
-
function createSandboxRegistryContents(definitions) {
|
|
2210
|
+
function createSandboxRegistryContents(file, definitions, scope) {
|
|
2211
|
+
const scopeSpecifier = createFileImportSpecifier(scope);
|
|
1766
2212
|
return [
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
2213
|
+
`import { createGeneratedSandboxRuntimeRegistry } from ${JSON.stringify(sandboxRuntimeStateSpecifier)}`,
|
|
2214
|
+
"",
|
|
2215
|
+
`const registry = createGeneratedSandboxRuntimeRegistry(${JSON.stringify(scopeSpecifier)}, {`,
|
|
2216
|
+
...definitions.map((definition) => [
|
|
2217
|
+
` ${JSON.stringify(definition.name)}: {`,
|
|
2218
|
+
` load: async () => import(${JSON.stringify(createImportPath(file, definition.definitionModulePath))}),`,
|
|
2219
|
+
` stablePath: ${JSON.stringify(createFileImportSpecifier(definition.stableDefinitionModulePath))},`,
|
|
2220
|
+
" },"
|
|
2221
|
+
].join("\n")),
|
|
2222
|
+
"})",
|
|
1770
2223
|
"export default registry",
|
|
1771
2224
|
""
|
|
1772
2225
|
].join("\n");
|
|
1773
2226
|
}
|
|
1774
2227
|
function createSandboxProviderLoaderContents(provider) {
|
|
1775
2228
|
const providerExport = sandboxProviderRuntimeExport(provider);
|
|
1776
|
-
const providerLoaderPath =
|
|
2229
|
+
const providerLoaderPath = sandboxRuntimeProviderSpecifiers[provider];
|
|
1777
2230
|
return [
|
|
1778
2231
|
`import { ${providerExport} as resolveSandboxBox } from ${JSON.stringify(providerLoaderPath)}`,
|
|
1779
2232
|
"",
|
|
@@ -1818,10 +2271,8 @@ async function createSandboxFeaturePlan(sandboxConfig, definitions, paths, deps,
|
|
|
1818
2271
|
const definitionMetadata = await loadSandboxDefinitionMetadata(definitions, discoveredDefinitionOptions.rootDir || process.cwd());
|
|
1819
2272
|
const metadataByName = new Map(definitionMetadata.map((definition) => [definition.name, definition]));
|
|
1820
2273
|
const manifest = createSandboxManifest(paths.aliasPath, createSandboxTypeTemplateContents(definitions.map((definition) => {
|
|
1821
|
-
const metadata = metadataByName.get(definition.name);
|
|
1822
2274
|
return {
|
|
1823
2275
|
handler: definition.handler,
|
|
1824
|
-
hasPayloadType: metadata?.hasPayloadType ?? false,
|
|
1825
2276
|
kind: definition.kind,
|
|
1826
2277
|
name: definition.name
|
|
1827
2278
|
};
|
|
@@ -1842,6 +2293,7 @@ async function createSandboxFeaturePlan(sandboxConfig, definitions, paths, deps,
|
|
|
1842
2293
|
const bundle = await bundleSandboxDefinition(source, definition._meta.sourcePath, {
|
|
1843
2294
|
alias: bundleAlias,
|
|
1844
2295
|
execution: metadata?.kind === "package-entry" ? "module" : "definition",
|
|
2296
|
+
includeProject: metadata?.projectMode,
|
|
1845
2297
|
project: metadata?.project
|
|
1846
2298
|
});
|
|
1847
2299
|
return `export default ${JSON.stringify({
|
|
@@ -1859,6 +2311,7 @@ async function createSandboxFeaturePlan(sandboxConfig, definitions, paths, deps,
|
|
|
1859
2311
|
} : void 0;
|
|
1860
2312
|
return {
|
|
1861
2313
|
manifest,
|
|
2314
|
+
watchFiles: [...new Set(definitionMetadata.flatMap((metadata) => metadata.project ? getSandboxProjectSourceFiles(metadata.project) : []))],
|
|
1862
2315
|
aliases: [{
|
|
1863
2316
|
key: "#vitehub-sandbox-registry",
|
|
1864
2317
|
artifactKey: "sandbox-registry"
|
|
@@ -1868,32 +2321,28 @@ async function createSandboxFeaturePlan(sandboxConfig, definitions, paths, deps,
|
|
|
1868
2321
|
{
|
|
1869
2322
|
key: "sandbox-registry",
|
|
1870
2323
|
filename: "runtime/sandbox-registry.mjs",
|
|
1871
|
-
getContents(emitted) {
|
|
1872
|
-
return createSandboxRegistryContents(sandboxDefinitions.map((definition) => {
|
|
2324
|
+
getContents(emitted, location) {
|
|
2325
|
+
return createSandboxRegistryContents(location.dst, sandboxDefinitions.map((definition) => {
|
|
1873
2326
|
const artifact = emitted.get(definition.definitionArtifactKey);
|
|
1874
2327
|
if (!artifact) throw new Error(`[vitehub] Missing generated sandbox definition module for "${definition.name}".`);
|
|
1875
2328
|
return {
|
|
1876
2329
|
name: definition.name,
|
|
1877
|
-
definitionModulePath: artifact.dst
|
|
2330
|
+
definitionModulePath: artifact.dst,
|
|
2331
|
+
stableDefinitionModulePath: artifact.stableDst
|
|
1878
2332
|
};
|
|
1879
|
-
}));
|
|
2333
|
+
}), paths.aliasPath);
|
|
1880
2334
|
}
|
|
1881
2335
|
},
|
|
1882
2336
|
...providerLoaderTarget ? [{
|
|
1883
2337
|
key: "sandbox-provider-loader",
|
|
1884
2338
|
filename: "runtime/sandbox-provider-loader.mjs",
|
|
1885
|
-
|
|
2339
|
+
contents: createSandboxProviderLoaderContents(providerLoaderTarget)
|
|
1886
2340
|
}] : []
|
|
1887
2341
|
],
|
|
1888
2342
|
cloudflare: cloudflareOptions
|
|
1889
2343
|
};
|
|
1890
2344
|
}
|
|
1891
2345
|
//#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
2346
|
//#region src/discovery.ts
|
|
1898
2347
|
const sandboxSuffixPattern = /\.sandbox\.(?:c|m)?[jt]s$/i;
|
|
1899
2348
|
const sandboxEntrypointFilenames = [
|
|
@@ -1966,13 +2415,367 @@ function discoverSandboxDefinitions(options) {
|
|
|
1966
2415
|
return mergeDefinitions("sandbox", discoverDefinitions("sandbox", [createSuffixDefinitionSource("vite-suffix", roots, sandboxSuffixPattern, normalizeSuffixSandboxName, { createDefinition: createDiscoveredSandboxDefinition("vite-suffix", "definition") })]), discoverServerSandboxDefinitions(serverScanDirs));
|
|
1967
2416
|
}
|
|
1968
2417
|
//#endregion
|
|
2418
|
+
//#region src/internal/runtime-generation.ts
|
|
2419
|
+
const generationMarker = "// vitehub-sandbox-generation: ";
|
|
2420
|
+
const generationLockClaimStaleMs = 3e4;
|
|
2421
|
+
const generationLockInitializationStaleMs = 5e3;
|
|
2422
|
+
const generationLockName = ".runtime-generation.lock";
|
|
2423
|
+
const generationLockPublicationStaleMs = 3e5;
|
|
2424
|
+
const generationLockWaitMs = 6e4;
|
|
2425
|
+
const generationLockStaleMs = 3e5;
|
|
2426
|
+
const generationLockHeartbeatMs = 3e4;
|
|
2427
|
+
const releasedSandboxRuntimeGenerationLocks = /* @__PURE__ */ new Set();
|
|
2428
|
+
function readNodeErrorCode$1(error) {
|
|
2429
|
+
return error instanceof Error && "code" in error ? error.code : void 0;
|
|
2430
|
+
}
|
|
2431
|
+
function parseSandboxRuntimeGenerationLockOwner(value) {
|
|
2432
|
+
if (!value) return void 0;
|
|
2433
|
+
try {
|
|
2434
|
+
const parsed = JSON.parse(value);
|
|
2435
|
+
if (Object(parsed) !== parsed || Array.isArray(parsed)) return void 0;
|
|
2436
|
+
const host = Reflect.get(Object(parsed), "host");
|
|
2437
|
+
const pid = Reflect.get(Object(parsed), "pid");
|
|
2438
|
+
const released = Reflect.get(Object(parsed), "released");
|
|
2439
|
+
const token = Reflect.get(Object(parsed), "token");
|
|
2440
|
+
if (String(host) !== host || !Number.isSafeInteger(pid) || Number(pid) <= 0 || !(released === void 0 || released === true || released === false) || String(token) !== token) return void 0;
|
|
2441
|
+
const owner = {
|
|
2442
|
+
host: String(host),
|
|
2443
|
+
pid: Number(pid),
|
|
2444
|
+
token: String(token)
|
|
2445
|
+
};
|
|
2446
|
+
if (released === true) owner.released = true;
|
|
2447
|
+
return owner;
|
|
2448
|
+
} catch {
|
|
2449
|
+
return;
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
function isLocalProcessAlive(pid) {
|
|
2453
|
+
try {
|
|
2454
|
+
process.kill(pid, 0);
|
|
2455
|
+
return true;
|
|
2456
|
+
} catch (error) {
|
|
2457
|
+
return readNodeErrorCode$1(error) !== "ESRCH";
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
async function observeSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath) {
|
|
2461
|
+
const before = await stat(lockDir).catch(() => void 0);
|
|
2462
|
+
if (!before) return void 0;
|
|
2463
|
+
const ownerValue = await readFile(ownerPath, "utf8").catch(() => void 0);
|
|
2464
|
+
const publicationValue = await readFile(publicationPath, "utf8").catch(() => void 0);
|
|
2465
|
+
const lease = await stat(leasePath).catch(() => void 0);
|
|
2466
|
+
const after = await stat(lockDir).catch(() => void 0);
|
|
2467
|
+
if (!after || before.dev !== after.dev || before.ino !== after.ino) return void 0;
|
|
2468
|
+
return {
|
|
2469
|
+
dev: after.dev,
|
|
2470
|
+
ino: after.ino,
|
|
2471
|
+
leaseDev: lease?.dev,
|
|
2472
|
+
leaseIno: lease?.ino,
|
|
2473
|
+
leaseMtimeMs: lease?.mtimeMs ?? after.mtimeMs,
|
|
2474
|
+
ownerValue,
|
|
2475
|
+
publicationValue
|
|
2476
|
+
};
|
|
2477
|
+
}
|
|
2478
|
+
function isSandboxRuntimeGenerationLockStale(observation, staleMs) {
|
|
2479
|
+
const owner = parseSandboxRuntimeGenerationLockOwner(observation.ownerValue);
|
|
2480
|
+
if (owner?.released === true || owner && releasedSandboxRuntimeGenerationLocks.has(owner.token)) return true;
|
|
2481
|
+
if (owner?.host === hostname()) {
|
|
2482
|
+
if (!isLocalProcessAlive(owner.pid)) return true;
|
|
2483
|
+
return Date.now() - observation.leaseMtimeMs > Math.max(staleMs, generationLockPublicationStaleMs);
|
|
2484
|
+
}
|
|
2485
|
+
if (owner && observation.publicationValue === owner.token) return Date.now() - observation.leaseMtimeMs > Math.max(staleMs, generationLockPublicationStaleMs);
|
|
2486
|
+
if (!owner || observation.leaseIno === void 0) return Date.now() - observation.leaseMtimeMs > Math.min(staleMs, generationLockInitializationStaleMs);
|
|
2487
|
+
return Date.now() - observation.leaseMtimeMs > staleMs;
|
|
2488
|
+
}
|
|
2489
|
+
function isSameSandboxRuntimeGenerationLock(left, right) {
|
|
2490
|
+
return !!right && left.dev === right.dev && left.ino === right.ino && left.leaseDev === right.leaseDev && left.leaseIno === right.leaseIno && (left.leaseIno === void 0 || left.leaseMtimeMs === right.leaseMtimeMs) && left.ownerValue === right.ownerValue && left.publicationValue === right.publicationValue;
|
|
2491
|
+
}
|
|
2492
|
+
function isSameSandboxRuntimeGenerationLockDirectory(left, right) {
|
|
2493
|
+
return !!right && left.dev === right.dev && left.ino === right.ino;
|
|
2494
|
+
}
|
|
2495
|
+
async function reclaimSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath, observation, staleMs) {
|
|
2496
|
+
const claimPath = resolve(lockDir, ".reclaim");
|
|
2497
|
+
let claim;
|
|
2498
|
+
while (!claim) try {
|
|
2499
|
+
claim = await open(claimPath, "wx");
|
|
2500
|
+
} catch (error) {
|
|
2501
|
+
const code = readNodeErrorCode$1(error);
|
|
2502
|
+
if (code === "ENOENT") return false;
|
|
2503
|
+
if (code !== "EEXIST") throw error;
|
|
2504
|
+
const claimInfo = await stat(claimPath).catch(() => void 0);
|
|
2505
|
+
if (!claimInfo || Date.now() - claimInfo.mtimeMs <= generationLockClaimStaleMs) return false;
|
|
2506
|
+
await rm(claimPath, { force: true }).catch(() => {});
|
|
2507
|
+
}
|
|
2508
|
+
await claim.close();
|
|
2509
|
+
let reclaimed = false;
|
|
2510
|
+
try {
|
|
2511
|
+
const current = await observeSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2512
|
+
const stillStale = current?.leaseIno === void 0 ? isSandboxRuntimeGenerationLockStale(observation, staleMs) : isSandboxRuntimeGenerationLockStale(current, staleMs);
|
|
2513
|
+
if (!isSameSandboxRuntimeGenerationLock(observation, current) || !current || !stillStale) return false;
|
|
2514
|
+
const staleDir = `${lockDir}.stale-${randomUUID()}`;
|
|
2515
|
+
reclaimed = await rename(lockDir, staleDir).then(() => true, (error) => {
|
|
2516
|
+
if (readNodeErrorCode$1(error) === "ENOENT") return false;
|
|
2517
|
+
throw error;
|
|
2518
|
+
});
|
|
2519
|
+
if (reclaimed) await rm(staleDir, {
|
|
2520
|
+
recursive: true,
|
|
2521
|
+
force: true
|
|
2522
|
+
});
|
|
2523
|
+
if (reclaimed) {
|
|
2524
|
+
const owner = parseSandboxRuntimeGenerationLockOwner(observation.ownerValue);
|
|
2525
|
+
if (owner) releasedSandboxRuntimeGenerationLocks.delete(owner.token);
|
|
2526
|
+
}
|
|
2527
|
+
return reclaimed;
|
|
2528
|
+
} finally {
|
|
2529
|
+
if (!reclaimed) await rm(claimPath, { force: true }).catch(() => {});
|
|
2530
|
+
}
|
|
2531
|
+
}
|
|
2532
|
+
async function retireSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath, observation, markReleased, retireLock) {
|
|
2533
|
+
const claimPath = resolve(lockDir, ".reclaim");
|
|
2534
|
+
let claim;
|
|
2535
|
+
try {
|
|
2536
|
+
claim = await open(claimPath, "wx");
|
|
2537
|
+
} catch (error) {
|
|
2538
|
+
if (readNodeErrorCode$1(error) === "ENOENT" || readNodeErrorCode$1(error) === "EEXIST") return;
|
|
2539
|
+
throw error;
|
|
2540
|
+
}
|
|
2541
|
+
await claim.close();
|
|
2542
|
+
let retired = false;
|
|
2543
|
+
try {
|
|
2544
|
+
if (!isSameSandboxRuntimeGenerationLock(observation, await observeSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath))) return;
|
|
2545
|
+
await markReleased();
|
|
2546
|
+
if (!isSameSandboxRuntimeGenerationLockDirectory(observation, await observeSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath))) return;
|
|
2547
|
+
const retiredDir = `${lockDir}.released-${randomUUID()}`;
|
|
2548
|
+
retired = await retireLock(lockDir, retiredDir).then(() => true, (error) => {
|
|
2549
|
+
if (readNodeErrorCode$1(error) === "ENOENT") return false;
|
|
2550
|
+
throw error;
|
|
2551
|
+
});
|
|
2552
|
+
return retired ? retiredDir : void 0;
|
|
2553
|
+
} finally {
|
|
2554
|
+
if (!retired) await rm(claimPath, { force: true }).catch(() => {});
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
async function withSandboxRuntimeGenerationLock(generatedDir, operation, options = {}) {
|
|
2558
|
+
const lockDir = resolve(generatedDir, generationLockName);
|
|
2559
|
+
const ownerPath = resolve(lockDir, "owner.json");
|
|
2560
|
+
const leasePath = resolve(lockDir, "lease");
|
|
2561
|
+
const publicationPath = resolve(lockDir, "publication");
|
|
2562
|
+
const heartbeatMs = options.heartbeatMs ?? generationLockHeartbeatMs;
|
|
2563
|
+
const pollMs = options.pollMs ?? 25;
|
|
2564
|
+
const removeLock = options.removeLock ?? rm;
|
|
2565
|
+
const retireLock = options.retireLock ?? rename;
|
|
2566
|
+
const staleMs = options.staleMs ?? generationLockStaleMs;
|
|
2567
|
+
const writeReleasedOwner = options.writeReleasedOwner ?? (async (file, value) => {
|
|
2568
|
+
await file.write(value, 0, "utf8");
|
|
2569
|
+
await file.truncate(Buffer.byteLength(value));
|
|
2570
|
+
});
|
|
2571
|
+
const ownerRecord = {
|
|
2572
|
+
host: options.host ?? hostname(),
|
|
2573
|
+
pid: process.pid,
|
|
2574
|
+
token: randomUUID()
|
|
2575
|
+
};
|
|
2576
|
+
const owner = JSON.stringify(ownerRecord);
|
|
2577
|
+
const deadline = Date.now() + (options.waitMs ?? generationLockWaitMs);
|
|
2578
|
+
let ownedLock;
|
|
2579
|
+
let createdLock;
|
|
2580
|
+
let leaseFile;
|
|
2581
|
+
let ownerFile;
|
|
2582
|
+
await mkdir(generatedDir, { recursive: true });
|
|
2583
|
+
while (true) {
|
|
2584
|
+
try {
|
|
2585
|
+
await mkdir(lockDir);
|
|
2586
|
+
} catch (error) {
|
|
2587
|
+
if (readNodeErrorCode$1(error) !== "EEXIST") throw error;
|
|
2588
|
+
const observation = await observeSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2589
|
+
if (observation && isSandboxRuntimeGenerationLockStale(observation, staleMs)) {
|
|
2590
|
+
await reclaimSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath, observation, staleMs);
|
|
2591
|
+
continue;
|
|
2592
|
+
}
|
|
2593
|
+
if (Date.now() >= deadline) throw new Error(`[vitehub] Timed out waiting to prepare the Sandbox runtime in ${generatedDir}.`);
|
|
2594
|
+
await setTimeout(pollMs);
|
|
2595
|
+
continue;
|
|
2596
|
+
}
|
|
2597
|
+
try {
|
|
2598
|
+
const created = await observeSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2599
|
+
if (!created || created.ownerValue !== void 0 || created.leaseIno !== void 0) throw new Error(`[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.`);
|
|
2600
|
+
createdLock = created;
|
|
2601
|
+
await options.beforeInitializeLock?.();
|
|
2602
|
+
ownerFile = await open(ownerPath, "wx");
|
|
2603
|
+
await ownerFile.writeFile(owner);
|
|
2604
|
+
leaseFile = await open(leasePath, "wx");
|
|
2605
|
+
await leaseFile.writeFile(owner);
|
|
2606
|
+
ownedLock = await observeSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2607
|
+
if (!ownedLock) throw new Error(`[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.`);
|
|
2608
|
+
break;
|
|
2609
|
+
} catch (error) {
|
|
2610
|
+
await leaseFile?.close().catch(() => {});
|
|
2611
|
+
leaseFile = void 0;
|
|
2612
|
+
await ownerFile?.close().catch(() => {});
|
|
2613
|
+
ownerFile = void 0;
|
|
2614
|
+
const failed = await observeSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2615
|
+
const failedOwnerBelongsToAttempt = failed?.ownerValue === owner || failed?.ownerValue === void 0 && failed?.leaseIno === void 0;
|
|
2616
|
+
if (createdLock && isSameSandboxRuntimeGenerationLockDirectory(createdLock, failed) && failed && failedOwnerBelongsToAttempt) {
|
|
2617
|
+
const retiredDir = await retireSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath, failed, async () => {}, rename).catch(() => void 0);
|
|
2618
|
+
if (retiredDir) await rm(retiredDir, {
|
|
2619
|
+
recursive: true,
|
|
2620
|
+
force: true
|
|
2621
|
+
}).catch(() => {});
|
|
2622
|
+
}
|
|
2623
|
+
throw error;
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
2626
|
+
let heartbeatError;
|
|
2627
|
+
const assertOwned = async () => {
|
|
2628
|
+
if (heartbeatError) throw new Error(`[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.`, { cause: heartbeatError });
|
|
2629
|
+
const active = await observeSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2630
|
+
if (!ownedLock || !active || active.dev !== ownedLock.dev || active.ino !== ownedLock.ino || active.leaseDev !== ownedLock.leaseDev || active.leaseIno !== ownedLock.leaseIno || active.ownerValue !== owner) throw new Error(`[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.`);
|
|
2631
|
+
};
|
|
2632
|
+
const publish = async (publication) => {
|
|
2633
|
+
await assertOwned();
|
|
2634
|
+
const publicationFile = await open(publicationPath, "wx");
|
|
2635
|
+
try {
|
|
2636
|
+
await publicationFile.writeFile(ownerRecord.token);
|
|
2637
|
+
} finally {
|
|
2638
|
+
await publicationFile.close();
|
|
2639
|
+
}
|
|
2640
|
+
try {
|
|
2641
|
+
await assertOwned();
|
|
2642
|
+
return await publication();
|
|
2643
|
+
} finally {
|
|
2644
|
+
await assertOwned();
|
|
2645
|
+
await rm(publicationPath, { force: true });
|
|
2646
|
+
}
|
|
2647
|
+
};
|
|
2648
|
+
const heartbeatAbort = new AbortController();
|
|
2649
|
+
const heartbeat = (async () => {
|
|
2650
|
+
while (!heartbeatAbort.signal.aborted) {
|
|
2651
|
+
try {
|
|
2652
|
+
await setTimeout(heartbeatMs, void 0, { signal: heartbeatAbort.signal });
|
|
2653
|
+
} catch (error) {
|
|
2654
|
+
if (heartbeatAbort.signal.aborted) return;
|
|
2655
|
+
throw error;
|
|
2656
|
+
}
|
|
2657
|
+
if (heartbeatAbort.signal.aborted) return;
|
|
2658
|
+
const now = /* @__PURE__ */ new Date();
|
|
2659
|
+
await leaseFile.utimes(now, now);
|
|
2660
|
+
await assertOwned();
|
|
2661
|
+
}
|
|
2662
|
+
})().catch((error) => {
|
|
2663
|
+
heartbeatError = error;
|
|
2664
|
+
});
|
|
2665
|
+
let operationFailed = false;
|
|
2666
|
+
let operationError;
|
|
2667
|
+
let operationResult;
|
|
2668
|
+
try {
|
|
2669
|
+
operationResult = { value: await operation({
|
|
2670
|
+
assertOwned,
|
|
2671
|
+
publish
|
|
2672
|
+
}) };
|
|
2673
|
+
} catch (error) {
|
|
2674
|
+
operationFailed = true;
|
|
2675
|
+
operationError = error;
|
|
2676
|
+
}
|
|
2677
|
+
const cleanupErrors = [];
|
|
2678
|
+
heartbeatAbort.abort();
|
|
2679
|
+
await heartbeat.catch((error) => cleanupErrors.push(error));
|
|
2680
|
+
if (heartbeatError) cleanupErrors.push(new Error(`[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.`, { cause: heartbeatError }));
|
|
2681
|
+
const activeOwner = await readFile(ownerPath, "utf8").catch(() => void 0);
|
|
2682
|
+
const active = await observeSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath);
|
|
2683
|
+
if (activeOwner === owner && ownedLock && active?.dev === ownedLock.dev && active.ino === ownedLock.ino && active.leaseDev === ownedLock.leaseDev && active.leaseIno === ownedLock.leaseIno) {
|
|
2684
|
+
releasedSandboxRuntimeGenerationLocks.add(ownerRecord.token);
|
|
2685
|
+
const markReleased = async () => {
|
|
2686
|
+
const releasedOwner = JSON.stringify({
|
|
2687
|
+
...ownerRecord,
|
|
2688
|
+
released: true
|
|
2689
|
+
});
|
|
2690
|
+
await writeReleasedOwner(ownerFile, releasedOwner);
|
|
2691
|
+
const expired = /* @__PURE__ */ new Date(0);
|
|
2692
|
+
await leaseFile.utimes(expired, expired);
|
|
2693
|
+
};
|
|
2694
|
+
let retiredDir;
|
|
2695
|
+
try {
|
|
2696
|
+
retiredDir = await retireSandboxRuntimeGenerationLock(lockDir, ownerPath, leasePath, publicationPath, active, markReleased, retireLock);
|
|
2697
|
+
} catch (releaseError) {
|
|
2698
|
+
try {
|
|
2699
|
+
await markReleased();
|
|
2700
|
+
} catch (recoveryError) {
|
|
2701
|
+
cleanupErrors.push(new AggregateError([releaseError, recoveryError], `[vitehub] Failed to release the Sandbox runtime generation lock in ${generatedDir}.`));
|
|
2702
|
+
}
|
|
2703
|
+
}
|
|
2704
|
+
if (!retiredDir && cleanupErrors.length === 0) await markReleased().catch((error) => cleanupErrors.push(error));
|
|
2705
|
+
await leaseFile?.close().catch((error) => cleanupErrors.push(error));
|
|
2706
|
+
leaseFile = void 0;
|
|
2707
|
+
await ownerFile?.close().catch((error) => cleanupErrors.push(error));
|
|
2708
|
+
ownerFile = void 0;
|
|
2709
|
+
if (retiredDir) {
|
|
2710
|
+
await removeLock(retiredDir, {
|
|
2711
|
+
recursive: true,
|
|
2712
|
+
force: true
|
|
2713
|
+
}).catch(() => {});
|
|
2714
|
+
releasedSandboxRuntimeGenerationLocks.delete(ownerRecord.token);
|
|
2715
|
+
}
|
|
2716
|
+
} else if (!heartbeatError) cleanupErrors.push(/* @__PURE__ */ new Error(`[vitehub] Lost ownership while preparing the Sandbox runtime in ${generatedDir}.`));
|
|
2717
|
+
await leaseFile?.close().catch((error) => cleanupErrors.push(error));
|
|
2718
|
+
await ownerFile?.close().catch((error) => cleanupErrors.push(error));
|
|
2719
|
+
if (operationFailed) {
|
|
2720
|
+
if (cleanupErrors.length > 0) throw new AggregateError([operationError, ...cleanupErrors], `[vitehub] Sandbox runtime preparation and generation lock cleanup failed in ${generatedDir}.`);
|
|
2721
|
+
throw operationError;
|
|
2722
|
+
}
|
|
2723
|
+
if (cleanupErrors.length === 1) throw cleanupErrors[0];
|
|
2724
|
+
if (cleanupErrors.length > 1) throw new AggregateError(cleanupErrors, `[vitehub] Failed to clean up the Sandbox runtime generation lock in ${generatedDir}.`);
|
|
2725
|
+
if (!operationResult) throw new Error(`[vitehub] Sandbox runtime preparation completed without a result in ${generatedDir}.`);
|
|
2726
|
+
return operationResult.value;
|
|
2727
|
+
}
|
|
2728
|
+
function markSandboxRuntimeGeneration(contents, generationDir) {
|
|
2729
|
+
return `${generationMarker}${basename(generationDir)}\n${contents}`;
|
|
2730
|
+
}
|
|
2731
|
+
async function readSandboxRuntimeGeneration(facadeFile, generationsDir) {
|
|
2732
|
+
const name = (await readFile(facadeFile, "utf8").catch(() => void 0))?.split("\n", 1)[0]?.slice(31);
|
|
2733
|
+
return name?.startsWith("runtime-") && basename(name) === name ? resolve(generationsDir, name) : void 0;
|
|
2734
|
+
}
|
|
2735
|
+
async function activateSandboxRuntimeFile(source, target, staged, operations = {
|
|
2736
|
+
copyFile,
|
|
2737
|
+
rename,
|
|
2738
|
+
rm
|
|
2739
|
+
}) {
|
|
2740
|
+
await operations.copyFile(source, staged);
|
|
2741
|
+
try {
|
|
2742
|
+
await operations.rename(staged, target);
|
|
2743
|
+
} finally {
|
|
2744
|
+
await operations.rm(staged, { force: true }).catch(() => {});
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
async function restoreSandboxRuntimeGeneration(previousRuntime, activeRuntime, lease, move = rename) {
|
|
2748
|
+
await lease.assertOwned();
|
|
2749
|
+
if (await lstat(activeRuntime).then(() => true, (error) => {
|
|
2750
|
+
if (readNodeErrorCode$1(error) === "ENOENT") return false;
|
|
2751
|
+
throw error;
|
|
2752
|
+
})) throw new Error(`[vitehub] Sandbox runtime changed during activation; the previous runtime is retained at ${previousRuntime}.`);
|
|
2753
|
+
await lease.assertOwned();
|
|
2754
|
+
await move(previousRuntime, activeRuntime);
|
|
2755
|
+
}
|
|
2756
|
+
function resolveSandboxRuntimeLinkType(platform) {
|
|
2757
|
+
return platform === "win32" ? "junction" : "dir";
|
|
2758
|
+
}
|
|
2759
|
+
function resolveSandboxRuntimeFacadeImportBase(runtimeDir, generationFacadeFile, platform) {
|
|
2760
|
+
return platform === "win32" ? resolve(runtimeDir, "sandbox.mjs") : generationFacadeFile;
|
|
2761
|
+
}
|
|
2762
|
+
async function pruneSandboxRuntimeGeneration(path, remove = rm) {
|
|
2763
|
+
await remove(path, {
|
|
2764
|
+
recursive: true,
|
|
2765
|
+
force: true
|
|
2766
|
+
}).catch(() => {});
|
|
2767
|
+
}
|
|
2768
|
+
//#endregion
|
|
1969
2769
|
//#region src/internal/runtime-preparation.ts
|
|
1970
2770
|
const SANDBOX_PACKAGE_ID$1 = "@vite-hub/sandbox";
|
|
1971
2771
|
const SANDBOX_REGISTRY_ID = "#vitehub-sandbox-registry";
|
|
1972
2772
|
const builtinModuleSet = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
2773
|
+
function readNodeErrorCode(error) {
|
|
2774
|
+
return error instanceof Error && "code" in error ? error.code : void 0;
|
|
2775
|
+
}
|
|
1973
2776
|
function normalizeSandboxOptions(options) {
|
|
1974
2777
|
if (options === false) return false;
|
|
1975
|
-
if (!isPlainObject(options)) throw new TypeError("[vitehub] `sandbox` must be a plain object.");
|
|
2778
|
+
if (!isPlainObject$1(options)) throw new TypeError("[vitehub] `sandbox` must be a plain object.");
|
|
1976
2779
|
return { ...options };
|
|
1977
2780
|
}
|
|
1978
2781
|
function createSandboxRuntimeConfig(config, hosting) {
|
|
@@ -1998,7 +2801,7 @@ async function readSandboxWorkspaceDeps(rootDir) {
|
|
|
1998
2801
|
async function resolveSandboxViteContext(integrationOptions, userConfig, env, hasDefinitions) {
|
|
1999
2802
|
const configOptions = userConfig.sandbox;
|
|
2000
2803
|
const options = normalizeSandboxOptions(typeof configOptions === "undefined" ? integrationOptions ?? {} : configOptions);
|
|
2001
|
-
const nitro = isPlainObject(userConfig.nitro) ? userConfig.nitro : {};
|
|
2804
|
+
const nitro = isPlainObject$1(userConfig.nitro) ? userConfig.nitro : {};
|
|
2002
2805
|
const hosting = detectHosting({ options: { preset: typeof userConfig.preset === "string" ? userConfig.preset : typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET } }) || void 0;
|
|
2003
2806
|
const config = options === false ? false : hasDefinitions ? resolveSandboxFeatureConfig(options, hosting) : { ...options };
|
|
2004
2807
|
const runtimeSandboxConfig = config !== false && (hasDefinitions || getSandboxFeatureProvider(config)?.provider) ? config : false;
|
|
@@ -2058,21 +2861,21 @@ function readResolveOptions(config) {
|
|
|
2058
2861
|
const resolveOptions = config.resolve;
|
|
2059
2862
|
return resolveOptions && typeof resolveOptions === "object" ? resolveOptions : {};
|
|
2060
2863
|
}
|
|
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");
|
|
2864
|
+
function createSandboxRuntimeFacadeContents(file, runtimeConfig, registryFile, providerLoaderFile) {
|
|
2064
2865
|
return [
|
|
2065
2866
|
`import sandboxRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
|
|
2066
|
-
`
|
|
2867
|
+
...providerLoaderFile ? [`export { loadSandboxRuntimeProvider } from ${JSON.stringify(createImportPath(file, providerLoaderFile))}`] : [],
|
|
2868
|
+
`import { setSandboxRuntimeConfig, setSandboxRuntimeRegistry } from ${JSON.stringify(sandboxRuntimeStateSpecifier)}`,
|
|
2067
2869
|
"",
|
|
2068
2870
|
`setSandboxRuntimeConfig(${JSON.stringify(runtimeConfig, null, 2)})`,
|
|
2069
2871
|
"setSandboxRuntimeRegistry(sandboxRegistry)",
|
|
2070
2872
|
"",
|
|
2071
|
-
|
|
2873
|
+
"export default sandboxRegistry",
|
|
2874
|
+
`export * from ${JSON.stringify(sandboxRuntimeSpecifier)}`,
|
|
2072
2875
|
""
|
|
2073
2876
|
].join("\n");
|
|
2074
2877
|
}
|
|
2075
|
-
function createGeneratedAliasMap(rootDir, plan) {
|
|
2878
|
+
function createGeneratedAliasMap(rootDir, plan, platform = process.platform) {
|
|
2076
2879
|
const generatedDir = ensureGeneratedDir(rootDir, "sandbox");
|
|
2077
2880
|
const artifactPaths = new Map((plan.artifacts || []).map((artifact) => [artifact.key, resolve(generatedDir, artifact.filename)]));
|
|
2078
2881
|
const aliases = { [SANDBOX_PACKAGE_ID$1]: plan.manifest.aliasPath };
|
|
@@ -2081,36 +2884,148 @@ function createGeneratedAliasMap(rootDir, plan) {
|
|
|
2081
2884
|
aliases[alias.key] = alias.value;
|
|
2082
2885
|
continue;
|
|
2083
2886
|
}
|
|
2887
|
+
if (platform === "win32" && alias.artifactKey) {
|
|
2888
|
+
aliases[alias.key] = plan.manifest.aliasPath;
|
|
2889
|
+
continue;
|
|
2890
|
+
}
|
|
2084
2891
|
if (alias.artifactKey && artifactPaths.has(alias.artifactKey)) aliases[alias.key] = artifactPaths.get(alias.artifactKey);
|
|
2085
2892
|
}
|
|
2086
2893
|
return aliases;
|
|
2087
2894
|
}
|
|
2088
|
-
async function writeSandboxArtifacts(rootDir, plan) {
|
|
2895
|
+
async function writeSandboxArtifacts(rootDir, plan, createFacadeContents, platform = process.platform) {
|
|
2089
2896
|
const generatedDir = ensureGeneratedDir(rootDir, "sandbox");
|
|
2897
|
+
await mkdir(generatedDir, { recursive: true });
|
|
2898
|
+
return await withSandboxRuntimeGenerationLock(generatedDir, async (lease) => await writeSandboxArtifactsLocked(plan, createFacadeContents, generatedDir, platform, lease));
|
|
2899
|
+
}
|
|
2900
|
+
async function writeSandboxArtifactsLocked(plan, createFacadeContents, generatedDir, platform, lease) {
|
|
2901
|
+
const generationsDir = resolve(generatedDir, ".runtime-generations");
|
|
2902
|
+
await mkdir(generationsDir, { recursive: true });
|
|
2903
|
+
const generationDir = await mkdtemp(resolve(generationsDir, "runtime-"));
|
|
2904
|
+
const runtimeDir = resolve(generatedDir, "runtime");
|
|
2905
|
+
const stagedLink = resolve(generatedDir, `.runtime-link-${generationDir.slice(generationsDir.length + 1)}`);
|
|
2906
|
+
const legacyRuntimeDir = resolve(generationsDir, `.legacy-${generationDir.slice(generationsDir.length + 1)}`);
|
|
2090
2907
|
const emitted = /* @__PURE__ */ new Map();
|
|
2091
2908
|
const typeTemplate = plan.manifest.typeTemplate;
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
contents,
|
|
2100
|
-
|
|
2909
|
+
let activated = false;
|
|
2910
|
+
const previousGeneration = await readlink(runtimeDir).catch(() => void 0);
|
|
2911
|
+
const previousWindowsGeneration = platform === "win32" ? await readSandboxRuntimeGeneration(resolve(runtimeDir, "sandbox.mjs"), generationsDir) : void 0;
|
|
2912
|
+
try {
|
|
2913
|
+
for (const artifact of plan.artifacts || []) {
|
|
2914
|
+
const stableDst = resolve(generatedDir, artifact.filename);
|
|
2915
|
+
const dst = resolve(generationDir, stableDst.slice(runtimeDir.length + 1));
|
|
2916
|
+
const contents = artifact.contents ?? await artifact.getContents?.(emitted, {
|
|
2917
|
+
dst,
|
|
2918
|
+
stableDst
|
|
2919
|
+
});
|
|
2920
|
+
if (typeof contents !== "string") throw new Error(`[vitehub] Sandbox generated artifact "${artifact.key}" did not return contents.`);
|
|
2921
|
+
emitted.set(artifact.key, {
|
|
2922
|
+
...artifact,
|
|
2923
|
+
contents,
|
|
2924
|
+
dst,
|
|
2925
|
+
stableDst
|
|
2926
|
+
});
|
|
2927
|
+
}
|
|
2928
|
+
if (typeTemplate) await writeFileIfChanged(resolve(generationDir, typeTemplate.filename.replace(/^runtime\//, "")), typeTemplate.contents);
|
|
2929
|
+
for (const artifact of emitted.values()) await writeFileIfChanged(artifact.dst, artifact.contents);
|
|
2930
|
+
const generationFacadeFile = resolve(generationDir, "sandbox.mjs");
|
|
2931
|
+
const activeFacadeFile = resolveSandboxRuntimeFacadeImportBase(runtimeDir, generationFacadeFile, platform);
|
|
2932
|
+
const registryArtifact = emitted.get(plan.aliases?.find((alias) => alias.key === SANDBOX_REGISTRY_ID)?.artifactKey || "");
|
|
2933
|
+
if (!registryArtifact) throw new Error("[vitehub] Sandbox runtime plan did not emit a registry artifact.");
|
|
2934
|
+
const providerLoaderArtifact = emitted.get("sandbox-provider-loader");
|
|
2935
|
+
await writeFileIfChanged(generationFacadeFile, markSandboxRuntimeGeneration(createFacadeContents(activeFacadeFile, registryArtifact.dst, providerLoaderArtifact?.dst), generationDir));
|
|
2936
|
+
await lease.assertOwned();
|
|
2937
|
+
if (platform === "win32") await lease.publish(async () => {
|
|
2938
|
+
await lease.assertOwned();
|
|
2939
|
+
await mkdir(runtimeDir, { recursive: true });
|
|
2940
|
+
const stableDefinitions = [...emitted.values()].filter((artifact) => artifact.key.startsWith("sandbox-definition:"));
|
|
2941
|
+
for (const artifact of stableDefinitions) {
|
|
2942
|
+
await lease.assertOwned();
|
|
2943
|
+
await mkdir(dirname(artifact.stableDst), { recursive: true });
|
|
2944
|
+
const stagedDefinition = resolve(generatedDir, `.runtime-definition-${generationDir.slice(generationsDir.length + 1)}-${basename(artifact.stableDst)}`);
|
|
2945
|
+
await activateSandboxRuntimeFile(artifact.dst, artifact.stableDst, stagedDefinition);
|
|
2946
|
+
}
|
|
2947
|
+
if (typeTemplate) {
|
|
2948
|
+
await lease.assertOwned();
|
|
2949
|
+
const relativePath = typeTemplate.filename.replace(/^runtime\//, "");
|
|
2950
|
+
const stagedType = resolve(generatedDir, `.runtime-types-${generationDir.slice(generationsDir.length + 1)}.d.ts`);
|
|
2951
|
+
await activateSandboxRuntimeFile(resolve(generationDir, relativePath), resolve(runtimeDir, relativePath), stagedType);
|
|
2952
|
+
}
|
|
2953
|
+
await lease.assertOwned();
|
|
2954
|
+
const stagedFacade = resolve(generatedDir, `.runtime-facade-${generationDir.slice(generationsDir.length + 1)}.mjs`);
|
|
2955
|
+
await activateSandboxRuntimeFile(generationFacadeFile, resolve(runtimeDir, "sandbox.mjs"), stagedFacade);
|
|
2956
|
+
activated = true;
|
|
2957
|
+
const stableDefinitionDir = resolve(runtimeDir, "sandbox-definitions");
|
|
2958
|
+
const retainedDefinitions = new Set(stableDefinitions.map((artifact) => artifact.stableDst));
|
|
2959
|
+
for (const entry of await readdir(stableDefinitionDir).catch(() => [])) {
|
|
2960
|
+
const path = resolve(stableDefinitionDir, entry);
|
|
2961
|
+
if (!retainedDefinitions.has(path)) {
|
|
2962
|
+
await lease.assertOwned();
|
|
2963
|
+
await pruneSandboxRuntimeGeneration(path);
|
|
2964
|
+
}
|
|
2965
|
+
}
|
|
2966
|
+
});
|
|
2967
|
+
else await lease.publish(async () => {
|
|
2968
|
+
await lease.assertOwned();
|
|
2969
|
+
await symlink(generationDir, stagedLink, resolveSandboxRuntimeLinkType(platform));
|
|
2970
|
+
await lease.assertOwned();
|
|
2971
|
+
try {
|
|
2972
|
+
await rename(stagedLink, runtimeDir);
|
|
2973
|
+
activated = true;
|
|
2974
|
+
} catch (error) {
|
|
2975
|
+
const code = readNodeErrorCode(error);
|
|
2976
|
+
if (code !== "EEXIST" && code !== "EISDIR" && code !== "ENOTEMPTY") throw error;
|
|
2977
|
+
await lease.assertOwned();
|
|
2978
|
+
await rename(runtimeDir, legacyRuntimeDir);
|
|
2979
|
+
try {
|
|
2980
|
+
await lease.assertOwned();
|
|
2981
|
+
await rename(stagedLink, runtimeDir);
|
|
2982
|
+
activated = true;
|
|
2983
|
+
} catch (activationError) {
|
|
2984
|
+
try {
|
|
2985
|
+
await restoreSandboxRuntimeGeneration(legacyRuntimeDir, runtimeDir, lease);
|
|
2986
|
+
} catch (rollbackError) {
|
|
2987
|
+
throw new AggregateError([activationError, rollbackError], `[vitehub] Sandbox runtime activation failed; the previous runtime is retained at ${legacyRuntimeDir}.`);
|
|
2988
|
+
}
|
|
2989
|
+
throw activationError;
|
|
2990
|
+
}
|
|
2991
|
+
await lease.assertOwned();
|
|
2992
|
+
await pruneSandboxRuntimeGeneration(legacyRuntimeDir);
|
|
2993
|
+
}
|
|
2994
|
+
});
|
|
2995
|
+
} finally {
|
|
2996
|
+
await rm(stagedLink, { force: true });
|
|
2997
|
+
if (!activated) await rm(generationDir, {
|
|
2998
|
+
recursive: true,
|
|
2999
|
+
force: true
|
|
2101
3000
|
});
|
|
2102
|
-
await writeFileIfChanged(dst, contents);
|
|
2103
3001
|
}
|
|
3002
|
+
const retained = new Set([
|
|
3003
|
+
generationDir,
|
|
3004
|
+
previousGeneration && resolve(generatedDir, previousGeneration),
|
|
3005
|
+
previousWindowsGeneration
|
|
3006
|
+
].filter(Boolean));
|
|
3007
|
+
await lease.publish(async () => {
|
|
3008
|
+
await lease.assertOwned();
|
|
3009
|
+
for (const entry of await readdir(generationsDir)) {
|
|
3010
|
+
const path = resolve(generationsDir, entry);
|
|
3011
|
+
if (!retained.has(path)) {
|
|
3012
|
+
await lease.assertOwned();
|
|
3013
|
+
await pruneSandboxRuntimeGeneration(path);
|
|
3014
|
+
}
|
|
3015
|
+
}
|
|
3016
|
+
});
|
|
2104
3017
|
return emitted;
|
|
2105
3018
|
}
|
|
2106
3019
|
async function prepareSandboxRuntime(options) {
|
|
2107
|
-
const
|
|
3020
|
+
const resolvedRoot = options.resolvedConfig?.root || resolve(process.cwd(), typeof options.userConfig.root === "string" ? options.userConfig.root : ".");
|
|
3021
|
+
const configuredProjectRoot = options.userConfig[VITEHUB_PROJECT_ROOT];
|
|
3022
|
+
const rootDir = typeof configuredProjectRoot === "string" ? resolve(configuredProjectRoot) : resolvedRoot;
|
|
2108
3023
|
const configOptions = options.userConfig.sandbox;
|
|
2109
3024
|
const definitions = (typeof configOptions === "undefined" ? options.integrationOptions === false : configOptions === false) ? [] : discoverSandboxDefinitions({ rootDir });
|
|
2110
3025
|
const resolvedNitro = options.resolvedConfig?.nitro;
|
|
2111
3026
|
const context = await resolveSandboxViteContext(options.integrationOptions, {
|
|
2112
3027
|
...options.userConfig,
|
|
2113
|
-
...isPlainObject(resolvedNitro) ? { nitro: resolvedNitro } : {},
|
|
3028
|
+
...isPlainObject$1(resolvedNitro) ? { nitro: resolvedNitro } : {},
|
|
2114
3029
|
root: rootDir
|
|
2115
3030
|
}, options.env, definitions.length > 0);
|
|
2116
3031
|
const stateModule = createSandboxStateModuleContents(context);
|
|
@@ -2120,7 +3035,9 @@ async function prepareSandboxRuntime(options) {
|
|
|
2120
3035
|
files: [],
|
|
2121
3036
|
hosting: context.hosting,
|
|
2122
3037
|
provider: void 0,
|
|
2123
|
-
|
|
3038
|
+
rootDir,
|
|
3039
|
+
stateModule,
|
|
3040
|
+
watchFiles: []
|
|
2124
3041
|
};
|
|
2125
3042
|
const facadeFile = resolve(ensureGeneratedDir(rootDir, "sandbox"), "runtime/sandbox.mjs");
|
|
2126
3043
|
const plan = await createSandboxFeaturePlan(context.config, definitions, { aliasPath: facadeFile }, context.deps, context.hosting, {
|
|
@@ -2129,7 +3046,7 @@ async function prepareSandboxRuntime(options) {
|
|
|
2129
3046
|
scanRoots: [rootDir],
|
|
2130
3047
|
serverImports: { presets: [] }
|
|
2131
3048
|
});
|
|
2132
|
-
const aliases = createGeneratedAliasMap(rootDir, plan);
|
|
3049
|
+
const aliases = createGeneratedAliasMap(rootDir, plan, options.platform);
|
|
2133
3050
|
if (options.writeArtifacts === false) return {
|
|
2134
3051
|
aliases,
|
|
2135
3052
|
cloudflare: plan.cloudflare,
|
|
@@ -2137,18 +3054,25 @@ async function prepareSandboxRuntime(options) {
|
|
|
2137
3054
|
files: [],
|
|
2138
3055
|
hosting: context.hosting,
|
|
2139
3056
|
provider: getSandboxFeatureProvider(context.config)?.provider,
|
|
2140
|
-
|
|
3057
|
+
rootDir,
|
|
3058
|
+
stateModule,
|
|
3059
|
+
watchFiles: plan.watchFiles || []
|
|
2141
3060
|
};
|
|
2142
|
-
const emitted = await writeSandboxArtifacts(rootDir, plan);
|
|
2143
|
-
await writeFileIfChanged(facadeFile, createSandboxRuntimeFacadeContents(facadeFile, context.runtimeConfig.sandbox, aliases[SANDBOX_REGISTRY_ID]));
|
|
3061
|
+
const emitted = await writeSandboxArtifacts(rootDir, plan, (file, registryFile, providerLoaderFile) => createSandboxRuntimeFacadeContents(file, context.runtimeConfig.sandbox, registryFile, providerLoaderFile), options.platform);
|
|
2144
3062
|
return {
|
|
2145
3063
|
aliases,
|
|
2146
3064
|
cloudflare: plan.cloudflare,
|
|
2147
3065
|
definitions,
|
|
2148
|
-
files: [
|
|
3066
|
+
files: [
|
|
3067
|
+
facadeFile,
|
|
3068
|
+
...Array.from(emitted.values(), (artifact) => artifact.dst),
|
|
3069
|
+
...(plan.artifacts || []).map((artifact) => resolve(ensureGeneratedDir(rootDir, "sandbox"), artifact.filename))
|
|
3070
|
+
],
|
|
2149
3071
|
hosting: context.hosting,
|
|
2150
3072
|
provider: getSandboxFeatureProvider(context.config)?.provider,
|
|
2151
|
-
|
|
3073
|
+
rootDir,
|
|
3074
|
+
stateModule,
|
|
3075
|
+
watchFiles: plan.watchFiles || []
|
|
2152
3076
|
};
|
|
2153
3077
|
}
|
|
2154
3078
|
//#endregion
|
|
@@ -2164,7 +3088,7 @@ function mergeSandboxNitroProviderAliases(nitro, aliases) {
|
|
|
2164
3088
|
}));
|
|
2165
3089
|
if (!Object.keys(providerAliases).length) return;
|
|
2166
3090
|
nitro.alias = {
|
|
2167
|
-
...
|
|
3091
|
+
...isPlainObject$1(nitro.alias) ? nitro.alias : {},
|
|
2168
3092
|
...providerAliases
|
|
2169
3093
|
};
|
|
2170
3094
|
}
|
|
@@ -2179,9 +3103,12 @@ function mergeSandboxNitroNoExternals(nitro, provider) {
|
|
|
2179
3103
|
function sandboxProviderLoaderFallback() {
|
|
2180
3104
|
return resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./runtime/provider-loader", "runtime/provider-loader.js");
|
|
2181
3105
|
}
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
3106
|
+
const sandboxRuntimePackageAliases = {
|
|
3107
|
+
[sandboxRuntimeProviderSpecifiers.cloudflare]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./runtime/providers/cloudflare", "runtime/providers/cloudflare.js"),
|
|
3108
|
+
[sandboxRuntimeProviderSpecifiers.vercel]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./runtime/providers/vercel", "runtime/providers/vercel.js"),
|
|
3109
|
+
[sandboxRuntimeSpecifier]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./index", "index.js"),
|
|
3110
|
+
[sandboxRuntimeStateSpecifier]: resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID, "./runtime/state", "runtime/state.js")
|
|
3111
|
+
};
|
|
2185
3112
|
function toSandboxAliasEntries(aliases) {
|
|
2186
3113
|
return Object.entries(aliases).map(([find, replacement]) => ({
|
|
2187
3114
|
find: find === SANDBOX_PACKAGE_ID ? /^@vite-hub\/sandbox$/ : find,
|
|
@@ -2210,12 +3137,14 @@ function isSandboxProjectFileUpdate(file, rootDir) {
|
|
|
2210
3137
|
const path = normalize(relative(rootDir, file));
|
|
2211
3138
|
return /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(path) || /^(?:pnpm-workspace\.yaml|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lock)$/.test(path);
|
|
2212
3139
|
}
|
|
2213
|
-
function isSandboxDefinitionUpdate(file, definitions, generatedFiles, rootDir) {
|
|
3140
|
+
function isSandboxDefinitionUpdate(file, definitions, generatedFiles, watchFiles, rootDir) {
|
|
2214
3141
|
const changedFile = normalize(file);
|
|
2215
3142
|
if (definitions.some((definition) => normalize(definition.handler) === changedFile)) return true;
|
|
2216
3143
|
if (generatedFiles.some((file) => normalize(file) === changedFile)) return false;
|
|
3144
|
+
if (watchFiles.some((file) => normalize(file) === changedFile)) return true;
|
|
2217
3145
|
if (isSandboxProjectManifestUpdate(changedFile, rootDir)) return true;
|
|
2218
3146
|
if (isSandboxProjectFileUpdate(changedFile, rootDir)) return true;
|
|
3147
|
+
if (isLocalSourceFile(changedFile, rootDir)) return true;
|
|
2219
3148
|
if (!isSandboxSourceFile(changedFile)) return false;
|
|
2220
3149
|
return /\.sandbox\.(?:c|m)?[jt]s$/i.test(changedFile) || /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(changedFile) || isLocalSourceFile(changedFile, rootDir);
|
|
2221
3150
|
}
|
|
@@ -2225,13 +3154,24 @@ function invalidateGeneratedSandboxModules(files, moduleGraph) {
|
|
|
2225
3154
|
if (module) moduleGraph.invalidateModule(module);
|
|
2226
3155
|
}
|
|
2227
3156
|
}
|
|
3157
|
+
async function resolveGeneratedSandboxModuleIds(files) {
|
|
3158
|
+
return Promise.all(files.map(async (file) => normalize(await realpath(file).catch(() => file))));
|
|
3159
|
+
}
|
|
3160
|
+
function publicSandboxOptions(options) {
|
|
3161
|
+
return Object.fromEntries(Object.entries(options).filter(([key]) => key !== "providerImportAliases" && key !== "providerImportSpecifier"));
|
|
3162
|
+
}
|
|
3163
|
+
function mutableSandboxNitroTarget(value) {
|
|
3164
|
+
return value;
|
|
3165
|
+
}
|
|
2228
3166
|
function hubSandbox(options) {
|
|
2229
3167
|
const internalOptions = options;
|
|
2230
|
-
const integrationOptions =
|
|
3168
|
+
const integrationOptions = internalOptions ? publicSandboxOptions(internalOptions) : internalOptions;
|
|
2231
3169
|
const mergeSandboxNoExternal = createNoExternalMerger("@vite-hub/sandbox");
|
|
2232
3170
|
let generatedAliases = {};
|
|
2233
3171
|
let generatedFiles = [];
|
|
3172
|
+
let watchFiles = [];
|
|
2234
3173
|
let definitions = [];
|
|
3174
|
+
let rootDir;
|
|
2235
3175
|
let sandboxStateModule;
|
|
2236
3176
|
let rawConfig = {};
|
|
2237
3177
|
let rawEnv = {
|
|
@@ -2243,6 +3183,7 @@ function hubSandbox(options) {
|
|
|
2243
3183
|
let earlyNitroTarget;
|
|
2244
3184
|
let earlyNitroSnapshot;
|
|
2245
3185
|
let composedCloudflareEarly = false;
|
|
3186
|
+
let sandboxRuntimeRefresh = Promise.resolve();
|
|
2246
3187
|
const sandboxNitroModule = (nitro) => {
|
|
2247
3188
|
mergeSandboxNitroNoExternals(nitro.options, selectedProvider);
|
|
2248
3189
|
if (selectedProvider) mergeSandboxNitroProviderAliases(nitro.options, generatedAliases);
|
|
@@ -2253,7 +3194,7 @@ function hubSandbox(options) {
|
|
|
2253
3194
|
};
|
|
2254
3195
|
function cloneConfigValue(value) {
|
|
2255
3196
|
if (Array.isArray(value)) return value.map(cloneConfigValue);
|
|
2256
|
-
if (value &&
|
|
3197
|
+
if (isPlainRecord(value) && Object.getPrototypeOf(value) === Object.prototype) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cloneConfigValue(entry)]));
|
|
2257
3198
|
return value;
|
|
2258
3199
|
}
|
|
2259
3200
|
async function prepareCurrentSandboxRuntime(writeArtifacts = true) {
|
|
@@ -2267,19 +3208,21 @@ function hubSandbox(options) {
|
|
|
2267
3208
|
sandboxStateModule = prepared.stateModule;
|
|
2268
3209
|
return prepared;
|
|
2269
3210
|
}
|
|
2270
|
-
async function
|
|
3211
|
+
async function activateCurrentSandboxRuntime() {
|
|
2271
3212
|
const prepared = await prepareCurrentSandboxRuntime();
|
|
2272
3213
|
generatedAliases = prepared.aliases;
|
|
2273
3214
|
generatedFiles = prepared.files;
|
|
3215
|
+
watchFiles = prepared.watchFiles;
|
|
2274
3216
|
definitions = prepared.definitions;
|
|
3217
|
+
rootDir = prepared.rootDir;
|
|
2275
3218
|
if (internalOptions?.providerImportAliases && internalOptions.providerImportSpecifier) {
|
|
2276
3219
|
const facade = generatedAliases[SANDBOX_PACKAGE_ID];
|
|
2277
3220
|
if (facade) {
|
|
2278
3221
|
internalOptions.providerImportAliases[internalOptions.providerImportSpecifier] = facade;
|
|
2279
|
-
internalOptions.providerImportAliases
|
|
3222
|
+
Object.assign(internalOptions.providerImportAliases, sandboxRuntimePackageAliases);
|
|
2280
3223
|
} else {
|
|
2281
3224
|
delete internalOptions.providerImportAliases[internalOptions.providerImportSpecifier];
|
|
2282
|
-
delete internalOptions.providerImportAliases[
|
|
3225
|
+
for (const specifier of Object.keys(sandboxRuntimePackageAliases)) delete internalOptions.providerImportAliases[specifier];
|
|
2283
3226
|
}
|
|
2284
3227
|
for (const specifier of sandboxProviderLoaderSpecifiers) {
|
|
2285
3228
|
const providerLoader = generatedAliases[specifier];
|
|
@@ -2289,9 +3232,14 @@ function hubSandbox(options) {
|
|
|
2289
3232
|
}
|
|
2290
3233
|
return prepared;
|
|
2291
3234
|
}
|
|
2292
|
-
async function
|
|
3235
|
+
async function refreshSandboxRuntime(transaction = (refresh) => refresh()) {
|
|
3236
|
+
const refresh = sandboxRuntimeRefresh.then(() => transaction(activateCurrentSandboxRuntime));
|
|
3237
|
+
sandboxRuntimeRefresh = refresh.then(() => void 0, () => void 0);
|
|
3238
|
+
return await refresh;
|
|
3239
|
+
}
|
|
3240
|
+
async function composeCloudflareSandbox(config, prepared, finalizeWrangler = false) {
|
|
2293
3241
|
if (!prepared.cloudflare || !hasNitroConfigContext(config) || getHostingProvider(prepared.hosting) !== "cloudflare") return false;
|
|
2294
|
-
config.nitro = await configureCloudflareSandboxNitro(config.nitro,
|
|
3242
|
+
config.nitro = await configureCloudflareSandboxNitro(mutableSandboxNitroTarget(config.nitro), prepared.rootDir, prepared.cloudflare, finalizeWrangler);
|
|
2295
3243
|
return true;
|
|
2296
3244
|
}
|
|
2297
3245
|
return {
|
|
@@ -2307,10 +3255,12 @@ function hubSandbox(options) {
|
|
|
2307
3255
|
const prepared = await prepareCurrentSandboxRuntime(false);
|
|
2308
3256
|
generatedAliases = prepared.aliases;
|
|
2309
3257
|
generatedFiles = prepared.files;
|
|
3258
|
+
watchFiles = prepared.watchFiles;
|
|
2310
3259
|
definitions = prepared.definitions;
|
|
3260
|
+
rootDir = prepared.rootDir;
|
|
2311
3261
|
selectedProvider = prepared.provider;
|
|
2312
3262
|
const nitro = config.nitro;
|
|
2313
|
-
if (nitro
|
|
3263
|
+
if (isPlainObject$1(nitro)) {
|
|
2314
3264
|
earlyNitroTarget = nitro;
|
|
2315
3265
|
earlyNitroSnapshot = cloneConfigValue(earlyNitroTarget);
|
|
2316
3266
|
}
|
|
@@ -2332,20 +3282,27 @@ function hubSandbox(options) {
|
|
|
2332
3282
|
resolvedConfig = config;
|
|
2333
3283
|
const prepared = await refreshSandboxRuntime();
|
|
2334
3284
|
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];
|
|
3285
|
+
if (!await composeCloudflareSandbox(config, prepared, true) && composedCloudflareEarly && earlyNitroTarget && earlyNitroSnapshot) for (const key of ["cloudflare", "rollupConfig"]) if (key in earlyNitroSnapshot) earlyNitroTarget[key] = earlyNitroSnapshot[key];
|
|
2336
3286
|
else delete earlyNitroTarget[key];
|
|
2337
3287
|
},
|
|
2338
3288
|
async handleHotUpdate(context) {
|
|
2339
|
-
if (!isSandboxDefinitionUpdate(context.file, definitions, generatedFiles,
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
...generatedFiles,
|
|
2347
|
-
|
|
2348
|
-
|
|
3289
|
+
if (!isSandboxDefinitionUpdate(context.file, definitions, generatedFiles, watchFiles, rootDir)) return;
|
|
3290
|
+
await refreshSandboxRuntime(async (refresh) => {
|
|
3291
|
+
const previousFiles = [...generatedFiles, ...Object.values(generatedAliases)];
|
|
3292
|
+
const previousResolvedFiles = await resolveGeneratedSandboxModuleIds(previousFiles);
|
|
3293
|
+
const prepared = await refresh();
|
|
3294
|
+
selectedProvider = prepared.provider;
|
|
3295
|
+
if (resolvedConfig) await composeCloudflareSandbox(resolvedConfig, prepared, true);
|
|
3296
|
+
const currentFiles = [...generatedFiles, ...Object.values(generatedAliases)];
|
|
3297
|
+
const currentResolvedFiles = await resolveGeneratedSandboxModuleIds(currentFiles);
|
|
3298
|
+
invalidateGeneratedSandboxModules([
|
|
3299
|
+
...previousFiles,
|
|
3300
|
+
...previousResolvedFiles,
|
|
3301
|
+
...currentFiles,
|
|
3302
|
+
...currentResolvedFiles
|
|
3303
|
+
], context.server.moduleGraph);
|
|
3304
|
+
return prepared;
|
|
3305
|
+
});
|
|
2349
3306
|
},
|
|
2350
3307
|
configEnvironment(name, config) {
|
|
2351
3308
|
const result = config.consumer === "server" ? { define: { __VITEHUB_ENVIRONMENT_SANDBOX__: JSON.stringify(name) } } : void 0;
|
|
@@ -2364,4 +3321,4 @@ function hubSandbox(options) {
|
|
|
2364
3321
|
};
|
|
2365
3322
|
}
|
|
2366
3323
|
//#endregion
|
|
2367
|
-
export { hubSandbox };
|
|
3324
|
+
export { discoverSandboxDefinitions, hubSandbox };
|