@vite-hub/sandbox 0.0.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +395 -37
- package/dist/abortable-CR01hzfi.js +57 -0
- package/dist/cloudflare-Cog_r2Me.js +910 -0
- package/dist/cloudflare-env-lookup-DzI6Xv1Y.js +16 -0
- package/dist/cloudflare-failure-CFQhalfh.js +50 -0
- package/dist/container-CqfD8yuE.js +868 -0
- package/dist/crabbox-sbV3Zjuo.js +1110 -0
- package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
- package/dist/error-diagnostics-BJtLRL9w.js +536 -0
- package/dist/file-listing-CHtRrfo1.js +26 -0
- package/dist/file-lock-D0-XPogS.js +74 -0
- package/dist/index-DsoQAUb7.d.ts +594 -0
- package/dist/index.d.ts +2 -69
- package/dist/index.js +281 -1182
- package/dist/internal/cloudflare.d.ts +176 -0
- package/dist/internal/cloudflare.js +8 -0
- package/dist/internal/host-toolchain.d.ts +22 -0
- package/dist/internal/host-toolchain.js +96 -0
- package/dist/internal/vercel.d.ts +4 -0
- package/dist/internal/vercel.js +8 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/module-types-B0LQ5H2S.js +7 -0
- package/dist/module-types-DCeJbS9Z.d.ts +110 -0
- package/dist/process-sweep-CMaujWE5.js +33 -0
- package/dist/provider-resolution-C6AQzuFG.js +133 -0
- package/dist/remote-70ZVZZlq.js +265 -0
- package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
- package/dist/runtime-DHp6ImeP.js +32 -0
- package/dist/runtime-type-Deo4qzxN.js +9 -0
- package/dist/session-e0lyzjJ3.js +338 -0
- package/dist/shell-quote-Q3u3plif.js +6 -0
- package/dist/size-7AkVwGZb.js +118 -0
- package/dist/ssh.d.ts +63 -0
- package/dist/ssh.js +286 -0
- package/dist/task/index.d.ts +69 -0
- package/dist/task/index.js +1414 -0
- package/dist/task/runtime/empty-registry.d.ts +6 -0
- package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
- package/dist/task/runtime/provider-loader.d.ts +18 -0
- package/dist/task/runtime/provider-loader.js +16 -0
- package/dist/task/runtime/providers/cloudflare.d.ts +14 -0
- package/dist/task/runtime/providers/cloudflare.js +27 -0
- package/dist/task/runtime/providers/vercel.d.ts +12 -0
- package/dist/task/runtime/providers/vercel.js +85 -0
- package/dist/task/runtime/state.d.ts +27 -0
- package/dist/task/runtime/state.js +82 -0
- package/dist/task/vite.d.ts +486 -0
- package/dist/task/vite.js +3966 -0
- package/dist/toolchain-BIVGMRty.js +528 -0
- package/dist/trusted-host-kxkpaQcs.js +714 -0
- package/dist/vercel-BGGrNpza.js +352 -0
- package/package.json +105 -51
- package/dist/cloudflare-env-QQV4uzCT.js +0 -14
- package/dist/module-types-DKYItiOu.d.ts +0 -93
- package/dist/module-types-Dj1MFmHT.js +0 -7
- package/dist/provider-loader-D0UihePq.d.ts +0 -21
- package/dist/runtime/empty-registry.d.ts +0 -6
- package/dist/runtime/provider-loader.d.ts +0 -2
- package/dist/runtime/provider-loader.js +0 -15
- package/dist/runtime/providers/cloudflare.d.ts +0 -29
- package/dist/runtime/providers/cloudflare.js +0 -25
- package/dist/runtime/providers/vercel.d.ts +0 -121
- package/dist/runtime/providers/vercel.js +0 -51
- package/dist/runtime/state.d.ts +0 -26
- package/dist/runtime/state.js +0 -72
- package/dist/vite.d.ts +0 -48
- package/dist/vite.js +0 -3324
package/dist/vite.js
DELETED
|
@@ -1,3324 +0,0 @@
|
|
|
1
|
-
import { t as getSandboxFeatureProvider } from "./module-types-Dj1MFmHT.js";
|
|
2
|
-
import { builtinModules, createRequire } from "node:module";
|
|
3
|
-
import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from "pathe";
|
|
4
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
|
-
import { existsSync, readdirSync, realpathSync } from "node:fs";
|
|
6
|
-
import { hostname } from "node:os";
|
|
7
|
-
import { dirname as dirname$1, matchesGlob, relative as relative$1, resolve as resolve$1 } from "node:path";
|
|
8
|
-
import { copyFile, glob, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
9
|
-
import { createUnimport } from "unimport";
|
|
10
|
-
import { findDynamicImports, resolvePathSync } from "mlly";
|
|
11
|
-
import { build } from "esbuild";
|
|
12
|
-
import { resolveModule } from "local-pkg";
|
|
13
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
14
|
-
import { dirname as dirname$2, join as join$1, normalize as normalize$1 } from "node:path/posix";
|
|
15
|
-
import { parse } from "yaml";
|
|
16
|
-
import { setTimeout } from "node:timers/promises";
|
|
17
|
-
//#region ../internal/src/build/vite.ts
|
|
18
|
-
function createNoExternalMerger(packageName) {
|
|
19
|
-
return (current) => {
|
|
20
|
-
if (current === true) return true;
|
|
21
|
-
if (!current) return [packageName];
|
|
22
|
-
const values = Array.isArray(current) ? current : [current];
|
|
23
|
-
return values.includes(packageName) ? values : [...values, packageName];
|
|
24
|
-
};
|
|
25
|
-
}
|
|
26
|
-
function isServerEnvironment(name, config) {
|
|
27
|
-
return name === "ssr" || config.consumer === "server";
|
|
28
|
-
}
|
|
29
|
-
const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
|
|
30
|
-
function includesNitroVitePlugin(value) {
|
|
31
|
-
if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
|
|
32
|
-
if (!value || typeof value !== "object") return false;
|
|
33
|
-
return "name" in value && value.name === "nitro:main";
|
|
34
|
-
}
|
|
35
|
-
function hasNitroConfigContext(config) {
|
|
36
|
-
return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
|
|
37
|
-
}
|
|
38
|
-
function deploymentPresetFromNitro(value) {
|
|
39
|
-
const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
|
|
40
|
-
if (!normalized) return;
|
|
41
|
-
if (normalized.startsWith("cloudflare")) return "cloudflare";
|
|
42
|
-
if (normalized.startsWith("deno")) return "deno";
|
|
43
|
-
if (normalized.startsWith("netlify")) return "netlify";
|
|
44
|
-
if (normalized === "node" || normalized.startsWith("node-")) return "node";
|
|
45
|
-
if (normalized.startsWith("vercel")) return "vercel";
|
|
46
|
-
}
|
|
47
|
-
//#endregion
|
|
48
|
-
//#region ../internal/src/hosting.ts
|
|
49
|
-
function normalizeHosting(hosting) {
|
|
50
|
-
const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
|
|
51
|
-
if (normalized === "cloudflare") return "cloudflare-module";
|
|
52
|
-
return normalized;
|
|
53
|
-
}
|
|
54
|
-
function detectHosting(target) {
|
|
55
|
-
return normalizeHosting(target.options.preset || process.env.VITEHUB_HOSTING || "");
|
|
56
|
-
}
|
|
57
|
-
function getHostingProvider(hosting) {
|
|
58
|
-
const preset = deploymentPresetFromNitro(hosting);
|
|
59
|
-
if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
|
|
60
|
-
}
|
|
61
|
-
function getSupportedHostingProvider(hosting, supportedProviders) {
|
|
62
|
-
const provider = getHostingProvider(hosting);
|
|
63
|
-
if (!provider || !supportedProviders.includes(provider)) return void 0;
|
|
64
|
-
return provider;
|
|
65
|
-
}
|
|
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
|
|
84
|
-
//#region ../internal/src/build/paths.ts
|
|
85
|
-
function generatedDirSegments(productName) {
|
|
86
|
-
return [".vitehub", productName];
|
|
87
|
-
}
|
|
88
|
-
function ensureGeneratedDir(rootDir, productName) {
|
|
89
|
-
return resolve(rootDir, ...generatedDirSegments(productName));
|
|
90
|
-
}
|
|
91
|
-
function createImportPath(fromFile, targetFile) {
|
|
92
|
-
const importPath = relative(realpathIfExists(dirname(fromFile)), realpathIfExists(targetFile));
|
|
93
|
-
return importPath.startsWith(".") ? importPath : `./${importPath}`;
|
|
94
|
-
}
|
|
95
|
-
function realpathIfExists(path) {
|
|
96
|
-
try {
|
|
97
|
-
return realpathSync.native(path);
|
|
98
|
-
} catch {
|
|
99
|
-
return resolve(path);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
//#endregion
|
|
103
|
-
//#region ../internal/src/definition-catalog.ts
|
|
104
|
-
const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
|
|
105
|
-
const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
|
|
106
|
-
const ignoredDirs = new Set([
|
|
107
|
-
"node_modules",
|
|
108
|
-
"dist",
|
|
109
|
-
".output",
|
|
110
|
-
".nuxt",
|
|
111
|
-
".vercel",
|
|
112
|
-
".git",
|
|
113
|
-
".vitehub"
|
|
114
|
-
]);
|
|
115
|
-
function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
|
|
116
|
-
return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
|
|
117
|
-
}
|
|
118
|
-
function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
|
|
119
|
-
return {
|
|
120
|
-
...options,
|
|
121
|
-
kind: "suffix",
|
|
122
|
-
normalizeName,
|
|
123
|
-
pattern,
|
|
124
|
-
roots,
|
|
125
|
-
source
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
function readDirEntries(root) {
|
|
129
|
-
try {
|
|
130
|
-
return readdirSync(root, { withFileTypes: true });
|
|
131
|
-
} catch (error) {
|
|
132
|
-
if (error.code === "ENOENT") return [];
|
|
133
|
-
throw error;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
function isGitRepositoryDirectory(directory) {
|
|
137
|
-
return existsSync(resolve(directory, ".git"));
|
|
138
|
-
}
|
|
139
|
-
function listMatchingFiles(root, predicate, options = {}) {
|
|
140
|
-
const files = [];
|
|
141
|
-
for (const entry of readDirEntries(root)) {
|
|
142
|
-
const absolute = resolve(root, entry.name);
|
|
143
|
-
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
144
|
-
if (isGitRepositoryDirectory(absolute)) continue;
|
|
145
|
-
if (entry.name.startsWith(".")) continue;
|
|
146
|
-
if (ignoredDirs.has(entry.name)) continue;
|
|
147
|
-
files.push(...listMatchingFiles(absolute, predicate, options));
|
|
148
|
-
continue;
|
|
149
|
-
}
|
|
150
|
-
if (entry.name.startsWith(".") && !options.includeHidden) continue;
|
|
151
|
-
if (entry.isFile() && predicate(entry.name)) files.push(absolute);
|
|
152
|
-
}
|
|
153
|
-
return files.sort();
|
|
154
|
-
}
|
|
155
|
-
function listSourceFiles(root, options = {}) {
|
|
156
|
-
return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
|
|
157
|
-
}
|
|
158
|
-
function normalizePathDefinitionName(rootDir, file) {
|
|
159
|
-
return relative(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
|
|
160
|
-
}
|
|
161
|
-
function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
|
|
162
|
-
const normalized = relative(rootDir, file).replace(pattern, "");
|
|
163
|
-
if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
|
|
164
|
-
return normalized;
|
|
165
|
-
}
|
|
166
|
-
function sortDefinitions(definitions) {
|
|
167
|
-
return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
168
|
-
}
|
|
169
|
-
function registerDefinition(definitions, definition, sourceLabel) {
|
|
170
|
-
const existing = definitions.get(definition.name);
|
|
171
|
-
if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
|
|
172
|
-
definitions.set(definition.name, definition);
|
|
173
|
-
}
|
|
174
|
-
function mergeDefinitions(feature, ...sources) {
|
|
175
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
176
|
-
for (const source of sources) {
|
|
177
|
-
if (!source) continue;
|
|
178
|
-
for (const definition of source) {
|
|
179
|
-
const existing = definitions.get(definition.name);
|
|
180
|
-
if (existing && existing.handler !== definition.handler) throw new Error(`Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})`);
|
|
181
|
-
if (!existing) definitions.set(definition.name, definition);
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
return sortDefinitions(definitions);
|
|
185
|
-
}
|
|
186
|
-
function createDefinition(source, file, name) {
|
|
187
|
-
if (source.createDefinition) return source.createDefinition({
|
|
188
|
-
file,
|
|
189
|
-
name
|
|
190
|
-
});
|
|
191
|
-
return {
|
|
192
|
-
handler: file,
|
|
193
|
-
name,
|
|
194
|
-
source: source.source
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
function scanSuffixDefinitions(feature, source) {
|
|
198
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
199
|
-
for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
|
|
200
|
-
const name = source.normalizeName(root, file);
|
|
201
|
-
if (!name) continue;
|
|
202
|
-
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
203
|
-
}
|
|
204
|
-
return sortDefinitions(definitions);
|
|
205
|
-
}
|
|
206
|
-
function scanDirectoryDefinitions(feature, source) {
|
|
207
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
208
|
-
for (const scanDir of source.scanDirs) {
|
|
209
|
-
const directory = resolve(scanDir, source.subdir);
|
|
210
|
-
for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
|
|
211
|
-
const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
|
|
212
|
-
if (!name) continue;
|
|
213
|
-
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
return sortDefinitions(definitions);
|
|
217
|
-
}
|
|
218
|
-
function discoverDefinitions(feature, sources) {
|
|
219
|
-
return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
|
|
220
|
-
}
|
|
221
|
-
async function writeFileIfChanged(file, contents) {
|
|
222
|
-
if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
|
|
223
|
-
await mkdir(resolve(file, ".."), { recursive: true });
|
|
224
|
-
await writeFile(file, contents, "utf8");
|
|
225
|
-
}
|
|
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
|
|
327
|
-
//#region src/cloudflare.ts
|
|
328
|
-
const defaultCloudflareSandboxBinding = "SANDBOX";
|
|
329
|
-
const defaultCloudflareSandboxClassName = "Sandbox";
|
|
330
|
-
const defaultCloudflareSandboxMaxInstances = 12;
|
|
331
|
-
const require$1 = createRequire(import.meta.url);
|
|
332
|
-
function resolveCloudflareSandboxEntrypoint() {
|
|
333
|
-
try {
|
|
334
|
-
return require$1.resolve("@cloudflare/sandbox");
|
|
335
|
-
} catch {
|
|
336
|
-
throw new Error("[vitehub] The Cloudflare Sandbox provider requires @cloudflare/sandbox. Install a supported version before building.");
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
function resolveCloudflareSandboxVersion() {
|
|
340
|
-
const pkg = require$1(join(resolveCloudflareSandboxEntrypoint(), "..", "..", "package.json"));
|
|
341
|
-
if (typeof pkg?.version !== "string") throw new Error("[vitehub] Could not resolve the installed @cloudflare/sandbox version.");
|
|
342
|
-
return pkg.version;
|
|
343
|
-
}
|
|
344
|
-
function resolveCloudflareSandboxEntrypointOptions(options = {}) {
|
|
345
|
-
if (options.className === "ContainerProxy") throw new Error("[vitehub] Cloudflare Sandbox className \"ContainerProxy\" is reserved by @cloudflare/sandbox. Configure a different className.");
|
|
346
|
-
return {
|
|
347
|
-
binding: options.binding || "SANDBOX",
|
|
348
|
-
className: options.className || "Sandbox",
|
|
349
|
-
migrationTag: options.migrationTag || "v1",
|
|
350
|
-
name: options.name || void 0
|
|
351
|
-
};
|
|
352
|
-
}
|
|
353
|
-
function mergeRollupExternal(value, addition) {
|
|
354
|
-
if (typeof value === "undefined") return [addition];
|
|
355
|
-
if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
|
|
356
|
-
if (typeof value === "string" || value instanceof RegExp) return [value, addition];
|
|
357
|
-
if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
|
|
358
|
-
return value;
|
|
359
|
-
}
|
|
360
|
-
function configureCloudflareSandbox(target, options = {}) {
|
|
361
|
-
const { binding, className, migrationTag, name } = resolveCloudflareSandboxEntrypointOptions(options);
|
|
362
|
-
if (typeof target.cloudflare?.wrangler?.exports !== "undefined") throw new Error("[vitehub] Cloudflare Sandbox cannot compose legacy migrations with an existing Wrangler exports configuration. Remove exports or configure the Sandbox Durable Object explicitly.");
|
|
363
|
-
const existingMigrations = target.cloudflare?.wrangler?.migrations;
|
|
364
|
-
if (!existingMigrations?.some((entry) => entry.new_sqlite_classes?.includes(className)) && existingMigrations?.some((entry) => entry.tag === migrationTag)) throw new Error(`[vitehub] Cloudflare migration tag ${JSON.stringify(migrationTag)} is already in use. Configure a unique sandbox migrationTag.`);
|
|
365
|
-
if ((target.cloudflare?.wrangler?.durable_objects?.bindings)?.some((entry) => entry.name === binding && entry.class_name !== className)) throw new Error(`[vitehub] Cloudflare Durable Object binding ${JSON.stringify(binding)} is already in use. Configure a unique sandbox binding.`);
|
|
366
|
-
target.cloudflare ||= {};
|
|
367
|
-
target.cloudflare.wrangler ||= {};
|
|
368
|
-
target.cloudflare.wrangler.containers ||= [];
|
|
369
|
-
target.cloudflare.wrangler.durable_objects ||= {};
|
|
370
|
-
target.cloudflare.wrangler.durable_objects.bindings ||= [];
|
|
371
|
-
target.cloudflare.wrangler.migrations ||= [];
|
|
372
|
-
const containers = target.cloudflare.wrangler.containers;
|
|
373
|
-
const image = "./Dockerfile";
|
|
374
|
-
if (!containers.some((entry) => entry.class_name === className)) containers.push({
|
|
375
|
-
class_name: className,
|
|
376
|
-
image,
|
|
377
|
-
instance_type: "lite",
|
|
378
|
-
max_instances: defaultCloudflareSandboxMaxInstances,
|
|
379
|
-
...name ? { name } : {}
|
|
380
|
-
});
|
|
381
|
-
else {
|
|
382
|
-
const container = containers.find((entry) => entry.class_name === className);
|
|
383
|
-
container.image ??= image;
|
|
384
|
-
if (typeof container.max_instances !== "number") container.max_instances = defaultCloudflareSandboxMaxInstances;
|
|
385
|
-
if (name) container.name ??= name;
|
|
386
|
-
}
|
|
387
|
-
const bindings = target.cloudflare.wrangler.durable_objects.bindings;
|
|
388
|
-
if (!bindings.some((entry) => entry.name === binding && entry.class_name === className)) bindings.push({
|
|
389
|
-
name: binding,
|
|
390
|
-
class_name: className
|
|
391
|
-
});
|
|
392
|
-
const migrations = target.cloudflare.wrangler.migrations;
|
|
393
|
-
if (!migrations.some((entry) => Array.isArray(entry.new_sqlite_classes) && entry.new_sqlite_classes.includes(className))) migrations.push({
|
|
394
|
-
tag: migrationTag,
|
|
395
|
-
new_sqlite_classes: [className]
|
|
396
|
-
});
|
|
397
|
-
}
|
|
398
|
-
function createCloudflareSandboxRollupPlugin(options = {}) {
|
|
399
|
-
const { className } = resolveCloudflareSandboxEntrypointOptions(options);
|
|
400
|
-
const cloudflareSandboxEntrypoint = resolveCloudflareSandboxEntrypoint();
|
|
401
|
-
const moduleId = "virtual:vitehub-sandbox-cloudflare-exports";
|
|
402
|
-
const resolvedModuleId = "\0virtual:vitehub-sandbox-cloudflare-exports";
|
|
403
|
-
return {
|
|
404
|
-
name: "vitehub-sandbox-cloudflare-exports",
|
|
405
|
-
buildStart() {
|
|
406
|
-
this.emitFile({
|
|
407
|
-
type: "chunk",
|
|
408
|
-
id: moduleId,
|
|
409
|
-
fileName: "sandbox-cloudflare-exports.mjs"
|
|
410
|
-
});
|
|
411
|
-
},
|
|
412
|
-
resolveId(id) {
|
|
413
|
-
if (id === moduleId) return resolvedModuleId;
|
|
414
|
-
if (id === "@cloudflare/sandbox") return cloudflareSandboxEntrypoint;
|
|
415
|
-
},
|
|
416
|
-
load(id) {
|
|
417
|
-
if (id === resolvedModuleId) return [
|
|
418
|
-
`import { Sandbox as CloudflareSandbox } from '@cloudflare/sandbox'`,
|
|
419
|
-
`export { ContainerProxy } from '@cloudflare/sandbox'`,
|
|
420
|
-
``,
|
|
421
|
-
`export class ${className} extends CloudflareSandbox {}`,
|
|
422
|
-
``
|
|
423
|
-
].join("\n");
|
|
424
|
-
},
|
|
425
|
-
renderChunk(code, chunk) {
|
|
426
|
-
if (!chunk.isEntry) return null;
|
|
427
|
-
const exportedNames = new Set(chunk.exports);
|
|
428
|
-
const missingExports = [className, "ContainerProxy"].filter((name) => !exportedNames.has(name));
|
|
429
|
-
if (!missingExports.length) return null;
|
|
430
|
-
const exportsPath = relative(dirname(chunk.fileName), "sandbox-cloudflare-exports.mjs").replace(/\\/g, "/");
|
|
431
|
-
const importPath = exportsPath.startsWith(".") ? exportsPath : `./${exportsPath}`;
|
|
432
|
-
return {
|
|
433
|
-
code: `${code}\nexport { ${missingExports.join(", ")} } from ${JSON.stringify(importPath)}\n`,
|
|
434
|
-
map: null
|
|
435
|
-
};
|
|
436
|
-
}
|
|
437
|
-
};
|
|
438
|
-
}
|
|
439
|
-
function installCloudflareSandboxEntrypoint(target, options = {}) {
|
|
440
|
-
const { className } = resolveCloudflareSandboxEntrypointOptions(options);
|
|
441
|
-
target.rollupConfig ||= {};
|
|
442
|
-
const plugins = Array.isArray(target.rollupConfig.plugins) ? target.rollupConfig.plugins : target.rollupConfig.plugins ? [target.rollupConfig.plugins] : [];
|
|
443
|
-
target.rollupConfig.plugins = plugins;
|
|
444
|
-
if (plugins.some((plugin) => typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === `vitehub-sandbox-cloudflare-exports:${className}`)) return;
|
|
445
|
-
const plugin = createCloudflareSandboxRollupPlugin({ className });
|
|
446
|
-
plugin.name = `vitehub-sandbox-cloudflare-exports:${className}`;
|
|
447
|
-
plugins.push(plugin);
|
|
448
|
-
}
|
|
449
|
-
async function writeCloudflareSandboxDockerfile(serverDir) {
|
|
450
|
-
const dockerfilePath = join(serverDir, "Dockerfile");
|
|
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"));
|
|
456
|
-
return dockerfilePath;
|
|
457
|
-
}
|
|
458
|
-
function relativeWranglerPath(from, to) {
|
|
459
|
-
const path = relative(from, to).replace(/\\/g, "/");
|
|
460
|
-
return path.startsWith(".") ? path : `./${path}`;
|
|
461
|
-
}
|
|
462
|
-
async function configureCloudflareSandboxNitro(targetValue, rootDir, options = {}, finalizeWrangler = true) {
|
|
463
|
-
const target = targetValue || {};
|
|
464
|
-
const serverDir = resolve(rootDir, target.output?.serverDir || ".output/server");
|
|
465
|
-
const resolvedOptions = resolveCloudflareSandboxEntrypointOptions(options);
|
|
466
|
-
const existingImage = (target.cloudflare?.wrangler?.containers?.find((entry) => entry.class_name === resolvedOptions.className))?.image?.replace(/\\/g, "/");
|
|
467
|
-
configureCloudflareSandbox(target, resolvedOptions);
|
|
468
|
-
const container = target.cloudflare.wrangler.containers.find((entry) => entry.class_name === resolvedOptions.className);
|
|
469
|
-
if (typeof existingImage !== "string" || existingImage.endsWith("/.vitehub/sandbox/Dockerfile")) {
|
|
470
|
-
container.image = relativeWranglerPath(serverDir, await writeCloudflareSandboxDockerfile(resolve(rootDir, ".vitehub/sandbox")));
|
|
471
|
-
container.image_build_context = relativeWranglerPath(serverDir, rootDir);
|
|
472
|
-
}
|
|
473
|
-
const wrangler = target.cloudflare.wrangler;
|
|
474
|
-
wrangler.compatibility_flags = Array.isArray(wrangler.compatibility_flags) ? [...wrangler.compatibility_flags] : [];
|
|
475
|
-
if (!wrangler.compatibility_flags.includes("nodejs_compat")) wrangler.compatibility_flags.push("nodejs_compat");
|
|
476
|
-
target.rollupConfig ||= {};
|
|
477
|
-
target.rollupConfig.external = mergeRollupExternal(target.rollupConfig.external, "cloudflare:workers");
|
|
478
|
-
installCloudflareSandboxEntrypoint(target, resolvedOptions);
|
|
479
|
-
if (finalizeWrangler) finalizeCloudflareWranglerConfig(target);
|
|
480
|
-
return target;
|
|
481
|
-
}
|
|
482
|
-
//#endregion
|
|
483
|
-
//#region src/internal/shared/discovered-definition/bundler.ts
|
|
484
|
-
const builtinModuleSet$2 = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
485
|
-
function resolveDefinitionLoader(options) {
|
|
486
|
-
let loader = options.loader;
|
|
487
|
-
if (!loader) {
|
|
488
|
-
const f = options.filename;
|
|
489
|
-
if (f.endsWith(".tsx")) loader = "tsx";
|
|
490
|
-
else if (f.endsWith(".jsx")) loader = "jsx";
|
|
491
|
-
else if (f.endsWith(".js") || f.endsWith(".mjs") || f.endsWith(".cjs")) loader = "js";
|
|
492
|
-
else loader = "ts";
|
|
493
|
-
}
|
|
494
|
-
return loader;
|
|
495
|
-
}
|
|
496
|
-
function isJsxDefinitionLoader(options) {
|
|
497
|
-
const loader = resolveDefinitionLoader(options);
|
|
498
|
-
return loader === "tsx" || loader === "jsx";
|
|
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
|
-
}
|
|
503
|
-
async function bundleDiscoveredDefinitionModule(options) {
|
|
504
|
-
const output = (await build({
|
|
505
|
-
alias: options.alias,
|
|
506
|
-
stdin: {
|
|
507
|
-
contents: options.source,
|
|
508
|
-
loader: resolveDefinitionLoader(options),
|
|
509
|
-
resolveDir: dirname(options.filename),
|
|
510
|
-
sourcefile: options.filename
|
|
511
|
-
},
|
|
512
|
-
bundle: true,
|
|
513
|
-
write: false,
|
|
514
|
-
format: "esm",
|
|
515
|
-
platform: "node",
|
|
516
|
-
target: "es2022",
|
|
517
|
-
logLevel: "silent",
|
|
518
|
-
jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
|
|
519
|
-
jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
|
|
520
|
-
packages: options.packages === "external" ? "external" : void 0,
|
|
521
|
-
external: [...builtinModuleSet$2, ...options.external || []],
|
|
522
|
-
plugins: options.plugins
|
|
523
|
-
})).outputFiles?.[0]?.text;
|
|
524
|
-
if (!output) throw new Error(`[vitehub] Failed to bundle discovered definition "${options.filename}".`);
|
|
525
|
-
return output;
|
|
526
|
-
}
|
|
527
|
-
async function bundleDiscoveredDefinitionModuleGraph(options) {
|
|
528
|
-
const outdir = resolve(dirname(options.filename), ".vitehub-discovered-definition");
|
|
529
|
-
const result = await build({
|
|
530
|
-
alias: options.alias,
|
|
531
|
-
stdin: {
|
|
532
|
-
contents: options.source,
|
|
533
|
-
loader: resolveDefinitionLoader(options),
|
|
534
|
-
resolveDir: dirname(options.filename),
|
|
535
|
-
sourcefile: options.filename
|
|
536
|
-
},
|
|
537
|
-
bundle: true,
|
|
538
|
-
splitting: true,
|
|
539
|
-
entryNames: "definition",
|
|
540
|
-
chunkNames: "chunks/[name]-[hash]",
|
|
541
|
-
outdir,
|
|
542
|
-
write: false,
|
|
543
|
-
format: "esm",
|
|
544
|
-
platform: "node",
|
|
545
|
-
target: "es2022",
|
|
546
|
-
metafile: true,
|
|
547
|
-
logLevel: "silent",
|
|
548
|
-
jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
|
|
549
|
-
jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
|
|
550
|
-
packages: options.packages === "external" ? "external" : void 0,
|
|
551
|
-
external: [...builtinModuleSet$2, ...options.external || []],
|
|
552
|
-
plugins: options.plugins
|
|
553
|
-
});
|
|
554
|
-
const modules = Object.fromEntries((result.outputFiles || []).map((outputFile) => {
|
|
555
|
-
return [relative(outdir, outputFile.path), outputFile.text];
|
|
556
|
-
}));
|
|
557
|
-
if (!modules["definition.js"]) throw new Error(`[vitehub] Failed to bundle discovered definition graph "${options.filename}".`);
|
|
558
|
-
return {
|
|
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),
|
|
562
|
-
modules
|
|
563
|
-
};
|
|
564
|
-
}
|
|
565
|
-
//#endregion
|
|
566
|
-
//#region src/internal/shared/discovered-definition/ast.ts
|
|
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
|
-
]);
|
|
585
|
-
function resolveImportLocalName(entry) {
|
|
586
|
-
return entry.as || entry.name;
|
|
587
|
-
}
|
|
588
|
-
function getScriptKind(id) {
|
|
589
|
-
const scriptKind = typescript$1.ScriptKind;
|
|
590
|
-
if (id.endsWith(".tsx")) return typescript$1.ScriptKind.TSX;
|
|
591
|
-
if (id.endsWith(".jsx")) return typescript$1.ScriptKind.JSX;
|
|
592
|
-
if (id.endsWith(".mts")) return scriptKind.MTS ?? typescript$1.ScriptKind.TS;
|
|
593
|
-
if (id.endsWith(".cts")) return scriptKind.CTS ?? typescript$1.ScriptKind.TS;
|
|
594
|
-
if (id.endsWith(".mjs")) return typescript$1.ScriptKind.JS;
|
|
595
|
-
if (id.endsWith(".cjs")) return typescript$1.ScriptKind.JS;
|
|
596
|
-
if (id.endsWith(".js")) return typescript$1.ScriptKind.JS;
|
|
597
|
-
return typescript$1.ScriptKind.TS;
|
|
598
|
-
}
|
|
599
|
-
function createSourceFile(id, source) {
|
|
600
|
-
return typescript$1.createSourceFile(id, source, typescript$1.ScriptTarget.Latest, true, getScriptKind(id));
|
|
601
|
-
}
|
|
602
|
-
function collectRuntimeModuleSpecifiers(source, id) {
|
|
603
|
-
const sourceFile = createSourceFile(id, source);
|
|
604
|
-
const specifiers = [];
|
|
605
|
-
let hasNonLiteralDynamicImport = false;
|
|
606
|
-
function addSpecifier(node) {
|
|
607
|
-
if (node && typescript$1.isStringLiteralLike(node)) specifiers.push({
|
|
608
|
-
node,
|
|
609
|
-
specifier: node.text
|
|
610
|
-
});
|
|
611
|
-
}
|
|
612
|
-
function visit(node) {
|
|
613
|
-
if (typescript$1.isImportDeclaration(node)) {
|
|
614
|
-
const clause = node.importClause;
|
|
615
|
-
const bindings = clause?.namedBindings;
|
|
616
|
-
if (!clause || !clause.isTypeOnly && (Boolean(clause.name) || !bindings || typescript$1.isNamespaceImport(bindings) || bindings.elements.length === 0 || bindings.elements.some((element) => !element.isTypeOnly))) addSpecifier(node.moduleSpecifier);
|
|
617
|
-
} else if (typescript$1.isExportDeclaration(node)) {
|
|
618
|
-
const clause = node.exportClause;
|
|
619
|
-
if (!node.isTypeOnly && (!clause || typescript$1.isNamespaceExport(clause) || clause.elements.length === 0 || clause.elements.some((element) => !element.isTypeOnly))) addSpecifier(node.moduleSpecifier);
|
|
620
|
-
} else if (typescript$1.isCallExpression(node) && node.expression.kind === typescript$1.SyntaxKind.ImportKeyword) {
|
|
621
|
-
const argument = node.arguments[0];
|
|
622
|
-
if (argument && typescript$1.isStringLiteralLike(argument)) addSpecifier(argument);
|
|
623
|
-
else hasNonLiteralDynamicImport = true;
|
|
624
|
-
}
|
|
625
|
-
typescript$1.forEachChild(node, visit);
|
|
626
|
-
}
|
|
627
|
-
visit(sourceFile);
|
|
628
|
-
return {
|
|
629
|
-
hasNonLiteralDynamicImport,
|
|
630
|
-
sourceFile,
|
|
631
|
-
specifiers
|
|
632
|
-
};
|
|
633
|
-
}
|
|
634
|
-
function findRuntimeModuleSpecifiers(source, id) {
|
|
635
|
-
return collectRuntimeModuleSpecifiers(source, id).specifiers.map((entry) => entry.specifier);
|
|
636
|
-
}
|
|
637
|
-
function hasNonLiteralDynamicImport(source, id) {
|
|
638
|
-
return collectRuntimeModuleSpecifiers(source, id).hasNonLiteralDynamicImport;
|
|
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
|
-
}
|
|
822
|
-
function propertyAccessRoot(expression) {
|
|
823
|
-
const properties = [];
|
|
824
|
-
let current = expression;
|
|
825
|
-
while (typescript$1.isPropertyAccessExpression(current) || typescript$1.isElementAccessExpression(current)) {
|
|
826
|
-
if (typescript$1.isPropertyAccessExpression(current)) {
|
|
827
|
-
properties.unshift(current.name.text);
|
|
828
|
-
current = current.expression;
|
|
829
|
-
continue;
|
|
830
|
-
}
|
|
831
|
-
const argument = current.argumentExpression;
|
|
832
|
-
properties.unshift(argument && typescript$1.isStringLiteralLike(argument) ? argument.text : "*");
|
|
833
|
-
current = current.expression;
|
|
834
|
-
}
|
|
835
|
-
return {
|
|
836
|
-
current,
|
|
837
|
-
properties
|
|
838
|
-
};
|
|
839
|
-
}
|
|
840
|
-
function findCommonJSImportEqualsSpecifiers(source, id) {
|
|
841
|
-
const sourceFile = createSourceFile(id, source);
|
|
842
|
-
const specifiers = [];
|
|
843
|
-
function visit(node) {
|
|
844
|
-
if (typescript$1.isImportEqualsDeclaration(node) && !node.isTypeOnly && typescript$1.isExternalModuleReference(node.moduleReference)) {
|
|
845
|
-
const expression = node.moduleReference.expression;
|
|
846
|
-
specifiers.push({
|
|
847
|
-
path: id,
|
|
848
|
-
specifier: expression && typescript$1.isStringLiteralLike(expression) ? expression.text : void 0,
|
|
849
|
-
syntax: "import-equals"
|
|
850
|
-
});
|
|
851
|
-
}
|
|
852
|
-
typescript$1.forEachChild(node, visit);
|
|
853
|
-
}
|
|
854
|
-
visit(sourceFile);
|
|
855
|
-
return specifiers;
|
|
856
|
-
}
|
|
857
|
-
function isExecutableIdentifierReference(node) {
|
|
858
|
-
const parent = node.parent;
|
|
859
|
-
if (typescript$1.isImportClause(parent) || typescript$1.isImportSpecifier(parent) || typescript$1.isNamespaceImport(parent) || typescript$1.isNamespaceExport(parent)) return false;
|
|
860
|
-
if (typescript$1.isExportSpecifier(parent)) {
|
|
861
|
-
if (parent.parent.parent.moduleSpecifier) return false;
|
|
862
|
-
return parent.propertyName ? parent.propertyName === node : parent.name === node;
|
|
863
|
-
}
|
|
864
|
-
if (typescript$1.isBindingElement(parent) && (parent.name === node || parent.propertyName === node)) return false;
|
|
865
|
-
if (typescript$1.isPropertyAccessExpression(parent) && parent.name === node) return false;
|
|
866
|
-
if (typescript$1.isLabeledStatement(parent) || typescript$1.isBreakStatement(parent) || typescript$1.isContinueStatement(parent)) return false;
|
|
867
|
-
if (!typescript$1.isShorthandPropertyAssignment(parent) && "name" in parent && parent.name === node) return false;
|
|
868
|
-
return !("propertyName" in parent) || parent.propertyName !== node;
|
|
869
|
-
}
|
|
870
|
-
function findExecutableCommonJSModuleSpecifiers(sources) {
|
|
871
|
-
const executableSources = new Map([...sources].map(([path, source]) => [`/${path.replace(/^[/]+/, "")}`, source]));
|
|
872
|
-
const options = {
|
|
873
|
-
allowJs: true,
|
|
874
|
-
checkJs: false,
|
|
875
|
-
module: typescript$1.ModuleKind.ESNext,
|
|
876
|
-
moduleDetection: typescript$1.ModuleDetectionKind.Force,
|
|
877
|
-
noLib: true,
|
|
878
|
-
noResolve: true,
|
|
879
|
-
target: typescript$1.ScriptTarget.ES2022,
|
|
880
|
-
types: []
|
|
881
|
-
};
|
|
882
|
-
const sourceFiles = /* @__PURE__ */ new Map();
|
|
883
|
-
const program = typescript$1.createProgram({
|
|
884
|
-
host: {
|
|
885
|
-
fileExists: (fileName) => executableSources.has(fileName),
|
|
886
|
-
getCanonicalFileName: (fileName) => fileName,
|
|
887
|
-
getCurrentDirectory: () => "/",
|
|
888
|
-
getDefaultLibFileName: () => "",
|
|
889
|
-
getNewLine: () => "\n",
|
|
890
|
-
getSourceFile(fileName, languageVersion) {
|
|
891
|
-
const source = executableSources.get(fileName);
|
|
892
|
-
if (source === void 0) return void 0;
|
|
893
|
-
let sourceFile = sourceFiles.get(fileName);
|
|
894
|
-
if (!sourceFile) {
|
|
895
|
-
sourceFile = typescript$1.createSourceFile(fileName, source, languageVersion, true, typescript$1.ScriptKind.JS);
|
|
896
|
-
sourceFiles.set(fileName, sourceFile);
|
|
897
|
-
}
|
|
898
|
-
return sourceFile;
|
|
899
|
-
},
|
|
900
|
-
readFile: (fileName) => executableSources.get(fileName),
|
|
901
|
-
useCaseSensitiveFileNames: () => true,
|
|
902
|
-
writeFile: () => {}
|
|
903
|
-
},
|
|
904
|
-
options,
|
|
905
|
-
rootNames: [...executableSources.keys()]
|
|
906
|
-
});
|
|
907
|
-
const checker = program.getTypeChecker();
|
|
908
|
-
const specifiers = [];
|
|
909
|
-
function isRuntimeBindingDeclaration(node) {
|
|
910
|
-
return typescript$1.isBindingElement(node) || typescript$1.isClassDeclaration(node) || typescript$1.isClassExpression(node) || typescript$1.isFunctionDeclaration(node) || typescript$1.isFunctionExpression(node) || typescript$1.isImportClause(node) || typescript$1.isImportSpecifier(node) || typescript$1.isNamespaceImport(node) || typescript$1.isParameter(node) || typescript$1.isVariableDeclaration(node);
|
|
911
|
-
}
|
|
912
|
-
function isBound(node) {
|
|
913
|
-
return (typescript$1.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node))?.declarations?.some(isRuntimeBindingDeclaration) ?? false;
|
|
914
|
-
}
|
|
915
|
-
function visit(sourceFile, node) {
|
|
916
|
-
if (typescript$1.isCallExpression(node) && typescript$1.isIdentifier(node.expression) && node.expression.text === "require" && !isBound(node.expression)) {
|
|
917
|
-
const argument = node.arguments[0];
|
|
918
|
-
specifiers.push({
|
|
919
|
-
path: sourceFile.fileName.slice(1),
|
|
920
|
-
specifier: argument && typescript$1.isStringLiteralLike(argument) ? argument.text : void 0,
|
|
921
|
-
syntax: "require"
|
|
922
|
-
});
|
|
923
|
-
} else if (typescript$1.isPropertyAccessExpression(node) || typescript$1.isElementAccessExpression(node)) {
|
|
924
|
-
const { current, properties } = propertyAccessRoot(node);
|
|
925
|
-
if (typescript$1.isIdentifier(current) && current.text === "require" && !isBound(current)) specifiers.push({
|
|
926
|
-
path: sourceFile.fileName.slice(1),
|
|
927
|
-
specifier: properties.join("."),
|
|
928
|
-
syntax: "require-property"
|
|
929
|
-
});
|
|
930
|
-
} else if (typescript$1.isBinaryExpression(node) && node.operatorToken.kind >= typescript$1.SyntaxKind.FirstAssignment && node.operatorToken.kind <= typescript$1.SyntaxKind.LastAssignment) {
|
|
931
|
-
const { current, properties } = propertyAccessRoot(node.left);
|
|
932
|
-
if (typescript$1.isIdentifier(current) && current.text === "module" && !isBound(current) && properties[0] === "exports") specifiers.push({
|
|
933
|
-
path: sourceFile.fileName.slice(1),
|
|
934
|
-
syntax: "module-exports-assignment"
|
|
935
|
-
});
|
|
936
|
-
else if (typescript$1.isIdentifier(current) && current.text === "exports" && !isBound(current) && properties.length) specifiers.push({
|
|
937
|
-
path: sourceFile.fileName.slice(1),
|
|
938
|
-
syntax: "exports-assignment"
|
|
939
|
-
});
|
|
940
|
-
} else if (typescript$1.isIdentifier(node) && (node.text === "module" || node.text === "exports") && isExecutableIdentifierReference(node) && !isBound(node)) specifiers.push({
|
|
941
|
-
path: sourceFile.fileName.slice(1),
|
|
942
|
-
syntax: node.text === "module" ? "module-reference" : "exports-reference"
|
|
943
|
-
});
|
|
944
|
-
typescript$1.forEachChild(node, (child) => visit(sourceFile, child));
|
|
945
|
-
}
|
|
946
|
-
for (const sourceFile of program.getSourceFiles()) visit(sourceFile, sourceFile);
|
|
947
|
-
return specifiers;
|
|
948
|
-
}
|
|
949
|
-
function rewriteRuntimeRelativeModuleSpecifiers(source, id, rewrite) {
|
|
950
|
-
const { sourceFile, specifiers } = collectRuntimeModuleSpecifiers(source, id);
|
|
951
|
-
const edits = [];
|
|
952
|
-
for (const { node, specifier } of specifiers) {
|
|
953
|
-
if (!/^\.\.?\//.test(specifier)) continue;
|
|
954
|
-
const replacement = rewrite(specifier);
|
|
955
|
-
if (replacement !== specifier) edits.push({
|
|
956
|
-
start: node.getStart(sourceFile),
|
|
957
|
-
end: node.getEnd(),
|
|
958
|
-
replacement: JSON.stringify(replacement)
|
|
959
|
-
});
|
|
960
|
-
}
|
|
961
|
-
return edits.sort((left, right) => right.start - left.start).reduce((contents, edit) => `${contents.slice(0, edit.start)}${edit.replacement}${contents.slice(edit.end)}`, source);
|
|
962
|
-
}
|
|
963
|
-
function collectExplicitImportNames(sourceFile) {
|
|
964
|
-
const names = /* @__PURE__ */ new Set();
|
|
965
|
-
for (const statement of sourceFile.statements) {
|
|
966
|
-
if (!typescript$1.isImportDeclaration(statement)) continue;
|
|
967
|
-
const clause = statement.importClause;
|
|
968
|
-
if (!clause) continue;
|
|
969
|
-
if (clause.name) names.add(clause.name.text);
|
|
970
|
-
const bindings = clause.namedBindings;
|
|
971
|
-
if (!bindings) continue;
|
|
972
|
-
if (typescript$1.isNamespaceImport(bindings)) {
|
|
973
|
-
names.add(bindings.name.text);
|
|
974
|
-
continue;
|
|
975
|
-
}
|
|
976
|
-
for (const element of bindings.elements) names.add(element.name.text);
|
|
977
|
-
}
|
|
978
|
-
return names;
|
|
979
|
-
}
|
|
980
|
-
function collectDeclaredTypeNames(sourceFile) {
|
|
981
|
-
const names = /* @__PURE__ */ new Set();
|
|
982
|
-
function visit(node) {
|
|
983
|
-
if ((typescript$1.isInterfaceDeclaration(node) || typescript$1.isTypeAliasDeclaration(node) || typescript$1.isClassDeclaration(node) || typescript$1.isEnumDeclaration(node)) && node.name) names.add(node.name.text);
|
|
984
|
-
if ((typescript$1.isFunctionDeclaration(node) || typescript$1.isClassDeclaration(node) || typescript$1.isInterfaceDeclaration(node) || typescript$1.isMethodDeclaration(node) || typescript$1.isArrowFunction(node) || typescript$1.isFunctionExpression(node) || typescript$1.isTypeAliasDeclaration(node)) && node.typeParameters) for (const parameter of node.typeParameters) names.add(parameter.name.text);
|
|
985
|
-
typescript$1.forEachChild(node, visit);
|
|
986
|
-
}
|
|
987
|
-
visit(sourceFile);
|
|
988
|
-
return names;
|
|
989
|
-
}
|
|
990
|
-
function collectTypeReferenceNames(sourceFile) {
|
|
991
|
-
const names = /* @__PURE__ */ new Set();
|
|
992
|
-
function addEntityName(name) {
|
|
993
|
-
if (typescript$1.isIdentifier(name)) names.add(name.text);
|
|
994
|
-
}
|
|
995
|
-
function visit(node) {
|
|
996
|
-
if (typescript$1.isImportTypeNode(node) || typescript$1.isTypeQueryNode(node)) return;
|
|
997
|
-
if (typescript$1.isTypeReferenceNode(node)) {
|
|
998
|
-
addEntityName(node.typeName);
|
|
999
|
-
node.typeArguments?.forEach((argument) => visit(argument));
|
|
1000
|
-
return;
|
|
1001
|
-
}
|
|
1002
|
-
if (typescript$1.isExpressionWithTypeArguments(node)) {
|
|
1003
|
-
if (typescript$1.isIdentifier(node.expression)) names.add(node.expression.text);
|
|
1004
|
-
node.typeArguments?.forEach((argument) => visit(argument));
|
|
1005
|
-
return;
|
|
1006
|
-
}
|
|
1007
|
-
typescript$1.forEachChild(node, visit);
|
|
1008
|
-
}
|
|
1009
|
-
visit(sourceFile);
|
|
1010
|
-
return names;
|
|
1011
|
-
}
|
|
1012
|
-
function groupTypeImports(imports) {
|
|
1013
|
-
const grouped = /* @__PURE__ */ new Map();
|
|
1014
|
-
for (const entry of imports) {
|
|
1015
|
-
const from = entry.typeFrom || entry.from;
|
|
1016
|
-
const entries = grouped.get(from);
|
|
1017
|
-
if (entries) {
|
|
1018
|
-
entries.push(entry);
|
|
1019
|
-
continue;
|
|
1020
|
-
}
|
|
1021
|
-
grouped.set(from, [entry]);
|
|
1022
|
-
}
|
|
1023
|
-
return grouped;
|
|
1024
|
-
}
|
|
1025
|
-
function stringifyTypeImport(entry) {
|
|
1026
|
-
const localName = resolveImportLocalName(entry);
|
|
1027
|
-
if (localName === entry.name) return entry.name;
|
|
1028
|
-
return `${entry.name} as ${localName}`;
|
|
1029
|
-
}
|
|
1030
|
-
function injectTypeImports(source, imports, id) {
|
|
1031
|
-
if (!imports.length) return source;
|
|
1032
|
-
const importStatements = createSourceFile(id, source).statements.filter(typescript$1.isImportDeclaration);
|
|
1033
|
-
const groupedImports = groupTypeImports(imports);
|
|
1034
|
-
const block = Array.from(groupedImports.entries()).map(([from, entries]) => `import type { ${entries.map(stringifyTypeImport).join(", ")} } from ${JSON.stringify(from)}`).join("\n");
|
|
1035
|
-
if (!block) return source;
|
|
1036
|
-
const insertAt = importStatements.at(-1)?.end ?? (source.startsWith("#!") ? source.indexOf("\n") + 1 : 0);
|
|
1037
|
-
const prefix = source.slice(0, insertAt);
|
|
1038
|
-
const suffix = source.slice(insertAt);
|
|
1039
|
-
const needsLeadingNewline = insertAt > 0 && !prefix.endsWith("\n");
|
|
1040
|
-
const needsTrailingNewline = suffix.length > 0 && !suffix.startsWith("\n");
|
|
1041
|
-
return `${prefix}${needsLeadingNewline ? "\n" : ""}${block}${needsTrailingNewline ? "\n" : ""}${suffix}`;
|
|
1042
|
-
}
|
|
1043
|
-
async function injectTypeImportsFromUnimport(source, id, imports) {
|
|
1044
|
-
const sourceFile = createSourceFile(id, source);
|
|
1045
|
-
const explicitImports = collectExplicitImportNames(sourceFile);
|
|
1046
|
-
const declaredTypes = collectDeclaredTypeNames(sourceFile);
|
|
1047
|
-
const usedTypes = collectTypeReferenceNames(sourceFile);
|
|
1048
|
-
const pendingImports = [];
|
|
1049
|
-
for (const entry of imports) {
|
|
1050
|
-
if (!entry.type || entry.disabled) continue;
|
|
1051
|
-
const localName = resolveImportLocalName(entry);
|
|
1052
|
-
if (!usedTypes.has(localName)) continue;
|
|
1053
|
-
if (explicitImports.has(localName) || declaredTypes.has(localName)) continue;
|
|
1054
|
-
pendingImports.push(entry);
|
|
1055
|
-
explicitImports.add(localName);
|
|
1056
|
-
}
|
|
1057
|
-
return injectTypeImports(source, pendingImports, id);
|
|
1058
|
-
}
|
|
1059
|
-
//#endregion
|
|
1060
|
-
//#region src/internal/shared/server-imports.ts
|
|
1061
|
-
function isServerAutoImportEnabled(imports) {
|
|
1062
|
-
return imports !== false && imports?.autoImport !== false;
|
|
1063
|
-
}
|
|
1064
|
-
//#endregion
|
|
1065
|
-
//#region src/internal/shared/discovered-definition.ts
|
|
1066
|
-
function normalizeDir(rootDir, dir) {
|
|
1067
|
-
if (typeof dir === "string") return isAbsolute(dir) ? dir : resolve(rootDir, dir);
|
|
1068
|
-
return {
|
|
1069
|
-
...dir,
|
|
1070
|
-
glob: isAbsolute(dir.glob) ? dir.glob : resolve(rootDir, dir.glob)
|
|
1071
|
-
};
|
|
1072
|
-
}
|
|
1073
|
-
function normalizePresetImport(from, entry) {
|
|
1074
|
-
if (typeof entry === "string") return {
|
|
1075
|
-
from,
|
|
1076
|
-
name: entry
|
|
1077
|
-
};
|
|
1078
|
-
return {
|
|
1079
|
-
from,
|
|
1080
|
-
name: entry.name,
|
|
1081
|
-
...entry.as ? { as: entry.as } : {},
|
|
1082
|
-
...entry.type ? { type: true } : {}
|
|
1083
|
-
};
|
|
1084
|
-
}
|
|
1085
|
-
function normalizeServerImport(entry) {
|
|
1086
|
-
return {
|
|
1087
|
-
from: entry.from,
|
|
1088
|
-
name: entry.name,
|
|
1089
|
-
...entry.as ? { as: entry.as } : {},
|
|
1090
|
-
...entry.type ? { type: true } : {}
|
|
1091
|
-
};
|
|
1092
|
-
}
|
|
1093
|
-
function resolveDefaultImportDirs(rootDir, scanRoots) {
|
|
1094
|
-
return scanRoots.flatMap((scanRoot) => [normalizeDir(rootDir, join(scanRoot, "server/utils/**/*")), normalizeDir(rootDir, join(scanRoot, "shared/types/**/*"))]);
|
|
1095
|
-
}
|
|
1096
|
-
function isInlinePreset(value) {
|
|
1097
|
-
return !!value && typeof value === "object" && typeof value.from === "string" && Array.isArray(value.imports);
|
|
1098
|
-
}
|
|
1099
|
-
function isPresetImport(value) {
|
|
1100
|
-
return !!value && typeof value === "object" && typeof value.name === "string";
|
|
1101
|
-
}
|
|
1102
|
-
function normalizePresetImports(presets = []) {
|
|
1103
|
-
const normalized = [];
|
|
1104
|
-
function collect(from, entry) {
|
|
1105
|
-
if (typeof entry === "string") {
|
|
1106
|
-
normalized.push(normalizePresetImport(from, entry));
|
|
1107
|
-
return;
|
|
1108
|
-
}
|
|
1109
|
-
if (isInlinePreset(entry)) {
|
|
1110
|
-
for (const nested of entry.imports) collect(entry.from, nested);
|
|
1111
|
-
return;
|
|
1112
|
-
}
|
|
1113
|
-
if (isPresetImport(entry)) normalized.push(normalizePresetImport(from, entry));
|
|
1114
|
-
}
|
|
1115
|
-
for (const preset of presets) {
|
|
1116
|
-
if (!isInlinePreset(preset)) continue;
|
|
1117
|
-
for (const entry of preset.imports) collect(preset.from, entry);
|
|
1118
|
-
}
|
|
1119
|
-
return normalized;
|
|
1120
|
-
}
|
|
1121
|
-
async function createInitializedUnimport(options) {
|
|
1122
|
-
const serverImports = options.serverImports !== false ? options.serverImports : void 0;
|
|
1123
|
-
const unimport = createUnimport({
|
|
1124
|
-
imports: [...normalizePresetImports(serverImports?.presets), ...(options.featureImports || []).map(normalizeServerImport)],
|
|
1125
|
-
dirs: [...resolveDefaultImportDirs(options.rootDir, options.scanRoots), ...(serverImports?.dirs || []).map((dir) => normalizeDir(options.rootDir, dir))]
|
|
1126
|
-
});
|
|
1127
|
-
await unimport.init();
|
|
1128
|
-
return unimport;
|
|
1129
|
-
}
|
|
1130
|
-
async function createDiscoveredDefinitionCompiler(options = {}) {
|
|
1131
|
-
const resolvedOptions = {
|
|
1132
|
-
rootDir: options.rootDir || process.cwd(),
|
|
1133
|
-
scanRoots: options.scanRoots || [],
|
|
1134
|
-
serverImports: options.serverImports,
|
|
1135
|
-
featureImports: options.featureImports || []
|
|
1136
|
-
};
|
|
1137
|
-
if (!isServerAutoImportEnabled(resolvedOptions.serverImports)) return {
|
|
1138
|
-
enabled: false,
|
|
1139
|
-
async injectSource(source) {
|
|
1140
|
-
return source;
|
|
1141
|
-
},
|
|
1142
|
-
async readSource(id) {
|
|
1143
|
-
return await readFile(id, "utf8");
|
|
1144
|
-
},
|
|
1145
|
-
async bundleModule(bundleOptions) {
|
|
1146
|
-
return await bundleDiscoveredDefinitionModule(bundleOptions);
|
|
1147
|
-
}
|
|
1148
|
-
};
|
|
1149
|
-
const unimport = await createInitializedUnimport(resolvedOptions);
|
|
1150
|
-
const injectSource = async (source, id) => {
|
|
1151
|
-
return await injectTypeImportsFromUnimport((await unimport.injectImports(source, id)).code, id, await unimport.getImports());
|
|
1152
|
-
};
|
|
1153
|
-
return {
|
|
1154
|
-
enabled: true,
|
|
1155
|
-
injectSource,
|
|
1156
|
-
async readSource(id) {
|
|
1157
|
-
return await injectSource(await readFile(id, "utf8"), id);
|
|
1158
|
-
},
|
|
1159
|
-
async bundleModule(bundleOptions) {
|
|
1160
|
-
return await bundleDiscoveredDefinitionModule(bundleOptions);
|
|
1161
|
-
}
|
|
1162
|
-
};
|
|
1163
|
-
}
|
|
1164
|
-
//#endregion
|
|
1165
|
-
//#region src/internal/shared/feature-definitions.ts
|
|
1166
|
-
function toTemplateSafeName(name) {
|
|
1167
|
-
return name.replace(/[^a-z0-9/_:-]/gi, "_").replace(/\//g, "__").replace(/:/g, "__");
|
|
1168
|
-
}
|
|
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
|
|
1175
|
-
//#region src/internal/shared/module-resolve.ts
|
|
1176
|
-
function normalizePaths(paths) {
|
|
1177
|
-
if (paths?.length) return paths;
|
|
1178
|
-
if (typeof process !== "undefined") return [process.cwd()];
|
|
1179
|
-
return [];
|
|
1180
|
-
}
|
|
1181
|
-
function tryResolveFromRuntime(id) {
|
|
1182
|
-
const requireResolver = globalThis.require?.resolve;
|
|
1183
|
-
if (typeof requireResolver !== "function") return void 0;
|
|
1184
|
-
try {
|
|
1185
|
-
return requireResolver(id);
|
|
1186
|
-
} catch {
|
|
1187
|
-
return false;
|
|
1188
|
-
}
|
|
1189
|
-
}
|
|
1190
|
-
function tryResolveModule(id, options = {}) {
|
|
1191
|
-
const paths = normalizePaths(options.paths);
|
|
1192
|
-
const runtimeResolved = tryResolveFromRuntime(id);
|
|
1193
|
-
if (runtimeResolved === false) return [/* @__PURE__ */ new Error(`Unable to resolve module "${id}" using the active runtime resolver`), void 0];
|
|
1194
|
-
if (runtimeResolved) return [null, runtimeResolved];
|
|
1195
|
-
const resolved = resolveModule(id, { paths });
|
|
1196
|
-
if (resolved) return [null, resolved];
|
|
1197
|
-
for (const url of paths) try {
|
|
1198
|
-
return [null, resolvePathSync(id, { url })];
|
|
1199
|
-
} catch {
|
|
1200
|
-
continue;
|
|
1201
|
-
}
|
|
1202
|
-
return [/* @__PURE__ */ new Error(paths.length > 0 ? `Unable to resolve module "${id}" from ${paths.join(", ")}` : `Unable to resolve module "${id}" without explicit resolution paths`), void 0];
|
|
1203
|
-
}
|
|
1204
|
-
//#endregion
|
|
1205
|
-
//#region src/internal/shared/feature-runtime-path.ts
|
|
1206
|
-
function resolveExistingModulePath(path) {
|
|
1207
|
-
if (existsSync(path)) return path;
|
|
1208
|
-
for (const extension of [
|
|
1209
|
-
".ts",
|
|
1210
|
-
".mts",
|
|
1211
|
-
".js",
|
|
1212
|
-
".mjs"
|
|
1213
|
-
]) {
|
|
1214
|
-
const withExtension = `${path}${extension}`;
|
|
1215
|
-
if (existsSync(withExtension)) return withExtension;
|
|
1216
|
-
}
|
|
1217
|
-
}
|
|
1218
|
-
function resolveFeatureRuntimePath(importMetaUrl, packageId, sourceRelativePath, distRelativePath) {
|
|
1219
|
-
const importerDir = dirname(fileURLToPath(importMetaUrl));
|
|
1220
|
-
const sourcePath = resolve(importerDir, sourceRelativePath);
|
|
1221
|
-
const importerUsesDist = importerDir.split(sep).includes("dist");
|
|
1222
|
-
const targetsSourceTree = /(?:^|\/)\.\.\/src(?:\/|$)|^\.\/*src(?:\/|$)/.test(sourceRelativePath);
|
|
1223
|
-
const resolvedSourcePath = resolveExistingModulePath(sourcePath);
|
|
1224
|
-
if ((!importerUsesDist || !targetsSourceTree) && resolvedSourcePath) return resolvedSourcePath;
|
|
1225
|
-
const [packageJsonError, packageJsonPath] = tryResolveModule(`${packageId}/package.json`);
|
|
1226
|
-
if (!packageJsonError) {
|
|
1227
|
-
const resolvedPackageSourcePath = resolveExistingModulePath(join(dirname(packageJsonPath), "src", sourceRelativePath.replace(/^(\.\.\/)+src\//, "").replace(/^\.\//, "")));
|
|
1228
|
-
if ((!importerUsesDist || !targetsSourceTree) && resolvedPackageSourcePath) return resolvedPackageSourcePath;
|
|
1229
|
-
return join(dirname(packageJsonPath), "dist", distRelativePath);
|
|
1230
|
-
}
|
|
1231
|
-
const [packageError, packagePath] = tryResolveModule(packageId);
|
|
1232
|
-
if (!packageError) return join(dirname(packagePath), distRelativePath);
|
|
1233
|
-
return sourcePath;
|
|
1234
|
-
}
|
|
1235
|
-
//#endregion
|
|
1236
|
-
//#region src/project.ts
|
|
1237
|
-
const sandboxProjectSourceFiles = /* @__PURE__ */ new WeakMap();
|
|
1238
|
-
function getSandboxProjectSourceFiles(project) {
|
|
1239
|
-
return sandboxProjectSourceFiles.get(project) || [];
|
|
1240
|
-
}
|
|
1241
|
-
const maxTimeout = 2147483647;
|
|
1242
|
-
const lockfiles = [
|
|
1243
|
-
{
|
|
1244
|
-
file: "pnpm-lock.yaml",
|
|
1245
|
-
manager: "pnpm"
|
|
1246
|
-
},
|
|
1247
|
-
{
|
|
1248
|
-
file: "package-lock.json",
|
|
1249
|
-
manager: "npm"
|
|
1250
|
-
},
|
|
1251
|
-
{
|
|
1252
|
-
file: "yarn.lock",
|
|
1253
|
-
manager: "yarn"
|
|
1254
|
-
},
|
|
1255
|
-
{
|
|
1256
|
-
file: "bun.lock",
|
|
1257
|
-
manager: "bun"
|
|
1258
|
-
}
|
|
1259
|
-
];
|
|
1260
|
-
const projectFileExcludes = [
|
|
1261
|
-
"node_modules/**",
|
|
1262
|
-
".git/**",
|
|
1263
|
-
"**/.env",
|
|
1264
|
-
"**/.env.*",
|
|
1265
|
-
"**/.npmrc",
|
|
1266
|
-
"bun.lockb"
|
|
1267
|
-
];
|
|
1268
|
-
function isInside(root, path) {
|
|
1269
|
-
const next = relative$1(root, path);
|
|
1270
|
-
return next === "" || !next.startsWith("..") && !next.startsWith("/");
|
|
1271
|
-
}
|
|
1272
|
-
async function isFile(path, root) {
|
|
1273
|
-
if (!await stat(path).then((value) => value.isFile(), () => false)) return false;
|
|
1274
|
-
if (!isInside(root, await realpath(path))) throw new Error(`[vitehub] Sandbox project file escapes its scan root: ${path}`);
|
|
1275
|
-
return true;
|
|
1276
|
-
}
|
|
1277
|
-
function ancestors(start, root) {
|
|
1278
|
-
const paths = [];
|
|
1279
|
-
let current = start;
|
|
1280
|
-
while (isInside(root, current)) {
|
|
1281
|
-
paths.push(current);
|
|
1282
|
-
if (current === root) break;
|
|
1283
|
-
const parent = dirname$1(current);
|
|
1284
|
-
if (parent === current) break;
|
|
1285
|
-
current = parent;
|
|
1286
|
-
}
|
|
1287
|
-
return paths;
|
|
1288
|
-
}
|
|
1289
|
-
function packageManagerFromField(value) {
|
|
1290
|
-
if (typeof value !== "string") return void 0;
|
|
1291
|
-
const name = value.split("@", 1)[0];
|
|
1292
|
-
return name === "pnpm" || name === "npm" || name === "yarn" || name === "bun" ? name : void 0;
|
|
1293
|
-
}
|
|
1294
|
-
function packageManagerMajor(value) {
|
|
1295
|
-
if (typeof value !== "string") return void 0;
|
|
1296
|
-
const version = value.slice(value.indexOf("@") + 1);
|
|
1297
|
-
const major = Number.parseInt(version, 10);
|
|
1298
|
-
return Number.isFinite(major) ? major : void 0;
|
|
1299
|
-
}
|
|
1300
|
-
function installArgs(manager, hasLockfile, declaredMajor) {
|
|
1301
|
-
if (manager === "npm") return hasLockfile ? ["ci"] : ["install"];
|
|
1302
|
-
if (manager === "yarn") return hasLockfile ? ["install", declaredMajor === 1 ? "--frozen-lockfile" : "--immutable"] : ["install"];
|
|
1303
|
-
return hasLockfile ? ["install", "--frozen-lockfile"] : ["install"];
|
|
1304
|
-
}
|
|
1305
|
-
function parseManifest(source, path) {
|
|
1306
|
-
try {
|
|
1307
|
-
return JSON.parse(source);
|
|
1308
|
-
} catch (error) {
|
|
1309
|
-
throw new Error(`[vitehub] Sandbox package manifest is invalid JSON: ${path}`, { cause: error });
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
function isPlainObject(value) {
|
|
1313
|
-
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
1314
|
-
}
|
|
1315
|
-
function parseSandboxProjectOptions(manifest, path) {
|
|
1316
|
-
if (typeof manifest.vitehub === "undefined") return void 0;
|
|
1317
|
-
if (!isPlainObject(manifest.vitehub)) throw new Error(`[vitehub] Sandbox package manifest "vitehub" must be an object: ${path}`);
|
|
1318
|
-
const sandbox = manifest.vitehub.sandbox;
|
|
1319
|
-
if (typeof sandbox === "undefined") return void 0;
|
|
1320
|
-
if (!isPlainObject(sandbox)) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox" must be an object: ${path}`);
|
|
1321
|
-
const unsupported = Object.keys(sandbox).filter((key) => key !== "timeout");
|
|
1322
|
-
if (unsupported.length) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox" has unsupported keys: ${unsupported.join(", ")}.`);
|
|
1323
|
-
const timeout = sandbox.timeout;
|
|
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);
|
|
1338
|
-
}
|
|
1339
|
-
function parsePnpmWorkspacePackages(source) {
|
|
1340
|
-
const patterns = [];
|
|
1341
|
-
let packagesIndent;
|
|
1342
|
-
for (const line of source.split(/\r?\n/)) {
|
|
1343
|
-
if (packagesIndent === void 0) {
|
|
1344
|
-
const inline = /^\s*packages\s*:\s*\[(.*)\]\s*(?:#.*)?$/.exec(line);
|
|
1345
|
-
if (inline) return inline[1].split(",").map((value) => value.trim().replace(/^(['"])(.*)\1$/, "$2")).filter(Boolean);
|
|
1346
|
-
const match = /^(\s*)packages\s*:\s*(?:#.*)?$/.exec(line);
|
|
1347
|
-
if (match) packagesIndent = match[1].length;
|
|
1348
|
-
continue;
|
|
1349
|
-
}
|
|
1350
|
-
if (!line.trim() || /^\s*#/.test(line)) continue;
|
|
1351
|
-
if ((/^\s*/.exec(line)?.[0].length || 0) <= packagesIndent) break;
|
|
1352
|
-
const item = /^\s*-\s*(.+?)\s*$/.exec(line)?.[1];
|
|
1353
|
-
if (!item) continue;
|
|
1354
|
-
const value = item.replace(/\s+#.*$/, "").trim().replace(/^(['"])(.*)\1$/, "$2");
|
|
1355
|
-
if (value) patterns.push(value.replaceAll("\\", "/").replace(/\/$/, ""));
|
|
1356
|
-
}
|
|
1357
|
-
return patterns;
|
|
1358
|
-
}
|
|
1359
|
-
function isWorkspacePackage(path, patterns) {
|
|
1360
|
-
return patterns.filter((pattern) => !pattern.startsWith("!")).some((pattern) => matchesGlob(path, pattern)) && !patterns.filter((pattern) => pattern.startsWith("!")).some((pattern) => matchesGlob(path, pattern.slice(1)));
|
|
1361
|
-
}
|
|
1362
|
-
async function findPnpmWorkspaceRoot(packageRoot, root) {
|
|
1363
|
-
for (const directory of ancestors(packageRoot, root)) {
|
|
1364
|
-
const file = resolve$1(directory, "pnpm-workspace.yaml");
|
|
1365
|
-
if (!await isFile(file, root)) continue;
|
|
1366
|
-
const source = await readFile(file, "utf8");
|
|
1367
|
-
const packagePath = relative$1(directory, packageRoot).replaceAll("\\", "/") || ".";
|
|
1368
|
-
if (directory === packageRoot || isWorkspacePackage(packagePath, parsePnpmWorkspacePackages(source))) return {
|
|
1369
|
-
directory,
|
|
1370
|
-
file,
|
|
1371
|
-
source
|
|
1372
|
-
};
|
|
1373
|
-
}
|
|
1374
|
-
}
|
|
1375
|
-
async function addProjectFile(files, installRoot, path, scanRoot) {
|
|
1376
|
-
if (!await isFile(path, scanRoot)) return;
|
|
1377
|
-
const mode = (await stat(path)).mode & 511;
|
|
1378
|
-
files[relative$1(installRoot, path).replaceAll("\\", "/")] = {
|
|
1379
|
-
contents: (await readFile(path)).toString("base64"),
|
|
1380
|
-
encoding: "base64",
|
|
1381
|
-
...mode & 73 ? { mode } : {}
|
|
1382
|
-
};
|
|
1383
|
-
}
|
|
1384
|
-
function workspaceDependencyNames(manifest) {
|
|
1385
|
-
const sections = [
|
|
1386
|
-
manifest.dependencies,
|
|
1387
|
-
manifest.devDependencies,
|
|
1388
|
-
manifest.optionalDependencies,
|
|
1389
|
-
manifest.peerDependencies
|
|
1390
|
-
];
|
|
1391
|
-
return [...new Set(sections.flatMap((section) => Object.entries(section || {})).filter(([, specifier]) => specifier.startsWith("workspace:")).map(([name]) => name))];
|
|
1392
|
-
}
|
|
1393
|
-
async function addPnpmWorkspaceDependencies(files, workspaceRoot, scanRoot, patterns, selectedManifest) {
|
|
1394
|
-
const packages = /* @__PURE__ */ new Map();
|
|
1395
|
-
for (const pattern of patterns.filter((pattern) => !pattern.startsWith("!"))) for await (const match of glob(`${pattern}/package.json`, {
|
|
1396
|
-
cwd: workspaceRoot,
|
|
1397
|
-
exclude: ["**/node_modules/**", "**/.git/**"]
|
|
1398
|
-
})) {
|
|
1399
|
-
const manifestPath = resolve$1(workspaceRoot, match);
|
|
1400
|
-
if (!await isFile(manifestPath, scanRoot)) continue;
|
|
1401
|
-
if (!isWorkspacePackage(relative$1(workspaceRoot, dirname$1(manifestPath)).replaceAll("\\", "/") || ".", patterns)) continue;
|
|
1402
|
-
const manifest = parseManifest(await readFile(manifestPath, "utf8"), manifestPath);
|
|
1403
|
-
if (manifest.name) packages.set(manifest.name, {
|
|
1404
|
-
manifest,
|
|
1405
|
-
root: dirname$1(manifestPath)
|
|
1406
|
-
});
|
|
1407
|
-
}
|
|
1408
|
-
const pending = workspaceDependencyNames(selectedManifest);
|
|
1409
|
-
const included = /* @__PURE__ */ new Set();
|
|
1410
|
-
while (pending.length) {
|
|
1411
|
-
const name = pending.shift();
|
|
1412
|
-
if (included.has(name)) continue;
|
|
1413
|
-
const dependency = packages.get(name);
|
|
1414
|
-
if (!dependency) throw new Error(`[vitehub] Sandbox package references missing pnpm workspace dependency "${name}".`);
|
|
1415
|
-
included.add(name);
|
|
1416
|
-
pending.push(...workspaceDependencyNames(dependency.manifest));
|
|
1417
|
-
for await (const match of glob("**/*", {
|
|
1418
|
-
cwd: dependency.root,
|
|
1419
|
-
exclude: projectFileExcludes
|
|
1420
|
-
})) await addProjectFile(files, workspaceRoot, resolve$1(dependency.root, match), scanRoot);
|
|
1421
|
-
}
|
|
1422
|
-
}
|
|
1423
|
-
async function resolveSandboxProject(definitionFile, scanRoot, options = {}) {
|
|
1424
|
-
const root = await realpath(resolve$1(scanRoot));
|
|
1425
|
-
const definition = await realpath(resolve$1(definitionFile));
|
|
1426
|
-
if (!isInside(root, definition)) throw new Error(`[vitehub] Sandbox Definition is outside its scan root: ${definitionFile}`);
|
|
1427
|
-
const packageRoot = await firstDirectoryWithFile(ancestors(dirname$1(definition), root), "package.json", root);
|
|
1428
|
-
if (!packageRoot) throw new Error(`[vitehub] Sandbox Definition "${definitionFile}" requires a package.json between its directory and "${root}".`);
|
|
1429
|
-
const manifestPath = resolve$1(packageRoot, "package.json");
|
|
1430
|
-
const manifest = parseManifest(await readFile(manifestPath, "utf8"), manifestPath);
|
|
1431
|
-
const sandboxOptions = options.readSandboxOptions ? parseSandboxProjectOptions(manifest, manifestPath) : void 0;
|
|
1432
|
-
const declaredManager = packageManagerFromField(manifest.packageManager);
|
|
1433
|
-
const declaredMajor = packageManagerMajor(manifest.packageManager);
|
|
1434
|
-
const workspace = declaredManager && declaredManager !== "pnpm" ? void 0 : await findPnpmWorkspaceRoot(packageRoot, root);
|
|
1435
|
-
const installRoot = workspace?.directory || packageRoot;
|
|
1436
|
-
const packageLock = await findLockfile([installRoot], root, workspace ? "pnpm" : declaredManager);
|
|
1437
|
-
const manager = declaredManager || packageLock?.manager || (workspace ? "pnpm" : "npm");
|
|
1438
|
-
const lock = packageLock?.manager === manager ? packageLock : void 0;
|
|
1439
|
-
const lockfileMajor = manager === "yarn" && lock && declaredMajor === void 0 ? (await readFile(lock.path, "utf8")).includes("__metadata:") ? 2 : 1 : void 0;
|
|
1440
|
-
const files = {};
|
|
1441
|
-
for await (const match of glob("**/*", {
|
|
1442
|
-
cwd: packageRoot,
|
|
1443
|
-
exclude: projectFileExcludes
|
|
1444
|
-
})) await addProjectFile(files, installRoot, resolve$1(packageRoot, match), root);
|
|
1445
|
-
if (installRoot !== packageRoot) await addProjectFile(files, installRoot, resolve$1(installRoot, "package.json"), root);
|
|
1446
|
-
if (workspace) {
|
|
1447
|
-
await addProjectFile(files, installRoot, workspace.file, root);
|
|
1448
|
-
await addPnpmWorkspaceDependencies(files, installRoot, root, parsePnpmWorkspacePackages(workspace.source), manifest);
|
|
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
|
-
}
|
|
1460
|
-
if (lock) await addProjectFile(files, installRoot, lock.path, root);
|
|
1461
|
-
const packagePath = relative$1(installRoot, packageRoot).replaceAll("\\", "/") || ".";
|
|
1462
|
-
const identity = JSON.stringify({
|
|
1463
|
-
files,
|
|
1464
|
-
manager,
|
|
1465
|
-
packagePath
|
|
1466
|
-
});
|
|
1467
|
-
const project = {
|
|
1468
|
-
digest: createHash("sha256").update(identity).digest("hex"),
|
|
1469
|
-
files,
|
|
1470
|
-
install: {
|
|
1471
|
-
args: installArgs(manager, Boolean(lock), declaredManager === manager ? declaredMajor : lockfileMajor),
|
|
1472
|
-
command: manager,
|
|
1473
|
-
cwd: "."
|
|
1474
|
-
},
|
|
1475
|
-
...sandboxOptions ? { options: sandboxOptions } : {},
|
|
1476
|
-
packagePath
|
|
1477
|
-
};
|
|
1478
|
-
sandboxProjectSourceFiles.set(project, Object.keys(files).map((path) => resolve$1(installRoot, path)));
|
|
1479
|
-
return project;
|
|
1480
|
-
}
|
|
1481
|
-
async function firstDirectoryWithFile(directories, file, root) {
|
|
1482
|
-
for (const directory of directories) if (await isFile(resolve$1(directory, file), root)) return directory;
|
|
1483
|
-
}
|
|
1484
|
-
async function findLockfile(directories, root, manager) {
|
|
1485
|
-
const candidates = manager ? lockfiles.filter((lock) => lock.manager === manager) : lockfiles;
|
|
1486
|
-
for (const directory of directories) for (const candidate of candidates) {
|
|
1487
|
-
const path = resolve$1(directory, candidate.file);
|
|
1488
|
-
if (await isFile(path, root)) return {
|
|
1489
|
-
directory,
|
|
1490
|
-
manager: candidate.manager,
|
|
1491
|
-
path
|
|
1492
|
-
};
|
|
1493
|
-
}
|
|
1494
|
-
}
|
|
1495
|
-
//#endregion
|
|
1496
|
-
//#region src/internal/package-entry.ts
|
|
1497
|
-
const typescript = createRequire(import.meta.url)("typescript");
|
|
1498
|
-
const runtimeExportConditions = new Set([
|
|
1499
|
-
"default",
|
|
1500
|
-
"import",
|
|
1501
|
-
"module-sync",
|
|
1502
|
-
"node",
|
|
1503
|
-
"node-addons"
|
|
1504
|
-
]);
|
|
1505
|
-
function isExecutableTypeScriptModule(path) {
|
|
1506
|
-
return /\.(?:ts|mts)$/.test(path) && !/\.d\.(?:ts|mts)$/.test(path);
|
|
1507
|
-
}
|
|
1508
|
-
function executablePackageModulePath(path) {
|
|
1509
|
-
const suffixIndex = path.search(/[?#]/);
|
|
1510
|
-
const modulePath = suffixIndex === -1 ? path : path.slice(0, suffixIndex);
|
|
1511
|
-
const suffix = suffixIndex === -1 ? "" : path.slice(suffixIndex);
|
|
1512
|
-
return isExecutableTypeScriptModule(modulePath) ? `${modulePath}.mjs${suffix}` : path;
|
|
1513
|
-
}
|
|
1514
|
-
function projectFileSource(project, path) {
|
|
1515
|
-
const file = project.files[path];
|
|
1516
|
-
if (!file) throw new Error(`[vitehub] Sandbox package project is missing required file: ${path}`);
|
|
1517
|
-
return Buffer.from(file.contents, file.encoding).toString();
|
|
1518
|
-
}
|
|
1519
|
-
function parseRuntimeManifest(project, path) {
|
|
1520
|
-
try {
|
|
1521
|
-
return JSON.parse(projectFileSource(project, path));
|
|
1522
|
-
} catch (error) {
|
|
1523
|
-
throw new Error(`[vitehub] Sandbox package manifest is invalid JSON: ${path}`, { cause: error });
|
|
1524
|
-
}
|
|
1525
|
-
}
|
|
1526
|
-
function selectedPackageManifest(project) {
|
|
1527
|
-
const path = project.packagePath === "." ? "package.json" : `${project.packagePath}/package.json`;
|
|
1528
|
-
const manifest = parseRuntimeManifest(project, path);
|
|
1529
|
-
if (manifest.type !== "module") throw new Error(`[vitehub] Sandbox package manifest "${path}" must set "type" to "module". Canonical Sandbox package entrypoints are ESM.`);
|
|
1530
|
-
return manifest;
|
|
1531
|
-
}
|
|
1532
|
-
function declaredWorkspaceDependencyNames(manifest) {
|
|
1533
|
-
return [...new Set([
|
|
1534
|
-
manifest.dependencies,
|
|
1535
|
-
manifest.devDependencies,
|
|
1536
|
-
manifest.optionalDependencies,
|
|
1537
|
-
manifest.peerDependencies
|
|
1538
|
-
].flatMap((section) => Object.entries(section || {})).filter(([, specifier]) => specifier.startsWith("workspace:")).map(([name]) => name))];
|
|
1539
|
-
}
|
|
1540
|
-
function runtimeExportTargets(value, patternMatch, allowPackageTarget = false) {
|
|
1541
|
-
if (typeof value === "string") {
|
|
1542
|
-
const target = patternMatch === void 0 ? value : value.replaceAll("*", patternMatch);
|
|
1543
|
-
return target.startsWith("./") || allowPackageTarget ? [target] : [];
|
|
1544
|
-
}
|
|
1545
|
-
if (Array.isArray(value)) {
|
|
1546
|
-
for (const target of value) {
|
|
1547
|
-
const targets = runtimeExportTargets(target, patternMatch, allowPackageTarget);
|
|
1548
|
-
if (targets.length) return targets;
|
|
1549
|
-
}
|
|
1550
|
-
return [];
|
|
1551
|
-
}
|
|
1552
|
-
if (!value || typeof value !== "object") return [];
|
|
1553
|
-
for (const [condition, target] of Object.entries(value)) if (runtimeExportConditions.has(condition)) {
|
|
1554
|
-
const targets = runtimeExportTargets(target, patternMatch, allowPackageTarget);
|
|
1555
|
-
if (targets.length) return targets;
|
|
1556
|
-
}
|
|
1557
|
-
return [];
|
|
1558
|
-
}
|
|
1559
|
-
function runtimeTargetsForPackageSpecifier(manifest, packageName, specifier) {
|
|
1560
|
-
if (manifest.exports !== void 0) {
|
|
1561
|
-
let selected = manifest.exports;
|
|
1562
|
-
let patternMatch;
|
|
1563
|
-
if (selected && typeof selected === "object" && !Array.isArray(selected)) {
|
|
1564
|
-
const entries = selected;
|
|
1565
|
-
if (Object.keys(entries).some((key) => key.startsWith("."))) {
|
|
1566
|
-
const subpath = specifier === packageName ? "." : `.${specifier.slice(packageName.length)}`;
|
|
1567
|
-
if (Object.hasOwn(entries, subpath)) selected = entries[subpath];
|
|
1568
|
-
else {
|
|
1569
|
-
const pattern = Object.keys(entries).filter((key) => {
|
|
1570
|
-
const star = key.indexOf("*");
|
|
1571
|
-
if (star === -1) return false;
|
|
1572
|
-
return subpath.startsWith(key.slice(0, star)) && subpath.endsWith(key.slice(star + 1));
|
|
1573
|
-
}).sort((left, right) => {
|
|
1574
|
-
const leftStar = left.indexOf("*");
|
|
1575
|
-
return right.indexOf("*") - leftStar || right.length - left.length;
|
|
1576
|
-
})[0];
|
|
1577
|
-
if (pattern) {
|
|
1578
|
-
const star = pattern.indexOf("*");
|
|
1579
|
-
patternMatch = subpath.slice(star, subpath.length - (pattern.length - star - 1));
|
|
1580
|
-
selected = entries[pattern];
|
|
1581
|
-
} else selected = void 0;
|
|
1582
|
-
}
|
|
1583
|
-
} else if (specifier !== packageName) selected = void 0;
|
|
1584
|
-
} else if (specifier !== packageName) selected = void 0;
|
|
1585
|
-
return runtimeExportTargets(selected, patternMatch);
|
|
1586
|
-
}
|
|
1587
|
-
if (specifier !== packageName) return [`.${specifier.slice(packageName.length)}`];
|
|
1588
|
-
return typeof manifest.main === "string" ? [manifest.main] : ["./index.js"];
|
|
1589
|
-
}
|
|
1590
|
-
function runtimeTargetsForPackageImport(manifest, specifier) {
|
|
1591
|
-
if (!manifest.imports || typeof manifest.imports !== "object" || Array.isArray(manifest.imports)) return [];
|
|
1592
|
-
const entries = manifest.imports;
|
|
1593
|
-
let selected = entries[specifier];
|
|
1594
|
-
let patternMatch;
|
|
1595
|
-
if (selected === void 0) {
|
|
1596
|
-
const pattern = Object.keys(entries).filter((key) => {
|
|
1597
|
-
const star = key.indexOf("*");
|
|
1598
|
-
if (star === -1) return false;
|
|
1599
|
-
return specifier.startsWith(key.slice(0, star)) && specifier.endsWith(key.slice(star + 1));
|
|
1600
|
-
}).sort((left, right) => {
|
|
1601
|
-
const leftStar = left.indexOf("*");
|
|
1602
|
-
return right.indexOf("*") - leftStar || right.length - left.length;
|
|
1603
|
-
})[0];
|
|
1604
|
-
if (!pattern) return [];
|
|
1605
|
-
const star = pattern.indexOf("*");
|
|
1606
|
-
patternMatch = specifier.slice(star, specifier.length - (pattern.length - star - 1));
|
|
1607
|
-
selected = entries[pattern];
|
|
1608
|
-
}
|
|
1609
|
-
return runtimeExportTargets(selected, patternMatch, true);
|
|
1610
|
-
}
|
|
1611
|
-
function isTypeScriptRuntimeTarget(path) {
|
|
1612
|
-
const target = path.replace(/[?#].*$/, "");
|
|
1613
|
-
return /\.[cm]?tsx?$/.test(target) && !/\.d\.[cm]?ts$/.test(target);
|
|
1614
|
-
}
|
|
1615
|
-
function validateWorkspaceJavaScriptGraph(project, packageName, manifest, manifestPath, targets) {
|
|
1616
|
-
const pending = targets.filter((target) => /\.(?:js|mjs)$/.test(target.replace(/[?#].*$/, ""))).map((target) => normalize$1(join$1(dirname$2(manifestPath), target.replace(/[?#].*$/, ""))));
|
|
1617
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1618
|
-
const runtimePackages = /* @__PURE__ */ new Set();
|
|
1619
|
-
while (pending.length) {
|
|
1620
|
-
const path = pending.shift();
|
|
1621
|
-
if (visited.has(path) || !Object.hasOwn(project.files, path)) continue;
|
|
1622
|
-
visited.add(path);
|
|
1623
|
-
const source = projectFileSource(project, path);
|
|
1624
|
-
for (const specifier of findRuntimeModuleSpecifiers(source, path)) {
|
|
1625
|
-
if (specifier.startsWith("#")) {
|
|
1626
|
-
for (const aliasTarget of runtimeTargetsForPackageImport(manifest, specifier)) {
|
|
1627
|
-
if (!/^\.\.?\//.test(aliasTarget)) {
|
|
1628
|
-
runtimePackages.add(aliasTarget);
|
|
1629
|
-
continue;
|
|
1630
|
-
}
|
|
1631
|
-
const target = normalize$1(join$1(dirname$2(manifestPath), aliasTarget.replace(/[?#].*$/, "")));
|
|
1632
|
-
if (isTypeScriptRuntimeTarget(target)) throw new Error(`[vitehub] Sandbox workspace dependency "${packageName}" exposes TypeScript runtime target "${aliasTarget}" through package import "${specifier}". Build dependencies to JavaScript before Sandbox execution.`);
|
|
1633
|
-
if (/\.(?:js|mjs)$/.test(target)) pending.push(target);
|
|
1634
|
-
}
|
|
1635
|
-
continue;
|
|
1636
|
-
}
|
|
1637
|
-
if (!/^\.\.?\//.test(specifier)) {
|
|
1638
|
-
if (!specifier.startsWith("node:")) runtimePackages.add(specifier);
|
|
1639
|
-
continue;
|
|
1640
|
-
}
|
|
1641
|
-
const target = normalize$1(join$1(dirname$2(path), specifier.replace(/[?#].*$/, "")));
|
|
1642
|
-
if (isTypeScriptRuntimeTarget(target)) throw new Error(`[vitehub] Sandbox workspace dependency "${packageName}" exposes TypeScript runtime target "${specifier}" from "${path}". Build dependencies to JavaScript before Sandbox execution.`);
|
|
1643
|
-
if (/\.(?:js|mjs)$/.test(target)) pending.push(target);
|
|
1644
|
-
}
|
|
1645
|
-
}
|
|
1646
|
-
return runtimePackages;
|
|
1647
|
-
}
|
|
1648
|
-
function validateWorkspaceRuntimeExports(project, runtimePackages, declaredWorkspacePackages) {
|
|
1649
|
-
const pending = [...runtimePackages];
|
|
1650
|
-
if (!pending.length) return;
|
|
1651
|
-
const workspacePackages = new Set(declaredWorkspacePackages);
|
|
1652
|
-
if (!workspacePackages.size) return;
|
|
1653
|
-
const workspaceFile = project.files["pnpm-workspace.yaml"];
|
|
1654
|
-
if (!workspaceFile) return;
|
|
1655
|
-
const workspacePatterns = parsePnpmWorkspacePackages(Buffer.from(workspaceFile.contents, workspaceFile.encoding).toString());
|
|
1656
|
-
const manifests = /* @__PURE__ */ new Map();
|
|
1657
|
-
for (const path of Object.keys(project.files).filter((path) => path === "package.json" || path.endsWith("/package.json") && isWorkspacePackage(dirname$2(path), workspacePatterns))) {
|
|
1658
|
-
let manifest;
|
|
1659
|
-
try {
|
|
1660
|
-
const value = JSON.parse(projectFileSource(project, path));
|
|
1661
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) continue;
|
|
1662
|
-
manifest = value;
|
|
1663
|
-
} catch {
|
|
1664
|
-
continue;
|
|
1665
|
-
}
|
|
1666
|
-
if (typeof manifest.name === "string") manifests.set(manifest.name, {
|
|
1667
|
-
manifest,
|
|
1668
|
-
path
|
|
1669
|
-
});
|
|
1670
|
-
}
|
|
1671
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1672
|
-
while (pending.length) {
|
|
1673
|
-
const specifier = pending.shift();
|
|
1674
|
-
if (visited.has(specifier)) continue;
|
|
1675
|
-
visited.add(specifier);
|
|
1676
|
-
const packageName = barePackageName(specifier);
|
|
1677
|
-
if (!workspacePackages.has(packageName)) continue;
|
|
1678
|
-
const dependency = manifests.get(packageName);
|
|
1679
|
-
if (!dependency) continue;
|
|
1680
|
-
const targets = runtimeTargetsForPackageSpecifier(dependency.manifest, packageName, specifier);
|
|
1681
|
-
const target = targets.find(isTypeScriptRuntimeTarget);
|
|
1682
|
-
if (target) throw new Error(`[vitehub] Sandbox workspace dependency "${packageName}" exposes TypeScript runtime target "${target}" in "${dependency.path}". Build dependencies to JavaScript before Sandbox execution.`);
|
|
1683
|
-
const runtimePackageEdges = validateWorkspaceJavaScriptGraph(project, packageName, dependency.manifest, dependency.path, targets);
|
|
1684
|
-
for (const name of declaredWorkspaceDependencyNames(dependency.manifest)) workspacePackages.add(name);
|
|
1685
|
-
pending.push(...runtimePackageEdges);
|
|
1686
|
-
}
|
|
1687
|
-
}
|
|
1688
|
-
function isInsideSelectedPackage(project, path) {
|
|
1689
|
-
if (project.packagePath === ".") return path !== ".." && !path.startsWith("../");
|
|
1690
|
-
return path.startsWith(`${project.packagePath}/`);
|
|
1691
|
-
}
|
|
1692
|
-
function removeTypeOnlyModuleDeclarations(context) {
|
|
1693
|
-
return (sourceFile) => context.factory.updateSourceFile(sourceFile, sourceFile.statements.filter((statement) => {
|
|
1694
|
-
if (typescript.isImportDeclaration(statement)) {
|
|
1695
|
-
const clause = statement.importClause;
|
|
1696
|
-
const bindings = clause?.namedBindings;
|
|
1697
|
-
return !(clause && !clause.name && bindings && typescript.isNamedImports(bindings) && bindings.elements.length > 0 && bindings.elements.every((element) => element.isTypeOnly));
|
|
1698
|
-
}
|
|
1699
|
-
if (typescript.isExportDeclaration(statement)) {
|
|
1700
|
-
const clause = statement.exportClause;
|
|
1701
|
-
return !(clause && typescript.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly));
|
|
1702
|
-
}
|
|
1703
|
-
return true;
|
|
1704
|
-
}));
|
|
1705
|
-
}
|
|
1706
|
-
function transpilePackageModule(source, path) {
|
|
1707
|
-
const result = typescript.transpileModule(source, {
|
|
1708
|
-
compilerOptions: {
|
|
1709
|
-
module: typescript.ModuleKind.ESNext,
|
|
1710
|
-
target: typescript.ScriptTarget.ES2022,
|
|
1711
|
-
verbatimModuleSyntax: true
|
|
1712
|
-
},
|
|
1713
|
-
fileName: path,
|
|
1714
|
-
reportDiagnostics: true,
|
|
1715
|
-
transformers: { before: [removeTypeOnlyModuleDeclarations] }
|
|
1716
|
-
});
|
|
1717
|
-
const errors = result.diagnostics?.filter((diagnostic) => diagnostic.category === typescript.DiagnosticCategory.Error) || [];
|
|
1718
|
-
if (errors.length) {
|
|
1719
|
-
const details = errors.map((diagnostic) => typescript.flattenDiagnosticMessageText(diagnostic.messageText, "\n")).join("\n");
|
|
1720
|
-
throw new Error(`[vitehub] Sandbox package module "${path}" could not be transpiled:\n${details}`);
|
|
1721
|
-
}
|
|
1722
|
-
return result.outputText;
|
|
1723
|
-
}
|
|
1724
|
-
function barePackageName(specifier) {
|
|
1725
|
-
const [scopeOrName, name] = specifier.split("/");
|
|
1726
|
-
return scopeOrName.startsWith("@") && name ? `${scopeOrName}/${name}` : scopeOrName;
|
|
1727
|
-
}
|
|
1728
|
-
function isUnsupportedExternalModuleSpecifier(specifier) {
|
|
1729
|
-
return specifier.startsWith("/") || specifier.startsWith("\\") || /^[A-Za-z][A-Za-z\d+.-]*:/.test(specifier) && !specifier.startsWith("node:");
|
|
1730
|
-
}
|
|
1731
|
-
function throwCommonJSSyntax(path, commonJS) {
|
|
1732
|
-
const syntax = {
|
|
1733
|
-
"exports-assignment": "exports assignment",
|
|
1734
|
-
"exports-reference": "exports reference",
|
|
1735
|
-
"import-equals": "import = require()",
|
|
1736
|
-
"module-exports-assignment": "module.exports assignment",
|
|
1737
|
-
"module-reference": "module reference",
|
|
1738
|
-
require: "require()",
|
|
1739
|
-
"require-property": commonJS.specifier ? `require.${commonJS.specifier}` : "require property access"
|
|
1740
|
-
}[commonJS.syntax];
|
|
1741
|
-
const target = commonJS.specifier && commonJS.syntax !== "require-property" ? ` for "${commonJS.specifier}"` : "";
|
|
1742
|
-
throw new Error(`[vitehub] Sandbox package module "${path}" uses CommonJS ${syntax}${target}. Canonical Sandbox package entrypoints are ESM; use import or export syntax.`);
|
|
1743
|
-
}
|
|
1744
|
-
function validatePackageModuleSpecifiers(project, entry, packageName) {
|
|
1745
|
-
const pending = [entry];
|
|
1746
|
-
const runtimePackages = /* @__PURE__ */ new Set();
|
|
1747
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1748
|
-
while (pending.length) {
|
|
1749
|
-
const path = pending.shift();
|
|
1750
|
-
if (visited.has(path)) continue;
|
|
1751
|
-
visited.add(path);
|
|
1752
|
-
const source = projectFileSource(project, path);
|
|
1753
|
-
if (hasNonLiteralDynamicImport(source, path)) throw new Error(`[vitehub] Sandbox package module "${path}" uses a non-literal dynamic import. Canonical Sandbox package entrypoints require literal import() specifiers.`);
|
|
1754
|
-
const importEquals = findCommonJSImportEqualsSpecifiers(source, path)[0];
|
|
1755
|
-
if (importEquals) throwCommonJSSyntax(path, importEquals);
|
|
1756
|
-
const moduleSpecifiers = findRuntimeModuleSpecifiers(source, path);
|
|
1757
|
-
for (const specifier of moduleSpecifiers) {
|
|
1758
|
-
if (specifier.startsWith("#")) throw new Error(`[vitehub] Sandbox package module "${path}" imports package alias "${specifier}". Use an explicit relative ESM import for local Sandbox source.`);
|
|
1759
|
-
if (packageName && (specifier === packageName || specifier.startsWith(`${packageName}/`))) throw new Error(`[vitehub] Sandbox package module "${path}" self-imports "${specifier}". Use an explicit relative ESM import for local Sandbox source.`);
|
|
1760
|
-
if (isUnsupportedExternalModuleSpecifier(specifier)) throw new Error(`[vitehub] Sandbox package module "${path}" imports absolute or URL module "${specifier}". Use a relative module inside the package or a runtime-ready package dependency.`);
|
|
1761
|
-
if (!/^\.\.?\//.test(specifier) && !specifier.startsWith("node:")) runtimePackages.add(specifier);
|
|
1762
|
-
}
|
|
1763
|
-
for (const specifier of moduleSpecifiers.filter((specifier) => /^\.\.?\//.test(specifier))) {
|
|
1764
|
-
const target = normalize$1(join$1(dirname$2(path), specifier.replace(/[?#].*$/, "")));
|
|
1765
|
-
if (!isInsideSelectedPackage(project, target)) throw new Error(`[vitehub] Sandbox package module "${path}" imports "${specifier}" outside its package. Declare runtime-ready JavaScript as a package dependency instead.`);
|
|
1766
|
-
if (!Object.hasOwn(project.files, target)) throw new Error(`[vitehub] Sandbox package module "${path}" imports "${specifier}", which is not an executable package file. Use an explicit extension that resolves to a package file.`);
|
|
1767
|
-
if (/\.(?:cjs|cts)$/.test(target)) throw new Error(`[vitehub] Sandbox package module "${path}" imports CommonJS module "${specifier}". Canonical Sandbox package source must use ESM JavaScript or TypeScript modules.`);
|
|
1768
|
-
if (/\.[cm]?[jt]sx$/.test(target)) throw new Error(`[vitehub] Sandbox package module "${path}" imports JSX module "${specifier}". Canonical Sandbox package source does not compile JSX.`);
|
|
1769
|
-
if (/\.d\.[cm]?ts$/.test(target)) throw new Error(`[vitehub] Sandbox package module "${path}" imports declaration file "${specifier}" at runtime. Use an import type declaration instead.`);
|
|
1770
|
-
if (/\.(?:js|mjs|ts|mts)$/.test(target)) pending.push(target);
|
|
1771
|
-
}
|
|
1772
|
-
}
|
|
1773
|
-
return {
|
|
1774
|
-
modulePaths: visited,
|
|
1775
|
-
runtimePackages
|
|
1776
|
-
};
|
|
1777
|
-
}
|
|
1778
|
-
function prepareExecutablePackageProject(project, entry) {
|
|
1779
|
-
const manifest = selectedPackageManifest(project);
|
|
1780
|
-
const { modulePaths, runtimePackages } = validatePackageModuleSpecifiers(project, entry, typeof manifest.name === "string" ? manifest.name : void 0);
|
|
1781
|
-
validateWorkspaceRuntimeExports(project, runtimePackages, declaredWorkspaceDependencyNames(manifest));
|
|
1782
|
-
const generatedFiles = {};
|
|
1783
|
-
const executableSources = /* @__PURE__ */ new Map();
|
|
1784
|
-
const originalPaths = /* @__PURE__ */ new Map();
|
|
1785
|
-
const files = { ...project.files };
|
|
1786
|
-
for (const path of modulePaths) {
|
|
1787
|
-
const file = project.files[path];
|
|
1788
|
-
const source = Buffer.from(file.contents, file.encoding).toString();
|
|
1789
|
-
const rewritten = rewriteRuntimeRelativeModuleSpecifiers(source, path, executablePackageModulePath);
|
|
1790
|
-
if (isExecutableTypeScriptModule(path)) {
|
|
1791
|
-
const executablePath = executablePackageModulePath(path);
|
|
1792
|
-
if (Object.hasOwn(project.files, executablePath)) throw new Error(`[vitehub] Sandbox package module "${path}" conflicts with generated executable "${executablePath}". Rename the existing file.`);
|
|
1793
|
-
const executableSource = transpilePackageModule(rewritten, path);
|
|
1794
|
-
executableSources.set(executablePath, executableSource);
|
|
1795
|
-
originalPaths.set(executablePath, path);
|
|
1796
|
-
generatedFiles[executablePath] = {
|
|
1797
|
-
contents: Buffer.from(executableSource).toString("base64"),
|
|
1798
|
-
encoding: "base64"
|
|
1799
|
-
};
|
|
1800
|
-
} else {
|
|
1801
|
-
executableSources.set(path, rewritten);
|
|
1802
|
-
originalPaths.set(path, path);
|
|
1803
|
-
if (rewritten !== source) generatedFiles[path] = {
|
|
1804
|
-
...file,
|
|
1805
|
-
contents: Buffer.from(rewritten).toString("base64")
|
|
1806
|
-
};
|
|
1807
|
-
}
|
|
1808
|
-
}
|
|
1809
|
-
const commonJS = findExecutableCommonJSModuleSpecifiers(executableSources)[0];
|
|
1810
|
-
if (commonJS) throwCommonJSSyntax(originalPaths.get(commonJS.path) || commonJS.path, commonJS);
|
|
1811
|
-
if (!Object.keys(generatedFiles).length) return {
|
|
1812
|
-
entry,
|
|
1813
|
-
project
|
|
1814
|
-
};
|
|
1815
|
-
Object.assign(files, generatedFiles);
|
|
1816
|
-
const digest = createHash("sha256").update(JSON.stringify({
|
|
1817
|
-
generatedFiles,
|
|
1818
|
-
project: project.digest
|
|
1819
|
-
})).digest("hex");
|
|
1820
|
-
return {
|
|
1821
|
-
entry: executablePackageModulePath(entry),
|
|
1822
|
-
project: {
|
|
1823
|
-
...project,
|
|
1824
|
-
digest,
|
|
1825
|
-
files
|
|
1826
|
-
}
|
|
1827
|
-
};
|
|
1828
|
-
}
|
|
1829
|
-
//#endregion
|
|
1830
|
-
//#region src/bundle.ts
|
|
1831
|
-
const SHIM_NAMESPACE = "vitehub-sandbox-runtime-shim";
|
|
1832
|
-
const builtinModuleSet$1 = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
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
|
-
}
|
|
1863
|
-
async function bundleSandboxDefinition(source, file, options = {}) {
|
|
1864
|
-
if (options.includeProject === true && !options.project) throw new Error(`[vitehub] Sandbox Definition ${file} declares project: true but no project was resolved.`);
|
|
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)}`);
|
|
1868
|
-
return {
|
|
1869
|
-
entry: executable.entry,
|
|
1870
|
-
execution: "module",
|
|
1871
|
-
modules: {},
|
|
1872
|
-
project: executable.project
|
|
1873
|
-
};
|
|
1874
|
-
}
|
|
1875
|
-
const { externalImports, hasRuntimeModuleResolution, ...bundle } = await bundleDiscoveredDefinitionModuleGraph({
|
|
1876
|
-
alias: options.alias,
|
|
1877
|
-
filename: file,
|
|
1878
|
-
packages: project ? "external" : "bundle",
|
|
1879
|
-
source,
|
|
1880
|
-
plugins: [{
|
|
1881
|
-
name: SHIM_NAMESPACE,
|
|
1882
|
-
setup(pluginBuild) {
|
|
1883
|
-
pluginBuild.onResolve({ filter: /^@vite-hub\/sandbox(?:\/runtime\/public)?$/ }, () => ({
|
|
1884
|
-
path: "sandbox-runtime-shim",
|
|
1885
|
-
namespace: SHIM_NAMESPACE
|
|
1886
|
-
}));
|
|
1887
|
-
pluginBuild.onLoad({
|
|
1888
|
-
filter: /.*/,
|
|
1889
|
-
namespace: SHIM_NAMESPACE
|
|
1890
|
-
}, () => ({
|
|
1891
|
-
contents: [
|
|
1892
|
-
"function hasStandardValidator(value) {",
|
|
1893
|
-
" return !!value && typeof value === \"object\" && !!value[\"~standard\"] && typeof value[\"~standard\"].validate === \"function\"",
|
|
1894
|
-
"}",
|
|
1895
|
-
"",
|
|
1896
|
-
"function createValidationError(cause) {",
|
|
1897
|
-
" if (cause instanceof Error)",
|
|
1898
|
-
" return cause",
|
|
1899
|
-
" const message = cause && typeof cause === \"object\" && typeof cause.message === \"string\"",
|
|
1900
|
-
" ? cause.message",
|
|
1901
|
-
" : \"Validation failed\"",
|
|
1902
|
-
" return Object.assign(new Error(message), cause && typeof cause === \"object\" ? cause : {})",
|
|
1903
|
-
"}",
|
|
1904
|
-
"",
|
|
1905
|
-
"export async function readValidatedPayload(payload, validate) {",
|
|
1906
|
-
" if (hasStandardValidator(validate)) {",
|
|
1907
|
-
" const result = await validate[\"~standard\"].validate(payload)",
|
|
1908
|
-
" if (result.issues?.length)",
|
|
1909
|
-
" throw createValidationError({ message: \"Validation failed\", issues: result.issues })",
|
|
1910
|
-
" return result.value",
|
|
1911
|
-
" }",
|
|
1912
|
-
" try {",
|
|
1913
|
-
" const result = await validate(payload)",
|
|
1914
|
-
" if (result === false)",
|
|
1915
|
-
" throw createValidationError({ message: \"Validation failed\" })",
|
|
1916
|
-
" return result === true || result == null ? payload : result",
|
|
1917
|
-
" }",
|
|
1918
|
-
" catch (error) {",
|
|
1919
|
-
" throw createValidationError(error)",
|
|
1920
|
-
" }",
|
|
1921
|
-
"}",
|
|
1922
|
-
"",
|
|
1923
|
-
"export function defineSandbox(input) {",
|
|
1924
|
-
" const { project: _project, run, ...options } = input",
|
|
1925
|
-
" return { run, options: Object.keys(options).length ? options : undefined }",
|
|
1926
|
-
"}"
|
|
1927
|
-
].join("\n"),
|
|
1928
|
-
loader: "js"
|
|
1929
|
-
}));
|
|
1930
|
-
}
|
|
1931
|
-
}]
|
|
1932
|
-
});
|
|
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 {
|
|
1937
|
-
...bundle,
|
|
1938
|
-
...options.execution ? { execution: options.execution } : {}
|
|
1939
|
-
};
|
|
1940
|
-
const prefix = project.packagePath === "." ? ".vitehub-sandbox" : `${project.packagePath}/.vitehub-sandbox`;
|
|
1941
|
-
const modules = {
|
|
1942
|
-
[`${prefix}/package.json`]: JSON.stringify({
|
|
1943
|
-
private: true,
|
|
1944
|
-
type: "module"
|
|
1945
|
-
}),
|
|
1946
|
-
...Object.fromEntries(Object.entries(bundle.modules).map(([path, contents]) => [`${prefix}/${path}`, contents]))
|
|
1947
|
-
};
|
|
1948
|
-
const digest = createHash("sha256").update(JSON.stringify({
|
|
1949
|
-
modules,
|
|
1950
|
-
packagePath: project.packagePath,
|
|
1951
|
-
project: project.digest
|
|
1952
|
-
})).digest("hex");
|
|
1953
|
-
return {
|
|
1954
|
-
entry: `${prefix}/${bundle.entry}`,
|
|
1955
|
-
...options.execution ? { execution: options.execution } : {},
|
|
1956
|
-
modules,
|
|
1957
|
-
project: {
|
|
1958
|
-
...project,
|
|
1959
|
-
digest
|
|
1960
|
-
}
|
|
1961
|
-
};
|
|
1962
|
-
}
|
|
1963
|
-
//#endregion
|
|
1964
|
-
//#region src/definition-options.ts
|
|
1965
|
-
const require = createRequire(import.meta.url);
|
|
1966
|
-
const sandboxDefinitionSyntax = "`defineSandbox({ run, ...options })`";
|
|
1967
|
-
function getTypeScript() {
|
|
1968
|
-
return require("typescript");
|
|
1969
|
-
}
|
|
1970
|
-
function readStaticValue(node) {
|
|
1971
|
-
const ts = getTypeScript();
|
|
1972
|
-
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
|
|
1973
|
-
if (ts.isNumericLiteral(node)) return Number(node.text);
|
|
1974
|
-
if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
|
|
1975
|
-
if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
|
|
1976
|
-
if (node.kind === ts.SyntaxKind.NullKeyword) return null;
|
|
1977
|
-
if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(node.operand)) return -Number(node.operand.text);
|
|
1978
|
-
if (ts.isParenthesizedExpression(node)) return readStaticValue(node.expression);
|
|
1979
|
-
if (ts.isArrayLiteralExpression(node)) return node.elements.map((element) => {
|
|
1980
|
-
if (!ts.isExpression(element)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options arrays must use static values.`);
|
|
1981
|
-
return readStaticValue(element);
|
|
1982
|
-
});
|
|
1983
|
-
if (ts.isObjectLiteralExpression(node)) {
|
|
1984
|
-
const value = {};
|
|
1985
|
-
for (const property of node.properties) {
|
|
1986
|
-
if (!ts.isPropertyAssignment(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use plain object literals.`);
|
|
1987
|
-
const key = ts.isIdentifier(property.name) ? property.name.text : ts.isStringLiteral(property.name) ? property.name.text : void 0;
|
|
1988
|
-
if (!key) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options only support identifier or string-literal keys.`);
|
|
1989
|
-
value[key] = readStaticValue(property.initializer);
|
|
1990
|
-
}
|
|
1991
|
-
return value;
|
|
1992
|
-
}
|
|
1993
|
-
throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use static JSON-serializable values.`);
|
|
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
|
-
}
|
|
2013
|
-
function readDefinitionObject(sourceFile) {
|
|
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
|
-
}
|
|
2021
|
-
for (const statement of sourceFile.statements) {
|
|
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;
|
|
2047
|
-
if (expression.arguments.length !== 1 || !ts.isObjectLiteralExpression(expression.arguments[0])) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires one direct object literal.`);
|
|
2048
|
-
return expression.arguments[0];
|
|
2049
|
-
}
|
|
2050
|
-
}
|
|
2051
|
-
function propertyName(property) {
|
|
2052
|
-
const ts = getTypeScript();
|
|
2053
|
-
if (!("name" in property) || !property.name) return void 0;
|
|
2054
|
-
return ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : void 0;
|
|
2055
|
-
}
|
|
2056
|
-
async function extractSandboxDefinitionMetadata(file) {
|
|
2057
|
-
const source = await readFile(file, "utf8");
|
|
2058
|
-
const ts = getTypeScript();
|
|
2059
|
-
const input = readDefinitionObject(ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS));
|
|
2060
|
-
if (!input) return void 0;
|
|
2061
|
-
const options = {};
|
|
2062
|
-
let project;
|
|
2063
|
-
let hasRun = false;
|
|
2064
|
-
for (const property of input.properties) {
|
|
2065
|
-
const key = propertyName(property);
|
|
2066
|
-
if (key === "run" && ts.isShorthandPropertyAssignment(property)) {
|
|
2067
|
-
hasRun = true;
|
|
2068
|
-
continue;
|
|
2069
|
-
}
|
|
2070
|
-
if (!key || !ts.isPropertyAssignment(property) && !ts.isMethodDeclaration(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires explicit object properties.`);
|
|
2071
|
-
if (key === "run") {
|
|
2072
|
-
hasRun = true;
|
|
2073
|
-
continue;
|
|
2074
|
-
}
|
|
2075
|
-
if (!ts.isPropertyAssignment(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use static values.`);
|
|
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;
|
|
2081
|
-
}
|
|
2082
|
-
if (!hasRun) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires a \`run\` handler.`);
|
|
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;
|
|
2088
|
-
}
|
|
2089
|
-
//#endregion
|
|
2090
|
-
//#region src/type-template.ts
|
|
2091
|
-
function createDefinitionContract(definition) {
|
|
2092
|
-
const module = `typeof import(${JSON.stringify(definition.handler)})`;
|
|
2093
|
-
if (definition.kind === "definition") return `{ payload: Parameters<${module}['default']['run']>[0], result: Awaited<ReturnType<${module}['default']['run']>> }`;
|
|
2094
|
-
return `SandboxPackageContract<${module}['default']>`;
|
|
2095
|
-
}
|
|
2096
|
-
function createSandboxTypeTemplateContents(definitions) {
|
|
2097
|
-
return [
|
|
2098
|
-
`declare module '#vitehub-sandbox-registry' {`,
|
|
2099
|
-
` type SandboxPackageContract<TDefault extends (...args: any[]) => any> = TDefault extends (...args: infer TArgs) => infer TResult`,
|
|
2100
|
-
` ? { payload: TArgs extends [] ? unknown : TArgs[0], result: Awaited<TResult> }`,
|
|
2101
|
-
` : never`,
|
|
2102
|
-
` export interface SandboxDefinitionModules {`,
|
|
2103
|
-
...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: ${createDefinitionContract(definition)},`),
|
|
2104
|
-
` }`,
|
|
2105
|
-
` const sandboxRegistry: {`,
|
|
2106
|
-
...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: () => Promise<{ default?: { bundle: import('@vite-hub/sandbox').SandboxDefinitionBundle, options?: import('@vite-hub/sandbox').SandboxDefinitionOptions } }>,`),
|
|
2107
|
-
` }`,
|
|
2108
|
-
` export default sandboxRegistry`,
|
|
2109
|
-
`}`,
|
|
2110
|
-
``
|
|
2111
|
-
].join("\n");
|
|
2112
|
-
}
|
|
2113
|
-
//#endregion
|
|
2114
|
-
//#region src/feature.ts
|
|
2115
|
-
const sandboxRuntimeStateSpecifier = "@vite-hub/sandbox/runtime/state";
|
|
2116
|
-
const sandboxRuntimeSpecifier = "@vite-hub/sandbox/_internal/runtime";
|
|
2117
|
-
const sandboxRuntimeProviderSpecifiers = {
|
|
2118
|
-
cloudflare: `${sandboxRuntimeSpecifier}/providers/cloudflare`,
|
|
2119
|
-
vercel: `${sandboxRuntimeSpecifier}/providers/vercel`
|
|
2120
|
-
};
|
|
2121
|
-
const sandboxRuntimeDependencyByProvider = {
|
|
2122
|
-
cloudflare: "@cloudflare/sandbox",
|
|
2123
|
-
vercel: "@vercel/sandbox"
|
|
2124
|
-
};
|
|
2125
|
-
function resolveSandboxProviderLoaderTarget(provider, deps) {
|
|
2126
|
-
if (provider) return provider;
|
|
2127
|
-
const hasCloudflareSandbox = Boolean(deps["@cloudflare/sandbox"]);
|
|
2128
|
-
if (hasCloudflareSandbox === Boolean(deps["@vercel/sandbox"])) return void 0;
|
|
2129
|
-
return hasCloudflareSandbox ? "cloudflare" : "vercel";
|
|
2130
|
-
}
|
|
2131
|
-
const sandboxProviderLoaderSpecifiers = [
|
|
2132
|
-
"vitehub-sandbox-provider-loader",
|
|
2133
|
-
"@vite-hub/sandbox/runtime/provider-loader",
|
|
2134
|
-
"virtual:vitehub-sandbox-provider-loader",
|
|
2135
|
-
"#vitehub-sandbox-provider-loader"
|
|
2136
|
-
];
|
|
2137
|
-
function createSandboxProviderLoaderAliases(defaultProviderName) {
|
|
2138
|
-
const keys = sandboxProviderLoaderSpecifiers;
|
|
2139
|
-
if (defaultProviderName) return keys.map((key) => ({
|
|
2140
|
-
key,
|
|
2141
|
-
artifactKey: "sandbox-provider-loader"
|
|
2142
|
-
}));
|
|
2143
|
-
const providerLoaderPath = resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./runtime/provider-loader", "runtime/provider-loader.js");
|
|
2144
|
-
return keys.map((key) => ({
|
|
2145
|
-
key,
|
|
2146
|
-
value: providerLoaderPath
|
|
2147
|
-
}));
|
|
2148
|
-
}
|
|
2149
|
-
function createSandboxManifest(aliasPath, typeTemplate) {
|
|
2150
|
-
return {
|
|
2151
|
-
alias: "@vite-hub/sandbox",
|
|
2152
|
-
aliasPath,
|
|
2153
|
-
imports: [
|
|
2154
|
-
{
|
|
2155
|
-
name: "defineSandbox",
|
|
2156
|
-
from: "@vite-hub/sandbox",
|
|
2157
|
-
meta: { description: "Define a free-form sandbox resource." }
|
|
2158
|
-
},
|
|
2159
|
-
{
|
|
2160
|
-
name: "readValidatedPayload",
|
|
2161
|
-
as: "readValidatedSandboxPayload",
|
|
2162
|
-
from: "@vite-hub/sandbox",
|
|
2163
|
-
meta: { description: "Validate sandbox payload input before execution." }
|
|
2164
|
-
},
|
|
2165
|
-
{
|
|
2166
|
-
name: "runSandbox",
|
|
2167
|
-
from: "@vite-hub/sandbox",
|
|
2168
|
-
meta: { description: "Run a named sandbox definition." }
|
|
2169
|
-
},
|
|
2170
|
-
{
|
|
2171
|
-
name: "SandboxDefinition",
|
|
2172
|
-
as: "SandboxDefinition",
|
|
2173
|
-
from: "@vite-hub/sandbox",
|
|
2174
|
-
type: true
|
|
2175
|
-
},
|
|
2176
|
-
{
|
|
2177
|
-
name: "SandboxRunResult",
|
|
2178
|
-
as: "SandboxRunResult",
|
|
2179
|
-
from: "@vite-hub/sandbox",
|
|
2180
|
-
type: true
|
|
2181
|
-
}
|
|
2182
|
-
],
|
|
2183
|
-
typeTemplate: {
|
|
2184
|
-
filename: "runtime/sandbox.d.ts",
|
|
2185
|
-
contents: typeTemplate
|
|
2186
|
-
}
|
|
2187
|
-
};
|
|
2188
|
-
}
|
|
2189
|
-
function normalizeSandboxDefinitionOptions(name, options) {
|
|
2190
|
-
if (!options) return void 0;
|
|
2191
|
-
try {
|
|
2192
|
-
return JSON.parse(JSON.stringify(options));
|
|
2193
|
-
} catch (error) {
|
|
2194
|
-
throw new Error(`[vitehub] Sandbox definition "${name}" options must be JSON-serializable.`, { cause: error });
|
|
2195
|
-
}
|
|
2196
|
-
}
|
|
2197
|
-
async function loadSandboxDefinitionMetadata(definitions, rootDir) {
|
|
2198
|
-
return await Promise.all(definitions.map(async (definition) => {
|
|
2199
|
-
const sourceMetadata = definition.kind === "package-entry" ? void 0 : await extractSandboxDefinitionMetadata(definition.handler);
|
|
2200
|
-
const project = sourceMetadata?.project === false ? void 0 : await resolveSandboxProject(definition.handler, rootDir, { readSandboxOptions: definition.kind === "package-entry" });
|
|
2201
|
-
return {
|
|
2202
|
-
kind: definition.kind,
|
|
2203
|
-
name: definition.name,
|
|
2204
|
-
options: definition.kind === "package-entry" ? project?.options : normalizeSandboxDefinitionOptions(definition.name, sourceMetadata?.options),
|
|
2205
|
-
project,
|
|
2206
|
-
projectMode: sourceMetadata?.project
|
|
2207
|
-
};
|
|
2208
|
-
}));
|
|
2209
|
-
}
|
|
2210
|
-
function createSandboxRegistryContents(file, definitions, scope) {
|
|
2211
|
-
const scopeSpecifier = createFileImportSpecifier(scope);
|
|
2212
|
-
return [
|
|
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
|
-
"})",
|
|
2223
|
-
"export default registry",
|
|
2224
|
-
""
|
|
2225
|
-
].join("\n");
|
|
2226
|
-
}
|
|
2227
|
-
function createSandboxProviderLoaderContents(provider) {
|
|
2228
|
-
const providerExport = sandboxProviderRuntimeExport(provider);
|
|
2229
|
-
const providerLoaderPath = sandboxRuntimeProviderSpecifiers[provider];
|
|
2230
|
-
return [
|
|
2231
|
-
`import { ${providerExport} as resolveSandboxBox } from ${JSON.stringify(providerLoaderPath)}`,
|
|
2232
|
-
"",
|
|
2233
|
-
"export async function loadSandboxRuntimeProvider(selectedProvider) {",
|
|
2234
|
-
` if (selectedProvider !== ${JSON.stringify(provider)})`,
|
|
2235
|
-
" throw new Error(`[vitehub] Unsupported sandbox provider for this hosted build: ${selectedProvider}`)",
|
|
2236
|
-
" return {",
|
|
2237
|
-
" resolveSandboxBox,",
|
|
2238
|
-
" }",
|
|
2239
|
-
"}",
|
|
2240
|
-
""
|
|
2241
|
-
].join("\n");
|
|
2242
|
-
}
|
|
2243
|
-
function sandboxProviderRuntimeExport(provider) {
|
|
2244
|
-
return provider === "cloudflare" ? "resolveCloudflareSandboxBox" : "resolveVercelSandboxBox";
|
|
2245
|
-
}
|
|
2246
|
-
function resolveSandboxFeatureConfig(sandboxConfig, hosting) {
|
|
2247
|
-
if (getSandboxFeatureProvider(sandboxConfig)?.provider) return { ...sandboxConfig };
|
|
2248
|
-
const config = { ...sandboxConfig };
|
|
2249
|
-
const hostedProvider = getSupportedHostingProvider(hosting, ["cloudflare", "vercel"]);
|
|
2250
|
-
if (hostedProvider) return {
|
|
2251
|
-
...config,
|
|
2252
|
-
provider: hostedProvider
|
|
2253
|
-
};
|
|
2254
|
-
const unsupportedHostedProvider = deploymentPresetFromNitro(hosting);
|
|
2255
|
-
if (unsupportedHostedProvider) throw new TypeError("[vitehub] Sandbox hosting inference does not support " + unsupportedHostedProvider + ". An explicit `sandbox.provider` is required.");
|
|
2256
|
-
return config;
|
|
2257
|
-
}
|
|
2258
|
-
async function createSandboxFeaturePlan(sandboxConfig, definitions, paths, deps, hosting, discoveredDefinitionOptions = {}) {
|
|
2259
|
-
const resolvedConfig = definitions.length > 0 ? resolveSandboxFeatureConfig(sandboxConfig, hosting) : { ...sandboxConfig };
|
|
2260
|
-
const sandboxDefinitions = definitions.map((definition) => ({
|
|
2261
|
-
...definition,
|
|
2262
|
-
definitionArtifactKey: `sandbox-definition:${definition.name}`,
|
|
2263
|
-
definitionFilename: `runtime/sandbox-definitions/${toTemplateSafeName(definition.name)}.mjs`
|
|
2264
|
-
}));
|
|
2265
|
-
const definitionFileByName = /* @__PURE__ */ new Map();
|
|
2266
|
-
for (const definition of sandboxDefinitions) {
|
|
2267
|
-
const existing = definitionFileByName.get(definition.definitionFilename);
|
|
2268
|
-
if (existing) throw new Error(`[vitehub] Sandbox definitions "${existing}" and "${definition.name}" generate the same artifact path "${definition.definitionFilename}".`);
|
|
2269
|
-
definitionFileByName.set(definition.definitionFilename, definition.name);
|
|
2270
|
-
}
|
|
2271
|
-
const definitionMetadata = await loadSandboxDefinitionMetadata(definitions, discoveredDefinitionOptions.rootDir || process.cwd());
|
|
2272
|
-
const metadataByName = new Map(definitionMetadata.map((definition) => [definition.name, definition]));
|
|
2273
|
-
const manifest = createSandboxManifest(paths.aliasPath, createSandboxTypeTemplateContents(definitions.map((definition) => {
|
|
2274
|
-
return {
|
|
2275
|
-
handler: definition.handler,
|
|
2276
|
-
kind: definition.kind,
|
|
2277
|
-
name: definition.name
|
|
2278
|
-
};
|
|
2279
|
-
})));
|
|
2280
|
-
const { bundleAlias, featureImports = manifest.imports, ...definitionCompilerOptions } = discoveredDefinitionOptions;
|
|
2281
|
-
const definitionCompiler = await createDiscoveredDefinitionCompiler({
|
|
2282
|
-
...definitionCompilerOptions,
|
|
2283
|
-
featureImports
|
|
2284
|
-
});
|
|
2285
|
-
const defaultProvider = getSandboxFeatureProvider(resolvedConfig);
|
|
2286
|
-
const defaultProviderName = defaultProvider?.provider;
|
|
2287
|
-
const sandboxArtifacts = sandboxDefinitions.map((definition) => ({
|
|
2288
|
-
key: definition.definitionArtifactKey,
|
|
2289
|
-
filename: definition.definitionFilename,
|
|
2290
|
-
async getContents() {
|
|
2291
|
-
const source = await definitionCompiler.readSource(definition._meta.sourcePath);
|
|
2292
|
-
const metadata = metadataByName.get(definition.name);
|
|
2293
|
-
const bundle = await bundleSandboxDefinition(source, definition._meta.sourcePath, {
|
|
2294
|
-
alias: bundleAlias,
|
|
2295
|
-
execution: metadata?.kind === "package-entry" ? "module" : "definition",
|
|
2296
|
-
includeProject: metadata?.projectMode,
|
|
2297
|
-
project: metadata?.project
|
|
2298
|
-
});
|
|
2299
|
-
return `export default ${JSON.stringify({
|
|
2300
|
-
bundle,
|
|
2301
|
-
options: metadata?.options
|
|
2302
|
-
})}\n`;
|
|
2303
|
-
}
|
|
2304
|
-
}));
|
|
2305
|
-
const providerLoaderTarget = resolveSandboxProviderLoaderTarget(defaultProviderName, deps);
|
|
2306
|
-
const cloudflareOptions = defaultProvider?.provider === "cloudflare" ? {
|
|
2307
|
-
binding: typeof defaultProvider.binding === "string" ? defaultProvider.binding : defaultCloudflareSandboxBinding,
|
|
2308
|
-
className: typeof defaultProvider.className === "string" ? defaultProvider.className : defaultCloudflareSandboxClassName,
|
|
2309
|
-
migrationTag: typeof defaultProvider.migrationTag === "string" ? defaultProvider.migrationTag : "v1",
|
|
2310
|
-
name: typeof defaultProvider.name === "string" ? defaultProvider.name : void 0
|
|
2311
|
-
} : void 0;
|
|
2312
|
-
return {
|
|
2313
|
-
manifest,
|
|
2314
|
-
watchFiles: [...new Set(definitionMetadata.flatMap((metadata) => metadata.project ? getSandboxProjectSourceFiles(metadata.project) : []))],
|
|
2315
|
-
aliases: [{
|
|
2316
|
-
key: "#vitehub-sandbox-registry",
|
|
2317
|
-
artifactKey: "sandbox-registry"
|
|
2318
|
-
}, ...createSandboxProviderLoaderAliases(providerLoaderTarget)],
|
|
2319
|
-
artifacts: [
|
|
2320
|
-
...sandboxArtifacts,
|
|
2321
|
-
{
|
|
2322
|
-
key: "sandbox-registry",
|
|
2323
|
-
filename: "runtime/sandbox-registry.mjs",
|
|
2324
|
-
getContents(emitted, location) {
|
|
2325
|
-
return createSandboxRegistryContents(location.dst, sandboxDefinitions.map((definition) => {
|
|
2326
|
-
const artifact = emitted.get(definition.definitionArtifactKey);
|
|
2327
|
-
if (!artifact) throw new Error(`[vitehub] Missing generated sandbox definition module for "${definition.name}".`);
|
|
2328
|
-
return {
|
|
2329
|
-
name: definition.name,
|
|
2330
|
-
definitionModulePath: artifact.dst,
|
|
2331
|
-
stableDefinitionModulePath: artifact.stableDst
|
|
2332
|
-
};
|
|
2333
|
-
}), paths.aliasPath);
|
|
2334
|
-
}
|
|
2335
|
-
},
|
|
2336
|
-
...providerLoaderTarget ? [{
|
|
2337
|
-
key: "sandbox-provider-loader",
|
|
2338
|
-
filename: "runtime/sandbox-provider-loader.mjs",
|
|
2339
|
-
contents: createSandboxProviderLoaderContents(providerLoaderTarget)
|
|
2340
|
-
}] : []
|
|
2341
|
-
],
|
|
2342
|
-
cloudflare: cloudflareOptions
|
|
2343
|
-
};
|
|
2344
|
-
}
|
|
2345
|
-
//#endregion
|
|
2346
|
-
//#region src/discovery.ts
|
|
2347
|
-
const sandboxSuffixPattern = /\.sandbox\.(?:c|m)?[jt]s$/i;
|
|
2348
|
-
const sandboxEntrypointFilenames = [
|
|
2349
|
-
"index.ts",
|
|
2350
|
-
"index.mts",
|
|
2351
|
-
"index.js",
|
|
2352
|
-
"index.mjs"
|
|
2353
|
-
];
|
|
2354
|
-
function createDiscoveredSandboxDefinition(source, kind) {
|
|
2355
|
-
return (context) => ({
|
|
2356
|
-
handler: context.file,
|
|
2357
|
-
kind,
|
|
2358
|
-
name: context.name,
|
|
2359
|
-
source,
|
|
2360
|
-
_meta: {
|
|
2361
|
-
filename: context.name,
|
|
2362
|
-
sourcePath: context.file
|
|
2363
|
-
}
|
|
2364
|
-
});
|
|
2365
|
-
}
|
|
2366
|
-
function isServerSandboxFile(rootDir, file) {
|
|
2367
|
-
const path = relative(rootDir, file).replace(/\\/g, "/");
|
|
2368
|
-
return path.startsWith("server/sandboxes/") || path.startsWith("src/server/sandboxes/");
|
|
2369
|
-
}
|
|
2370
|
-
function normalizeSuffixSandboxName(rootDir, file) {
|
|
2371
|
-
if (isServerSandboxFile(rootDir, file)) return void 0;
|
|
2372
|
-
return normalizeSuffixDefinitionName(rootDir, file, sandboxSuffixPattern, { stripPrefix: "src/" });
|
|
2373
|
-
}
|
|
2374
|
-
function normalizeDirectorySandboxName(directory, file) {
|
|
2375
|
-
return normalizePathDefinitionName(directory, file).replace(/\.sandbox$/, "");
|
|
2376
|
-
}
|
|
2377
|
-
function isNestedDirectory(parent, candidate) {
|
|
2378
|
-
const path = relative(parent, candidate).replace(/\\/g, "/");
|
|
2379
|
-
return path !== "" && path !== ".." && !path.startsWith("../");
|
|
2380
|
-
}
|
|
2381
|
-
function discoverServerSandboxDefinitions(scanDirs) {
|
|
2382
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
2383
|
-
const createDefinition = createDiscoveredSandboxDefinition("server-sandboxes", "package-entry");
|
|
2384
|
-
for (const scanDir of scanDirs) {
|
|
2385
|
-
const directory = resolve(scanDir, "sandboxes");
|
|
2386
|
-
const packageRoots = listMatchingFiles(directory, (name) => name === "package.json").map((manifest) => dirname(manifest)).sort((left, right) => {
|
|
2387
|
-
return relative(directory, left).split(/[\\/]/).length - relative(directory, right).split(/[\\/]/).length || left.localeCompare(right);
|
|
2388
|
-
});
|
|
2389
|
-
const entrypoints = new Map(packageRoots.map((packageRoot) => [packageRoot, sandboxEntrypointFilenames.map((filename) => resolve(packageRoot, filename)).filter((file) => existsSync(file))]));
|
|
2390
|
-
const selectedRoots = [];
|
|
2391
|
-
for (const packageRoot of packageRoots) {
|
|
2392
|
-
if (selectedRoots.some((root) => isNestedDirectory(root, packageRoot))) continue;
|
|
2393
|
-
const packageEntrypoints = entrypoints.get(packageRoot);
|
|
2394
|
-
if (packageEntrypoints.length > 1) throw new Error(`[vitehub] Sandbox package "${packageRoot}" has multiple entrypoints: ${packageEntrypoints.join(", ")}.`);
|
|
2395
|
-
if (packageEntrypoints.length === 0) continue;
|
|
2396
|
-
const file = packageEntrypoints[0];
|
|
2397
|
-
registerDefinition(definitions, createDefinition({
|
|
2398
|
-
file,
|
|
2399
|
-
name: normalizeDirectorySandboxName(directory, file)
|
|
2400
|
-
}), "sandbox");
|
|
2401
|
-
selectedRoots.push(packageRoot);
|
|
2402
|
-
}
|
|
2403
|
-
for (const packageRoot of packageRoots) {
|
|
2404
|
-
if (entrypoints.get(packageRoot).length > 0) continue;
|
|
2405
|
-
if (selectedRoots.some((root) => isNestedDirectory(packageRoot, root) || isNestedDirectory(root, packageRoot))) continue;
|
|
2406
|
-
throw new Error(`[vitehub] Sandbox package "${packageRoot}" requires one ESM entrypoint: ${sandboxEntrypointFilenames.join(", ")}.`);
|
|
2407
|
-
}
|
|
2408
|
-
}
|
|
2409
|
-
return sortDefinitions(definitions);
|
|
2410
|
-
}
|
|
2411
|
-
function discoverSandboxDefinitions(options) {
|
|
2412
|
-
if (options.mode === "server-sandboxes") return discoverServerSandboxDefinitions(options.scanDirs);
|
|
2413
|
-
const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
|
|
2414
|
-
const serverScanDirs = roots.map((root) => resolve(root, "server"));
|
|
2415
|
-
return mergeDefinitions("sandbox", discoverDefinitions("sandbox", [createSuffixDefinitionSource("vite-suffix", roots, sandboxSuffixPattern, normalizeSuffixSandboxName, { createDefinition: createDiscoveredSandboxDefinition("vite-suffix", "definition") })]), discoverServerSandboxDefinitions(serverScanDirs));
|
|
2416
|
-
}
|
|
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
|
|
2769
|
-
//#region src/internal/runtime-preparation.ts
|
|
2770
|
-
const SANDBOX_PACKAGE_ID$1 = "@vite-hub/sandbox";
|
|
2771
|
-
const SANDBOX_REGISTRY_ID = "#vitehub-sandbox-registry";
|
|
2772
|
-
const builtinModuleSet = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
2773
|
-
function readNodeErrorCode(error) {
|
|
2774
|
-
return error instanceof Error && "code" in error ? error.code : void 0;
|
|
2775
|
-
}
|
|
2776
|
-
function normalizeSandboxOptions(options) {
|
|
2777
|
-
if (options === false) return false;
|
|
2778
|
-
if (!isPlainObject$1(options)) throw new TypeError("[vitehub] `sandbox` must be a plain object.");
|
|
2779
|
-
return { ...options };
|
|
2780
|
-
}
|
|
2781
|
-
function createSandboxRuntimeConfig(config, hosting) {
|
|
2782
|
-
const provider = getSandboxFeatureProvider(config);
|
|
2783
|
-
const sandbox = provider?.provider === "vercel" ? {
|
|
2784
|
-
...config,
|
|
2785
|
-
token: provider.token ?? "",
|
|
2786
|
-
teamId: provider.teamId ?? "",
|
|
2787
|
-
projectId: provider.projectId ?? ""
|
|
2788
|
-
} : config;
|
|
2789
|
-
return {
|
|
2790
|
-
...hosting ? { hosting } : {},
|
|
2791
|
-
sandbox
|
|
2792
|
-
};
|
|
2793
|
-
}
|
|
2794
|
-
async function readSandboxWorkspaceDeps(rootDir) {
|
|
2795
|
-
const packageJson = JSON.parse(await readFile(resolve(rootDir, "package.json"), "utf8"));
|
|
2796
|
-
return {
|
|
2797
|
-
...packageJson.dependencies,
|
|
2798
|
-
...packageJson.devDependencies
|
|
2799
|
-
};
|
|
2800
|
-
}
|
|
2801
|
-
async function resolveSandboxViteContext(integrationOptions, userConfig, env, hasDefinitions) {
|
|
2802
|
-
const configOptions = userConfig.sandbox;
|
|
2803
|
-
const options = normalizeSandboxOptions(typeof configOptions === "undefined" ? integrationOptions ?? {} : configOptions);
|
|
2804
|
-
const nitro = isPlainObject$1(userConfig.nitro) ? userConfig.nitro : {};
|
|
2805
|
-
const hosting = detectHosting({ options: { preset: typeof userConfig.preset === "string" ? userConfig.preset : typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET } }) || void 0;
|
|
2806
|
-
const config = options === false ? false : hasDefinitions ? resolveSandboxFeatureConfig(options, hosting) : { ...options };
|
|
2807
|
-
const runtimeSandboxConfig = config !== false && (hasDefinitions || getSandboxFeatureProvider(config)?.provider) ? config : false;
|
|
2808
|
-
const rootDir = resolve(process.cwd(), typeof userConfig.root === "string" ? userConfig.root : ".");
|
|
2809
|
-
return {
|
|
2810
|
-
rootDir,
|
|
2811
|
-
config,
|
|
2812
|
-
deps: hasDefinitions ? await readSandboxWorkspaceDeps(rootDir) : {},
|
|
2813
|
-
runtimeConfig: createSandboxRuntimeConfig(runtimeSandboxConfig, hosting),
|
|
2814
|
-
hosting,
|
|
2815
|
-
command: env.command,
|
|
2816
|
-
mode: env.mode
|
|
2817
|
-
};
|
|
2818
|
-
}
|
|
2819
|
-
function createSandboxStateModuleContents(context) {
|
|
2820
|
-
const state = {
|
|
2821
|
-
config: context.config,
|
|
2822
|
-
runtimeConfig: context.runtimeConfig,
|
|
2823
|
-
hosting: context.hosting,
|
|
2824
|
-
rootDir: context.rootDir,
|
|
2825
|
-
mode: context.mode,
|
|
2826
|
-
command: context.command
|
|
2827
|
-
};
|
|
2828
|
-
return [
|
|
2829
|
-
`const state = ${JSON.stringify(state, null, 2)}`,
|
|
2830
|
-
"export const config = state.config",
|
|
2831
|
-
"export const runtimeConfig = state.runtimeConfig",
|
|
2832
|
-
"export const hosting = state.hosting",
|
|
2833
|
-
"export const rootDir = state.rootDir",
|
|
2834
|
-
"export const mode = state.mode",
|
|
2835
|
-
"export const command = state.command",
|
|
2836
|
-
"export default state",
|
|
2837
|
-
""
|
|
2838
|
-
].join("\n");
|
|
2839
|
-
}
|
|
2840
|
-
function readAliasEntries(alias) {
|
|
2841
|
-
if (Array.isArray(alias)) return alias;
|
|
2842
|
-
if (!alias || typeof alias !== "object") return [];
|
|
2843
|
-
return Object.entries(alias).filter((entry) => typeof entry[1] === "string").map(([find, replacement]) => ({
|
|
2844
|
-
find,
|
|
2845
|
-
replacement
|
|
2846
|
-
}));
|
|
2847
|
-
}
|
|
2848
|
-
function resolveStringAliases(alias) {
|
|
2849
|
-
const aliases = {};
|
|
2850
|
-
for (const entry of readAliasEntries(alias)) {
|
|
2851
|
-
if (typeof entry.find !== "string" || typeof entry.replacement !== "string") continue;
|
|
2852
|
-
const find = entry.find.replace(/\/$/, "");
|
|
2853
|
-
if (builtinModuleSet.has(entry.find) || builtinModuleSet.has(find)) continue;
|
|
2854
|
-
if (!find) continue;
|
|
2855
|
-
aliases[find] = entry.replacement;
|
|
2856
|
-
}
|
|
2857
|
-
return aliases;
|
|
2858
|
-
}
|
|
2859
|
-
function readResolveOptions(config) {
|
|
2860
|
-
if (!config || typeof config !== "object" || !("resolve" in config)) return {};
|
|
2861
|
-
const resolveOptions = config.resolve;
|
|
2862
|
-
return resolveOptions && typeof resolveOptions === "object" ? resolveOptions : {};
|
|
2863
|
-
}
|
|
2864
|
-
function createSandboxRuntimeFacadeContents(file, runtimeConfig, registryFile, providerLoaderFile) {
|
|
2865
|
-
return [
|
|
2866
|
-
`import sandboxRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
|
|
2867
|
-
...providerLoaderFile ? [`export { loadSandboxRuntimeProvider } from ${JSON.stringify(createImportPath(file, providerLoaderFile))}`] : [],
|
|
2868
|
-
`import { setSandboxRuntimeConfig, setSandboxRuntimeRegistry } from ${JSON.stringify(sandboxRuntimeStateSpecifier)}`,
|
|
2869
|
-
"",
|
|
2870
|
-
`setSandboxRuntimeConfig(${JSON.stringify(runtimeConfig, null, 2)})`,
|
|
2871
|
-
"setSandboxRuntimeRegistry(sandboxRegistry)",
|
|
2872
|
-
"",
|
|
2873
|
-
"export default sandboxRegistry",
|
|
2874
|
-
`export * from ${JSON.stringify(sandboxRuntimeSpecifier)}`,
|
|
2875
|
-
""
|
|
2876
|
-
].join("\n");
|
|
2877
|
-
}
|
|
2878
|
-
function createGeneratedAliasMap(rootDir, plan, platform = process.platform) {
|
|
2879
|
-
const generatedDir = ensureGeneratedDir(rootDir, "sandbox");
|
|
2880
|
-
const artifactPaths = new Map((plan.artifacts || []).map((artifact) => [artifact.key, resolve(generatedDir, artifact.filename)]));
|
|
2881
|
-
const aliases = { [SANDBOX_PACKAGE_ID$1]: plan.manifest.aliasPath };
|
|
2882
|
-
for (const alias of plan.aliases || []) {
|
|
2883
|
-
if (alias.value) {
|
|
2884
|
-
aliases[alias.key] = alias.value;
|
|
2885
|
-
continue;
|
|
2886
|
-
}
|
|
2887
|
-
if (platform === "win32" && alias.artifactKey) {
|
|
2888
|
-
aliases[alias.key] = plan.manifest.aliasPath;
|
|
2889
|
-
continue;
|
|
2890
|
-
}
|
|
2891
|
-
if (alias.artifactKey && artifactPaths.has(alias.artifactKey)) aliases[alias.key] = artifactPaths.get(alias.artifactKey);
|
|
2892
|
-
}
|
|
2893
|
-
return aliases;
|
|
2894
|
-
}
|
|
2895
|
-
async function writeSandboxArtifacts(rootDir, plan, createFacadeContents, platform = process.platform) {
|
|
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)}`);
|
|
2907
|
-
const emitted = /* @__PURE__ */ new Map();
|
|
2908
|
-
const typeTemplate = plan.manifest.typeTemplate;
|
|
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
|
|
3000
|
-
});
|
|
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
|
-
});
|
|
3017
|
-
return emitted;
|
|
3018
|
-
}
|
|
3019
|
-
async function prepareSandboxRuntime(options) {
|
|
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;
|
|
3023
|
-
const configOptions = options.userConfig.sandbox;
|
|
3024
|
-
const definitions = (typeof configOptions === "undefined" ? options.integrationOptions === false : configOptions === false) ? [] : discoverSandboxDefinitions({ rootDir });
|
|
3025
|
-
const resolvedNitro = options.resolvedConfig?.nitro;
|
|
3026
|
-
const context = await resolveSandboxViteContext(options.integrationOptions, {
|
|
3027
|
-
...options.userConfig,
|
|
3028
|
-
...isPlainObject$1(resolvedNitro) ? { nitro: resolvedNitro } : {},
|
|
3029
|
-
root: rootDir
|
|
3030
|
-
}, options.env, definitions.length > 0);
|
|
3031
|
-
const stateModule = createSandboxStateModuleContents(context);
|
|
3032
|
-
if (!context.config) return {
|
|
3033
|
-
aliases: {},
|
|
3034
|
-
definitions: [],
|
|
3035
|
-
files: [],
|
|
3036
|
-
hosting: context.hosting,
|
|
3037
|
-
provider: void 0,
|
|
3038
|
-
rootDir,
|
|
3039
|
-
stateModule,
|
|
3040
|
-
watchFiles: []
|
|
3041
|
-
};
|
|
3042
|
-
const facadeFile = resolve(ensureGeneratedDir(rootDir, "sandbox"), "runtime/sandbox.mjs");
|
|
3043
|
-
const plan = await createSandboxFeaturePlan(context.config, definitions, { aliasPath: facadeFile }, context.deps, context.hosting, {
|
|
3044
|
-
bundleAlias: resolveStringAliases(options.resolvedConfig?.resolve.alias ?? readResolveOptions(options.userConfig).alias),
|
|
3045
|
-
rootDir,
|
|
3046
|
-
scanRoots: [rootDir],
|
|
3047
|
-
serverImports: { presets: [] }
|
|
3048
|
-
});
|
|
3049
|
-
const aliases = createGeneratedAliasMap(rootDir, plan, options.platform);
|
|
3050
|
-
if (options.writeArtifacts === false) return {
|
|
3051
|
-
aliases,
|
|
3052
|
-
cloudflare: plan.cloudflare,
|
|
3053
|
-
definitions,
|
|
3054
|
-
files: [],
|
|
3055
|
-
hosting: context.hosting,
|
|
3056
|
-
provider: getSandboxFeatureProvider(context.config)?.provider,
|
|
3057
|
-
rootDir,
|
|
3058
|
-
stateModule,
|
|
3059
|
-
watchFiles: plan.watchFiles || []
|
|
3060
|
-
};
|
|
3061
|
-
const emitted = await writeSandboxArtifacts(rootDir, plan, (file, registryFile, providerLoaderFile) => createSandboxRuntimeFacadeContents(file, context.runtimeConfig.sandbox, registryFile, providerLoaderFile), options.platform);
|
|
3062
|
-
return {
|
|
3063
|
-
aliases,
|
|
3064
|
-
cloudflare: plan.cloudflare,
|
|
3065
|
-
definitions,
|
|
3066
|
-
files: [
|
|
3067
|
-
facadeFile,
|
|
3068
|
-
...Array.from(emitted.values(), (artifact) => artifact.dst),
|
|
3069
|
-
...(plan.artifacts || []).map((artifact) => resolve(ensureGeneratedDir(rootDir, "sandbox"), artifact.filename))
|
|
3070
|
-
],
|
|
3071
|
-
hosting: context.hosting,
|
|
3072
|
-
provider: getSandboxFeatureProvider(context.config)?.provider,
|
|
3073
|
-
rootDir,
|
|
3074
|
-
stateModule,
|
|
3075
|
-
watchFiles: plan.watchFiles || []
|
|
3076
|
-
};
|
|
3077
|
-
}
|
|
3078
|
-
//#endregion
|
|
3079
|
-
//#region src/vite.ts
|
|
3080
|
-
const SANDBOX_PACKAGE_ID = "@vite-hub/sandbox";
|
|
3081
|
-
const SANDBOX_PROVIDER_LOADER_ID = "vitehub-sandbox-provider-loader";
|
|
3082
|
-
const SANDBOX_STATE_ID = "#vitehub/sandbox";
|
|
3083
|
-
const RESOLVED_SANDBOX_STATE_ID = "\0vitehub:sandbox:state";
|
|
3084
|
-
function mergeSandboxNitroProviderAliases(nitro, aliases) {
|
|
3085
|
-
const providerAliases = Object.fromEntries(sandboxProviderLoaderSpecifiers.flatMap((specifier) => {
|
|
3086
|
-
const replacement = aliases[specifier];
|
|
3087
|
-
return replacement ? [[specifier, replacement]] : [];
|
|
3088
|
-
}));
|
|
3089
|
-
if (!Object.keys(providerAliases).length) return;
|
|
3090
|
-
nitro.alias = {
|
|
3091
|
-
...isPlainObject$1(nitro.alias) ? nitro.alias : {},
|
|
3092
|
-
...providerAliases
|
|
3093
|
-
};
|
|
3094
|
-
}
|
|
3095
|
-
function mergeSandboxNitroNoExternals(nitro, provider) {
|
|
3096
|
-
if (provider !== "cloudflare" && provider !== "vercel") return;
|
|
3097
|
-
const existing = nitro.noExternals;
|
|
3098
|
-
if (existing === true) return;
|
|
3099
|
-
const existingEntries = Array.isArray(existing) ? existing : [];
|
|
3100
|
-
const additions = [SANDBOX_PACKAGE_ID, sandboxRuntimeDependencyByProvider[provider]];
|
|
3101
|
-
nitro.noExternals = [...existingEntries, ...additions.filter((addition) => !existingEntries.includes(addition))];
|
|
3102
|
-
}
|
|
3103
|
-
function sandboxProviderLoaderFallback() {
|
|
3104
|
-
return resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./runtime/provider-loader", "runtime/provider-loader.js");
|
|
3105
|
-
}
|
|
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
|
-
};
|
|
3112
|
-
function toSandboxAliasEntries(aliases) {
|
|
3113
|
-
return Object.entries(aliases).map(([find, replacement]) => ({
|
|
3114
|
-
find: find === SANDBOX_PACKAGE_ID ? /^@vite-hub\/sandbox$/ : find,
|
|
3115
|
-
replacement
|
|
3116
|
-
}));
|
|
3117
|
-
}
|
|
3118
|
-
function withoutSandboxPackageAlias(aliases) {
|
|
3119
|
-
const { [SANDBOX_PACKAGE_ID]: _sandboxAlias, ...rest } = aliases;
|
|
3120
|
-
return rest;
|
|
3121
|
-
}
|
|
3122
|
-
function isSandboxSourceFile(file) {
|
|
3123
|
-
return /\.(?:c|m)?[jt]s$/i.test(file) && !/\.d\.(?:c|m)?[jt]s$/i.test(file);
|
|
3124
|
-
}
|
|
3125
|
-
function isLocalSourceFile(file, rootDir) {
|
|
3126
|
-
if (!rootDir) return false;
|
|
3127
|
-
const path = normalize(relative(rootDir, file));
|
|
3128
|
-
return path !== "" && !path.startsWith("../") && !path.startsWith("/") && !path.startsWith("node_modules/") && !path.startsWith(".vitehub/");
|
|
3129
|
-
}
|
|
3130
|
-
function isSandboxProjectManifestUpdate(file, rootDir) {
|
|
3131
|
-
if (basename(file) !== "package.json" || !isLocalSourceFile(file, rootDir)) return false;
|
|
3132
|
-
const path = normalize(relative(rootDir, file));
|
|
3133
|
-
return /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(path);
|
|
3134
|
-
}
|
|
3135
|
-
function isSandboxProjectFileUpdate(file, rootDir) {
|
|
3136
|
-
if (!isLocalSourceFile(file, rootDir)) return false;
|
|
3137
|
-
const path = normalize(relative(rootDir, file));
|
|
3138
|
-
return /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(path) || /^(?:pnpm-workspace\.yaml|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lock)$/.test(path);
|
|
3139
|
-
}
|
|
3140
|
-
function isSandboxDefinitionUpdate(file, definitions, generatedFiles, watchFiles, rootDir) {
|
|
3141
|
-
const changedFile = normalize(file);
|
|
3142
|
-
if (definitions.some((definition) => normalize(definition.handler) === changedFile)) return true;
|
|
3143
|
-
if (generatedFiles.some((file) => normalize(file) === changedFile)) return false;
|
|
3144
|
-
if (watchFiles.some((file) => normalize(file) === changedFile)) return true;
|
|
3145
|
-
if (isSandboxProjectManifestUpdate(changedFile, rootDir)) return true;
|
|
3146
|
-
if (isSandboxProjectFileUpdate(changedFile, rootDir)) return true;
|
|
3147
|
-
if (isLocalSourceFile(changedFile, rootDir)) return true;
|
|
3148
|
-
if (!isSandboxSourceFile(changedFile)) return false;
|
|
3149
|
-
return /\.sandbox\.(?:c|m)?[jt]s$/i.test(changedFile) || /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(changedFile) || isLocalSourceFile(changedFile, rootDir);
|
|
3150
|
-
}
|
|
3151
|
-
function invalidateGeneratedSandboxModules(files, moduleGraph) {
|
|
3152
|
-
for (const file of new Set(files.map((file) => normalize(file)))) {
|
|
3153
|
-
const module = moduleGraph.getModuleById(file);
|
|
3154
|
-
if (module) moduleGraph.invalidateModule(module);
|
|
3155
|
-
}
|
|
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
|
-
}
|
|
3166
|
-
function hubSandbox(options) {
|
|
3167
|
-
const internalOptions = options;
|
|
3168
|
-
const integrationOptions = internalOptions ? publicSandboxOptions(internalOptions) : internalOptions;
|
|
3169
|
-
const mergeSandboxNoExternal = createNoExternalMerger("@vite-hub/sandbox");
|
|
3170
|
-
let generatedAliases = {};
|
|
3171
|
-
let generatedFiles = [];
|
|
3172
|
-
let watchFiles = [];
|
|
3173
|
-
let definitions = [];
|
|
3174
|
-
let rootDir;
|
|
3175
|
-
let sandboxStateModule;
|
|
3176
|
-
let rawConfig = {};
|
|
3177
|
-
let rawEnv = {
|
|
3178
|
-
command: "serve",
|
|
3179
|
-
mode: "development"
|
|
3180
|
-
};
|
|
3181
|
-
let resolvedConfig;
|
|
3182
|
-
let selectedProvider;
|
|
3183
|
-
let earlyNitroTarget;
|
|
3184
|
-
let earlyNitroSnapshot;
|
|
3185
|
-
let composedCloudflareEarly = false;
|
|
3186
|
-
let sandboxRuntimeRefresh = Promise.resolve();
|
|
3187
|
-
const sandboxNitroModule = (nitro) => {
|
|
3188
|
-
mergeSandboxNitroNoExternals(nitro.options, selectedProvider);
|
|
3189
|
-
if (selectedProvider) mergeSandboxNitroProviderAliases(nitro.options, generatedAliases);
|
|
3190
|
-
nitro.hooks.hook("build:before", () => {
|
|
3191
|
-
mergeSandboxNitroNoExternals(nitro.options, selectedProvider);
|
|
3192
|
-
if (selectedProvider) mergeSandboxNitroProviderAliases(nitro.options, generatedAliases);
|
|
3193
|
-
});
|
|
3194
|
-
};
|
|
3195
|
-
function cloneConfigValue(value) {
|
|
3196
|
-
if (Array.isArray(value)) return value.map(cloneConfigValue);
|
|
3197
|
-
if (isPlainRecord(value) && Object.getPrototypeOf(value) === Object.prototype) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cloneConfigValue(entry)]));
|
|
3198
|
-
return value;
|
|
3199
|
-
}
|
|
3200
|
-
async function prepareCurrentSandboxRuntime(writeArtifacts = true) {
|
|
3201
|
-
const prepared = await prepareSandboxRuntime({
|
|
3202
|
-
integrationOptions,
|
|
3203
|
-
userConfig: rawConfig,
|
|
3204
|
-
env: rawEnv,
|
|
3205
|
-
resolvedConfig,
|
|
3206
|
-
writeArtifacts
|
|
3207
|
-
});
|
|
3208
|
-
sandboxStateModule = prepared.stateModule;
|
|
3209
|
-
return prepared;
|
|
3210
|
-
}
|
|
3211
|
-
async function activateCurrentSandboxRuntime() {
|
|
3212
|
-
const prepared = await prepareCurrentSandboxRuntime();
|
|
3213
|
-
generatedAliases = prepared.aliases;
|
|
3214
|
-
generatedFiles = prepared.files;
|
|
3215
|
-
watchFiles = prepared.watchFiles;
|
|
3216
|
-
definitions = prepared.definitions;
|
|
3217
|
-
rootDir = prepared.rootDir;
|
|
3218
|
-
if (internalOptions?.providerImportAliases && internalOptions.providerImportSpecifier) {
|
|
3219
|
-
const facade = generatedAliases[SANDBOX_PACKAGE_ID];
|
|
3220
|
-
if (facade) {
|
|
3221
|
-
internalOptions.providerImportAliases[internalOptions.providerImportSpecifier] = facade;
|
|
3222
|
-
Object.assign(internalOptions.providerImportAliases, sandboxRuntimePackageAliases);
|
|
3223
|
-
} else {
|
|
3224
|
-
delete internalOptions.providerImportAliases[internalOptions.providerImportSpecifier];
|
|
3225
|
-
for (const specifier of Object.keys(sandboxRuntimePackageAliases)) delete internalOptions.providerImportAliases[specifier];
|
|
3226
|
-
}
|
|
3227
|
-
for (const specifier of sandboxProviderLoaderSpecifiers) {
|
|
3228
|
-
const providerLoader = generatedAliases[specifier];
|
|
3229
|
-
if (providerLoader) internalOptions.providerImportAliases[specifier] = providerLoader;
|
|
3230
|
-
else delete internalOptions.providerImportAliases[specifier];
|
|
3231
|
-
}
|
|
3232
|
-
}
|
|
3233
|
-
return prepared;
|
|
3234
|
-
}
|
|
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) {
|
|
3241
|
-
if (!prepared.cloudflare || !hasNitroConfigContext(config) || getHostingProvider(prepared.hosting) !== "cloudflare") return false;
|
|
3242
|
-
config.nitro = await configureCloudflareSandboxNitro(mutableSandboxNitroTarget(config.nitro), prepared.rootDir, prepared.cloudflare, finalizeWrangler);
|
|
3243
|
-
return true;
|
|
3244
|
-
}
|
|
3245
|
-
return {
|
|
3246
|
-
name: "@vite-hub/sandbox/vite",
|
|
3247
|
-
enforce: "pre",
|
|
3248
|
-
nitro: {
|
|
3249
|
-
name: "@vite-hub/sandbox/provider-runtime",
|
|
3250
|
-
setup: sandboxNitroModule
|
|
3251
|
-
},
|
|
3252
|
-
async config(config, env) {
|
|
3253
|
-
rawConfig = config;
|
|
3254
|
-
rawEnv = env;
|
|
3255
|
-
const prepared = await prepareCurrentSandboxRuntime(false);
|
|
3256
|
-
generatedAliases = prepared.aliases;
|
|
3257
|
-
generatedFiles = prepared.files;
|
|
3258
|
-
watchFiles = prepared.watchFiles;
|
|
3259
|
-
definitions = prepared.definitions;
|
|
3260
|
-
rootDir = prepared.rootDir;
|
|
3261
|
-
selectedProvider = prepared.provider;
|
|
3262
|
-
const nitro = config.nitro;
|
|
3263
|
-
if (isPlainObject$1(nitro)) {
|
|
3264
|
-
earlyNitroTarget = nitro;
|
|
3265
|
-
earlyNitroSnapshot = cloneConfigValue(earlyNitroTarget);
|
|
3266
|
-
}
|
|
3267
|
-
composedCloudflareEarly = await composeCloudflareSandbox(config, prepared);
|
|
3268
|
-
return { resolve: { alias: toSandboxAliasEntries({
|
|
3269
|
-
[SANDBOX_PROVIDER_LOADER_ID]: sandboxProviderLoaderFallback(),
|
|
3270
|
-
...withoutSandboxPackageAlias(generatedAliases)
|
|
3271
|
-
}) } };
|
|
3272
|
-
},
|
|
3273
|
-
resolveId(id) {
|
|
3274
|
-
if (!sandboxStateModule) return;
|
|
3275
|
-
if (id === SANDBOX_STATE_ID) return RESOLVED_SANDBOX_STATE_ID;
|
|
3276
|
-
if (id === RESOLVED_SANDBOX_STATE_ID) return id;
|
|
3277
|
-
},
|
|
3278
|
-
load(id) {
|
|
3279
|
-
if (id === SANDBOX_STATE_ID || id === RESOLVED_SANDBOX_STATE_ID) return sandboxStateModule;
|
|
3280
|
-
},
|
|
3281
|
-
async configResolved(config) {
|
|
3282
|
-
resolvedConfig = config;
|
|
3283
|
-
const prepared = await refreshSandboxRuntime();
|
|
3284
|
-
selectedProvider = prepared.provider;
|
|
3285
|
-
if (!await composeCloudflareSandbox(config, prepared, true) && composedCloudflareEarly && earlyNitroTarget && earlyNitroSnapshot) for (const key of ["cloudflare", "rollupConfig"]) if (key in earlyNitroSnapshot) earlyNitroTarget[key] = earlyNitroSnapshot[key];
|
|
3286
|
-
else delete earlyNitroTarget[key];
|
|
3287
|
-
},
|
|
3288
|
-
async handleHotUpdate(context) {
|
|
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
|
-
});
|
|
3306
|
-
},
|
|
3307
|
-
configEnvironment(name, config) {
|
|
3308
|
-
const result = config.consumer === "server" ? { define: { __VITEHUB_ENVIRONMENT_SANDBOX__: JSON.stringify(name) } } : void 0;
|
|
3309
|
-
if (!isServerEnvironment(name, config)) return result;
|
|
3310
|
-
return {
|
|
3311
|
-
...result,
|
|
3312
|
-
resolve: {
|
|
3313
|
-
alias: toSandboxAliasEntries({
|
|
3314
|
-
[SANDBOX_PROVIDER_LOADER_ID]: sandboxProviderLoaderFallback(),
|
|
3315
|
-
...generatedAliases
|
|
3316
|
-
}),
|
|
3317
|
-
noExternal: mergeSandboxNoExternal(config.resolve?.noExternal)
|
|
3318
|
-
}
|
|
3319
|
-
};
|
|
3320
|
-
}
|
|
3321
|
-
};
|
|
3322
|
-
}
|
|
3323
|
-
//#endregion
|
|
3324
|
-
export { discoverSandboxDefinitions, hubSandbox };
|