@vite-hub/sandbox 0.0.1 → 0.0.2
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 +35 -37
- package/dist/cloudflare-env-2NctU8i7.js +12 -0
- package/dist/index-DiH4OGAU.d.ts +101 -0
- package/dist/index.d.ts +23 -32
- package/dist/index.js +688 -265
- package/dist/module-types-Cjqo67ay.d.ts +91 -0
- package/dist/provider-loader-3ml65ZFy.d.ts +21 -0
- package/dist/runtime/provider-loader.d.ts +2 -17
- package/dist/runtime/provider-loader.js +4 -10
- package/dist/runtime/providers/cloudflare.d.ts +6 -11
- package/dist/runtime/providers/cloudflare.js +14 -11
- package/dist/runtime/providers/vercel.d.ts +5 -12
- package/dist/runtime/providers/vercel.js +16 -30
- package/dist/runtime/state.d.ts +1 -1
- package/dist/vite.d.ts +12 -28
- package/dist/vite.js +2276 -354
- package/package.json +68 -59
- package/dist/_shared-CJ2_pS4E.js +0 -53
- package/dist/cloudflare-retry-Cfra7MvS.js +0 -21
- package/dist/common-CS4FcWrh.d.ts +0 -369
- package/dist/index-B4j3Mvzr.d.ts +0 -146
- package/dist/integration-wkNE8jMO.js +0 -2032
- package/dist/module-types-CUcY8iuI.d.ts +0 -88
- package/dist/nitro.d.ts +0 -19
- package/dist/nitro.js +0 -488
- package/dist/provider-detection-IbezCeoR.js +0 -25
- package/dist/runtime/nitro-plugin.d.ts +0 -4
- package/dist/runtime/nitro-plugin.js +0 -8
- package/dist/sandbox/providers/cloudflare.d.ts +0 -7
- package/dist/sandbox/providers/cloudflare.js +0 -339
- package/dist/sandbox/providers/vercel.d.ts +0 -17
- package/dist/sandbox/providers/vercel.js +0 -538
- package/dist/shared-pqTHYWg1.d.ts +0 -8
- package/dist/utils-V7ODsDW_.js +0 -44
- package/dist/vercel-runtime-BPzvh_6V.js +0 -11
- /package/dist/{module-types-BomzaqnM.js → module-types-Dj1MFmHT.js} +0 -0
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import { g as VercelSandboxProviderOptions, t as CloudflareSandboxOptions } from "./common-CS4FcWrh.js";
|
|
2
|
-
|
|
3
|
-
//#region src/internal/shared/errors.d.ts
|
|
4
|
-
interface VitehubErrorMetadata {
|
|
5
|
-
code?: string;
|
|
6
|
-
provider?: string;
|
|
7
|
-
method?: string;
|
|
8
|
-
httpStatus?: number;
|
|
9
|
-
upstreamError?: unknown;
|
|
10
|
-
details?: Record<string, unknown>;
|
|
11
|
-
cause?: unknown;
|
|
12
|
-
}
|
|
13
|
-
declare class VitehubError extends Error {
|
|
14
|
-
readonly code?: string;
|
|
15
|
-
readonly provider?: string;
|
|
16
|
-
readonly method?: string;
|
|
17
|
-
readonly httpStatus?: number;
|
|
18
|
-
readonly upstreamError?: unknown;
|
|
19
|
-
readonly details?: Record<string, unknown>;
|
|
20
|
-
readonly cause?: unknown;
|
|
21
|
-
constructor(message: string, metadata?: string | VitehubErrorMetadata);
|
|
22
|
-
}
|
|
23
|
-
//#endregion
|
|
24
|
-
//#region src/sandbox/errors.d.ts
|
|
25
|
-
declare class SandboxError extends VitehubError {
|
|
26
|
-
constructor(message: string, metadata?: string | VitehubErrorMetadata);
|
|
27
|
-
}
|
|
28
|
-
//#endregion
|
|
29
|
-
//#region src/module-types.d.ts
|
|
30
|
-
interface CloudflareSandboxDefinitionProviderOptions {
|
|
31
|
-
provider: 'cloudflare';
|
|
32
|
-
binding?: string;
|
|
33
|
-
className?: string;
|
|
34
|
-
migrationTag?: string;
|
|
35
|
-
name?: string;
|
|
36
|
-
sandboxId?: string;
|
|
37
|
-
sleepAfter?: CloudflareSandboxOptions['sleepAfter'];
|
|
38
|
-
keepAlive?: CloudflareSandboxOptions['keepAlive'];
|
|
39
|
-
normalizeId?: CloudflareSandboxOptions['normalizeId'];
|
|
40
|
-
}
|
|
41
|
-
type SandboxDefinitionProviderOptions = VercelSandboxProviderOptions | CloudflareSandboxDefinitionProviderOptions;
|
|
42
|
-
type AgentSandboxConfig = SandboxDefinitionProviderOptions | {
|
|
43
|
-
provider?: undefined;
|
|
44
|
-
name?: string;
|
|
45
|
-
};
|
|
46
|
-
interface SandboxDefinitionRuntime {
|
|
47
|
-
command: string;
|
|
48
|
-
args?: string[];
|
|
49
|
-
}
|
|
50
|
-
interface SandboxDefinitionBundle {
|
|
51
|
-
entry: string;
|
|
52
|
-
modules: Record<string, string>;
|
|
53
|
-
}
|
|
54
|
-
interface SandboxExecutionOptions {
|
|
55
|
-
context?: Record<string, unknown>;
|
|
56
|
-
sandboxId?: string;
|
|
57
|
-
}
|
|
58
|
-
type SandboxDefinitionHandler<TPayload = unknown, TResult = unknown> = (payload?: TPayload, context?: Record<string, unknown>) => TResult | Promise<TResult>;
|
|
59
|
-
type SandboxDefinitionPayload<THandler extends (...args: any[]) => any> = Parameters<THandler> extends [infer TPayload, ...unknown[]] ? TPayload : unknown;
|
|
60
|
-
type SandboxDefinitionResult<THandler extends (...args: any[]) => any> = Awaited<ReturnType<THandler>>;
|
|
61
|
-
interface SandboxDefinitionOptions {
|
|
62
|
-
timeout?: number;
|
|
63
|
-
env?: Record<string, string>;
|
|
64
|
-
runtime?: SandboxDefinitionRuntime;
|
|
65
|
-
}
|
|
66
|
-
interface SandboxDefinition<TPayload = unknown, TResult = unknown> {
|
|
67
|
-
run: SandboxDefinitionHandler<TPayload, TResult>;
|
|
68
|
-
options?: SandboxDefinitionOptions;
|
|
69
|
-
}
|
|
70
|
-
type SandboxDefinitionFromHandler<THandler extends (...args: any[]) => any> = SandboxDefinition<SandboxDefinitionPayload<THandler>, SandboxDefinitionResult<THandler>> & {
|
|
71
|
-
run: THandler;
|
|
72
|
-
};
|
|
73
|
-
interface SandboxOkResult<TResult = unknown> {
|
|
74
|
-
isOk: () => true;
|
|
75
|
-
isErr: () => false;
|
|
76
|
-
value: TResult;
|
|
77
|
-
error?: never;
|
|
78
|
-
}
|
|
79
|
-
interface SandboxErrResult {
|
|
80
|
-
isOk: () => false;
|
|
81
|
-
isErr: () => true;
|
|
82
|
-
value?: never;
|
|
83
|
-
error: SandboxError;
|
|
84
|
-
}
|
|
85
|
-
type SandboxRunResult<TResult = unknown> = SandboxOkResult<TResult> | SandboxErrResult;
|
|
86
|
-
declare function getSandboxFeatureProvider(config?: AgentSandboxConfig | false): SandboxDefinitionProviderOptions | undefined;
|
|
87
|
-
//#endregion
|
|
88
|
-
export { SandboxDefinitionFromHandler as a, SandboxDefinitionProviderOptions as c, SandboxExecutionOptions as d, SandboxOkResult as f, SandboxError as h, SandboxDefinitionBundle as i, SandboxDefinitionRuntime as l, getSandboxFeatureProvider as m, CloudflareSandboxDefinitionProviderOptions as n, SandboxDefinitionHandler as o, SandboxRunResult as p, SandboxDefinition as r, SandboxDefinitionOptions as s, AgentSandboxConfig as t, SandboxErrResult as u };
|
package/dist/nitro.d.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { t as AgentSandboxConfig } from "./module-types-CUcY8iuI.js";
|
|
2
|
-
import { NitroModule } from "nitro/types";
|
|
3
|
-
|
|
4
|
-
//#region src/nitro/module.d.ts
|
|
5
|
-
declare const sandboxNitroModule: NitroModule;
|
|
6
|
-
declare module 'nitro/types' {
|
|
7
|
-
interface NitroConfig {
|
|
8
|
-
sandbox?: false | AgentSandboxConfig;
|
|
9
|
-
}
|
|
10
|
-
interface NitroOptions {
|
|
11
|
-
sandbox?: false | AgentSandboxConfig;
|
|
12
|
-
}
|
|
13
|
-
interface NitroRuntimeConfig {
|
|
14
|
-
hosting?: string;
|
|
15
|
-
sandbox?: false | AgentSandboxConfig;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
//#endregion
|
|
19
|
-
export { sandboxNitroModule as default };
|
package/dist/nitro.js
DELETED
|
@@ -1,488 +0,0 @@
|
|
|
1
|
-
import { t as getSandboxFeatureProvider } from "./module-types-BomzaqnM.js";
|
|
2
|
-
import { D as applyServerImportsToNitro, E as createDiscoveredDefinitionCompiler, S as getSupportedHostingProvider, T as tryResolveModule, _ as defaultCloudflareSandboxClassName, a as ensureNitroImports, b as bundleSandboxDefinition, d as resolveSandboxProviderLoaderTarget, f as sandboxRuntimeDependencies, g as defaultCloudflareSandboxBinding, h as configureCloudflareSandbox, i as resolveEffectiveViteHubServerImports, l as resolveRuntimeEntry$1, m as extractSandboxDefinitionOptions, p as sandboxRuntimeDependencyByProvider, t as normalizeSandboxPublicOptions, u as createSandboxProviderLoaderContents, v as installCloudflareSandboxEntrypoint, w as hasInstalledDependency, x as detectHosting, y as writeCloudflareSandboxDockerfile } from "./integration-wkNE8jMO.js";
|
|
3
|
-
import { dirname, relative, resolve } from "pathe";
|
|
4
|
-
import { readPackageJSON } from "pkg-types";
|
|
5
|
-
import { readdirSync, realpathSync } from "node:fs";
|
|
6
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
7
|
-
import "node:url";
|
|
8
|
-
import { resolve as resolve$1 } from "node:path";
|
|
9
|
-
//#region ../internal/src/build/paths.ts
|
|
10
|
-
function generatedDirSegments(productName) {
|
|
11
|
-
return [".vitehub", productName];
|
|
12
|
-
}
|
|
13
|
-
function createImportPath(fromFile, targetFile) {
|
|
14
|
-
const importPath = relative(realpathIfExists(dirname(fromFile)), realpathIfExists(targetFile));
|
|
15
|
-
return importPath.startsWith(".") ? importPath : `./${importPath}`;
|
|
16
|
-
}
|
|
17
|
-
function realpathIfExists(path) {
|
|
18
|
-
try {
|
|
19
|
-
return realpathSync.native(path);
|
|
20
|
-
} catch {
|
|
21
|
-
return resolve(path);
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
//#endregion
|
|
25
|
-
//#region ../internal/src/definition-catalog.ts
|
|
26
|
-
const sourceFilePattern = /\.(?:c|m)?[jt]s$/i;
|
|
27
|
-
const declarationFilePattern = /\.d\.(?:c|m)?[jt]s$/i;
|
|
28
|
-
const ignoredDirs = new Set([
|
|
29
|
-
"node_modules",
|
|
30
|
-
"dist",
|
|
31
|
-
".nitro",
|
|
32
|
-
".output",
|
|
33
|
-
".nuxt",
|
|
34
|
-
".vercel",
|
|
35
|
-
".git",
|
|
36
|
-
".vitehub"
|
|
37
|
-
]);
|
|
38
|
-
function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
|
|
39
|
-
return {
|
|
40
|
-
...options,
|
|
41
|
-
kind: "directory",
|
|
42
|
-
scanDirs,
|
|
43
|
-
source,
|
|
44
|
-
subdir
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
function readDirEntries(root) {
|
|
48
|
-
try {
|
|
49
|
-
return readdirSync(root, { withFileTypes: true });
|
|
50
|
-
} catch (error) {
|
|
51
|
-
if (error.code === "ENOENT") return [];
|
|
52
|
-
throw error;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
function listMatchingFiles(root, predicate, options = {}) {
|
|
56
|
-
const files = [];
|
|
57
|
-
for (const entry of readDirEntries(root)) {
|
|
58
|
-
const absolute = resolve(root, entry.name);
|
|
59
|
-
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
60
|
-
if (entry.name.startsWith(".")) continue;
|
|
61
|
-
if (ignoredDirs.has(entry.name)) continue;
|
|
62
|
-
files.push(...listMatchingFiles(absolute, predicate, options));
|
|
63
|
-
continue;
|
|
64
|
-
}
|
|
65
|
-
if (entry.name.startsWith(".") && !options.includeHidden) continue;
|
|
66
|
-
if (entry.isFile() && predicate(entry.name)) files.push(absolute);
|
|
67
|
-
}
|
|
68
|
-
return files.sort();
|
|
69
|
-
}
|
|
70
|
-
function listSourceFiles(root, options = {}) {
|
|
71
|
-
return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
|
|
72
|
-
}
|
|
73
|
-
function normalizePathDefinitionName(rootDir, file) {
|
|
74
|
-
return relative(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
|
|
75
|
-
}
|
|
76
|
-
function sanitizeDefinitionFilename(name) {
|
|
77
|
-
let result = "";
|
|
78
|
-
for (const char of name) if (/[a-z0-9-]/i.test(char)) result += char;
|
|
79
|
-
else if (char === "_") result += "__";
|
|
80
|
-
else if (char === "/") result += "_s";
|
|
81
|
-
else if (char === ":") result += "_c";
|
|
82
|
-
else result += `_x${char.charCodeAt(0).toString(16).padStart(4, "0")}`;
|
|
83
|
-
return result;
|
|
84
|
-
}
|
|
85
|
-
function sortDefinitions(definitions) {
|
|
86
|
-
return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
87
|
-
}
|
|
88
|
-
function registerDefinition(definitions, definition, sourceLabel) {
|
|
89
|
-
const existing = definitions.get(definition.name);
|
|
90
|
-
if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
|
|
91
|
-
definitions.set(definition.name, definition);
|
|
92
|
-
}
|
|
93
|
-
function mergeDefinitions(feature, ...sources) {
|
|
94
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
95
|
-
for (const source of sources) {
|
|
96
|
-
if (!source) continue;
|
|
97
|
-
for (const definition of source) {
|
|
98
|
-
const existing = definitions.get(definition.name);
|
|
99
|
-
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"})`);
|
|
100
|
-
if (!existing) definitions.set(definition.name, definition);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
return sortDefinitions(definitions);
|
|
104
|
-
}
|
|
105
|
-
function createDefinition(source, file, name) {
|
|
106
|
-
if (source.createDefinition) return source.createDefinition({
|
|
107
|
-
file,
|
|
108
|
-
name
|
|
109
|
-
});
|
|
110
|
-
return {
|
|
111
|
-
handler: file,
|
|
112
|
-
name,
|
|
113
|
-
source: source.source
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
function scanSuffixDefinitions(feature, source) {
|
|
117
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
118
|
-
for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
|
|
119
|
-
const name = source.normalizeName(root, file);
|
|
120
|
-
if (!name) continue;
|
|
121
|
-
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
122
|
-
}
|
|
123
|
-
return sortDefinitions(definitions);
|
|
124
|
-
}
|
|
125
|
-
function scanDirectoryDefinitions(feature, source) {
|
|
126
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
127
|
-
for (const scanDir of source.scanDirs) {
|
|
128
|
-
const directory = resolve(scanDir, source.subdir);
|
|
129
|
-
for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
|
|
130
|
-
const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
|
|
131
|
-
if (!name) continue;
|
|
132
|
-
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
return sortDefinitions(definitions);
|
|
136
|
-
}
|
|
137
|
-
function discoverDefinitions(feature, sources) {
|
|
138
|
-
return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
|
|
139
|
-
}
|
|
140
|
-
function createImportExpression(registryFile, file) {
|
|
141
|
-
const importPath = relative(resolve(registryFile, ".."), file);
|
|
142
|
-
return `import(${JSON.stringify(importPath.startsWith(".") ? importPath : `./${importPath}`)})`;
|
|
143
|
-
}
|
|
144
|
-
function createRuntimeRegistryContents(registryFile, definitions) {
|
|
145
|
-
const needsWorkflowRuntime = definitions.some((definition) => definition.steps?.length);
|
|
146
|
-
const runtimeImport = needsWorkflowRuntime ? [`import { createWorkflowSteps } from "@vite-hub/workflow/runtime/execute"`, `import { takeInlineWorkflowDefinitionForModule } from "@vite-hub/workflow/runtime/state"`] : [];
|
|
147
|
-
const imports = definitions.map((definition) => {
|
|
148
|
-
if (!definition.steps?.length) return ` ${JSON.stringify(definition.name)}: async () => ${createImportExpression(registryFile, definition.handler)},`;
|
|
149
|
-
const workflowDirectory = /\.(?:c|m)?[jt]s$/i.test(definition.handler) ? dirname(definition.handler) : definition.handler;
|
|
150
|
-
const stepImports = definition.steps.map((step) => {
|
|
151
|
-
const stepName = relative(workflowDirectory, step);
|
|
152
|
-
return `{ name: ${JSON.stringify(stepName)}, run: (await ${createImportExpression(registryFile, step)}).default }`;
|
|
153
|
-
});
|
|
154
|
-
const hasIndex = /\.(?:c|m)?[jt]s$/i.test(definition.handler);
|
|
155
|
-
const indexImport = hasIndex ? `const index = await ${createImportExpression(registryFile, definition.handler)}` : "";
|
|
156
|
-
const handler = hasIndex ? `index.default?.handler ? index.default : takeInlineWorkflowDefinitionForModule(${JSON.stringify(definition.name)}, index) || { handler: index.default }` : "{ handler: async (context) => { let value = context.payload; for (const step of Object.values(context.steps || {})) value = await step(value); return value } }";
|
|
157
|
-
return [
|
|
158
|
-
` ${JSON.stringify(definition.name)}: async () => {`,
|
|
159
|
-
` const cached = registryEntryCache.get(${JSON.stringify(definition.name)})`,
|
|
160
|
-
" if (cached) return cached",
|
|
161
|
-
indexImport ? ` ${indexImport}` : "",
|
|
162
|
-
` const steps = [${stepImports.join(", ")}]`,
|
|
163
|
-
` const definition = ${handler}`,
|
|
164
|
-
" const entry = {",
|
|
165
|
-
" ...definition,",
|
|
166
|
-
" options: { ...definition.options, rootStep: false },",
|
|
167
|
-
" handler: async (context) => {",
|
|
168
|
-
" const workflowSteps = createWorkflowSteps(context, steps)",
|
|
169
|
-
" return await definition.handler({ ...context, steps: workflowSteps })",
|
|
170
|
-
" },",
|
|
171
|
-
" }",
|
|
172
|
-
` registryEntryCache.set(${JSON.stringify(definition.name)}, entry)`,
|
|
173
|
-
" return entry",
|
|
174
|
-
" },"
|
|
175
|
-
].filter(Boolean).join("\n");
|
|
176
|
-
});
|
|
177
|
-
return [
|
|
178
|
-
...runtimeImport,
|
|
179
|
-
runtimeImport.length ? "" : "",
|
|
180
|
-
...needsWorkflowRuntime ? ["const registryEntryCache = new Map()", ""] : [],
|
|
181
|
-
"const registry = {",
|
|
182
|
-
...imports,
|
|
183
|
-
"}",
|
|
184
|
-
"",
|
|
185
|
-
"export default registry",
|
|
186
|
-
""
|
|
187
|
-
].join("\n");
|
|
188
|
-
}
|
|
189
|
-
function createGeneratedDefinitionPath(rootDir, options) {
|
|
190
|
-
const segments = options.segments ?? generatedDirSegments(options.productName);
|
|
191
|
-
return resolve(...options.buildDir ? [
|
|
192
|
-
rootDir,
|
|
193
|
-
options.buildDir,
|
|
194
|
-
...segments,
|
|
195
|
-
options.fileName
|
|
196
|
-
] : [
|
|
197
|
-
rootDir,
|
|
198
|
-
...segments,
|
|
199
|
-
options.fileName
|
|
200
|
-
]);
|
|
201
|
-
}
|
|
202
|
-
function createNitroRuntimeFilePath(rootDir, options) {
|
|
203
|
-
return createGeneratedDefinitionPath(rootDir, options);
|
|
204
|
-
}
|
|
205
|
-
async function writeRuntimeRegistryFiles(options) {
|
|
206
|
-
await Promise.all([writeFileIfChanged(options.registryFile, createRuntimeRegistryContents(options.registryFile, options.definitions)), writeFileIfChanged(options.pluginFile, options.createPluginContents(options.pluginFile, options.registryFile))]);
|
|
207
|
-
return {
|
|
208
|
-
definitions: options.definitions,
|
|
209
|
-
pluginFile: options.pluginFile,
|
|
210
|
-
registryFile: options.registryFile
|
|
211
|
-
};
|
|
212
|
-
}
|
|
213
|
-
function hookNitroRuntimeRegistryRefresh(nitro, refresh, onRefresh = () => {}) {
|
|
214
|
-
for (const hookName of ["build:before", "dev:reload"]) nitro.hooks.hook(hookName, async () => {
|
|
215
|
-
await onRefresh(await refresh(), hookName);
|
|
216
|
-
});
|
|
217
|
-
}
|
|
218
|
-
async function writeFileIfChanged(file, contents) {
|
|
219
|
-
if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
|
|
220
|
-
await mkdir(resolve(file, ".."), { recursive: true });
|
|
221
|
-
await writeFile(file, contents, "utf8");
|
|
222
|
-
}
|
|
223
|
-
//#endregion
|
|
224
|
-
//#region src/nitro/sandbox-config.ts
|
|
225
|
-
function resolveNitroSandboxScanDirs(rootDir, scanDirs) {
|
|
226
|
-
return scanDirs?.length ? scanDirs : [resolve$1(rootDir, "server")];
|
|
227
|
-
}
|
|
228
|
-
function resolveSandboxConfig(config, hosting) {
|
|
229
|
-
if (getSandboxFeatureProvider(config)?.provider) return { ...config };
|
|
230
|
-
const inferred = getSupportedHostingProvider(hosting, ["cloudflare", "vercel"]);
|
|
231
|
-
if (!inferred) return { ...config };
|
|
232
|
-
return {
|
|
233
|
-
...config,
|
|
234
|
-
provider: inferred
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
function assignSandboxRuntimeConfig(runtimeConfig, config) {
|
|
238
|
-
const provider = getSandboxFeatureProvider(config);
|
|
239
|
-
if (provider?.provider === "vercel") {
|
|
240
|
-
runtimeConfig.sandbox = {
|
|
241
|
-
...config,
|
|
242
|
-
token: provider.token ?? "",
|
|
243
|
-
teamId: provider.teamId ?? "",
|
|
244
|
-
projectId: provider.projectId ?? ""
|
|
245
|
-
};
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
runtimeConfig.sandbox = config;
|
|
249
|
-
}
|
|
250
|
-
function normalizeSandboxDefinitionOptions(name, options) {
|
|
251
|
-
if (!options) return void 0;
|
|
252
|
-
try {
|
|
253
|
-
return JSON.parse(JSON.stringify(options));
|
|
254
|
-
} catch (error) {
|
|
255
|
-
throw new Error(`[vitehub] Sandbox definition "${name}" options must be JSON-serializable.`, { cause: error });
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
//#endregion
|
|
259
|
-
//#region src/discovery.ts
|
|
260
|
-
function discoverNitroSandboxDefinitions(scanDirs) {
|
|
261
|
-
return discoverDefinitions("sandbox", [createDirectoryDefinitionSource("nitro-server-sandboxes", scanDirs, "sandboxes", { createDefinition({ file, name }) {
|
|
262
|
-
return {
|
|
263
|
-
handler: file,
|
|
264
|
-
name,
|
|
265
|
-
source: "nitro-server-sandboxes",
|
|
266
|
-
_meta: {
|
|
267
|
-
filename: name,
|
|
268
|
-
sourcePath: file
|
|
269
|
-
}
|
|
270
|
-
};
|
|
271
|
-
} })]);
|
|
272
|
-
}
|
|
273
|
-
//#endregion
|
|
274
|
-
//#region src/nitro/runtime-files.ts
|
|
275
|
-
const sandboxGeneratedDir = generatedDirSegments("sandbox");
|
|
276
|
-
function createNitroSandboxRegistryPath(rootDir, buildDir) {
|
|
277
|
-
return createNitroRuntimeFilePath(rootDir, {
|
|
278
|
-
buildDir,
|
|
279
|
-
fileName: "nitro-registry.mjs",
|
|
280
|
-
segments: sandboxGeneratedDir
|
|
281
|
-
});
|
|
282
|
-
}
|
|
283
|
-
function createNitroSandboxPluginPath(rootDir, buildDir) {
|
|
284
|
-
return createNitroRuntimeFilePath(rootDir, {
|
|
285
|
-
buildDir,
|
|
286
|
-
fileName: "nitro-plugin.ts",
|
|
287
|
-
segments: sandboxGeneratedDir
|
|
288
|
-
});
|
|
289
|
-
}
|
|
290
|
-
function createNitroSandboxDefinitionPath(rootDir, buildDir, name) {
|
|
291
|
-
return createNitroRuntimeFilePath(rootDir, {
|
|
292
|
-
buildDir,
|
|
293
|
-
fileName: `definitions/${sanitizeDefinitionFilename(name)}.mjs`,
|
|
294
|
-
segments: sandboxGeneratedDir
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
function createNitroSandboxPluginContents(file, registryFile) {
|
|
298
|
-
return [
|
|
299
|
-
"import { definePlugin as defineNitroPlugin } from \"nitro\"",
|
|
300
|
-
"import { useRuntimeConfig } from \"nitro/runtime-config\"",
|
|
301
|
-
"import type { AgentSandboxConfig } from \"@vite-hub/sandbox\"",
|
|
302
|
-
"import { setSandboxRuntimeConfig, setSandboxRuntimeRegistry } from \"@vite-hub/sandbox/runtime/state\"",
|
|
303
|
-
"",
|
|
304
|
-
`import sandboxRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
|
|
305
|
-
"",
|
|
306
|
-
"const sandboxNitroPlugin: ReturnType<typeof defineNitroPlugin> = defineNitroPlugin((nitroApp: any) => {",
|
|
307
|
-
" const applyRuntimeState = () => {",
|
|
308
|
-
" const runtimeConfig = useRuntimeConfig() as { sandbox?: false | AgentSandboxConfig }",
|
|
309
|
-
" setSandboxRuntimeConfig(runtimeConfig.sandbox)",
|
|
310
|
-
" setSandboxRuntimeRegistry(sandboxRegistry)",
|
|
311
|
-
" }",
|
|
312
|
-
"",
|
|
313
|
-
" applyRuntimeState()",
|
|
314
|
-
"",
|
|
315
|
-
" nitroApp.hooks.hook(\"request\", () => {",
|
|
316
|
-
" applyRuntimeState()",
|
|
317
|
-
" })",
|
|
318
|
-
"})",
|
|
319
|
-
"",
|
|
320
|
-
"export default sandboxNitroPlugin",
|
|
321
|
-
""
|
|
322
|
-
].join("\n");
|
|
323
|
-
}
|
|
324
|
-
async function createNitroSandboxDefinitionContents(definition, compiler) {
|
|
325
|
-
const bundle = await bundleSandboxDefinition(await compiler.readSource(definition._meta.sourcePath), definition._meta.sourcePath);
|
|
326
|
-
const options = normalizeSandboxDefinitionOptions(definition.name, await extractSandboxDefinitionOptions(definition.handler));
|
|
327
|
-
return `export default ${JSON.stringify({
|
|
328
|
-
bundle,
|
|
329
|
-
options
|
|
330
|
-
})}\n`;
|
|
331
|
-
}
|
|
332
|
-
async function writeNitroSandboxRuntimeFiles(nitro) {
|
|
333
|
-
const registryFile = createNitroSandboxRegistryPath(nitro.options.rootDir, nitro.options.buildDir);
|
|
334
|
-
const pluginFile = createNitroSandboxPluginPath(nitro.options.rootDir, nitro.options.buildDir);
|
|
335
|
-
const definitions = discoverNitroSandboxDefinitions(resolveNitroSandboxScanDirs(nitro.options.rootDir, nitro.options.scanDirs));
|
|
336
|
-
const compiler = await createDiscoveredDefinitionCompiler({
|
|
337
|
-
rootDir: nitro.options.rootDir,
|
|
338
|
-
scanRoots: [nitro.options.rootDir],
|
|
339
|
-
nitroImports: nitro.options.imports,
|
|
340
|
-
featureImports: resolveEffectiveViteHubServerImports(nitro.options, "sandbox")
|
|
341
|
-
});
|
|
342
|
-
const registryDefinitions = [];
|
|
343
|
-
await mkdir(resolve$1(registryFile, ".."), { recursive: true });
|
|
344
|
-
await Promise.all(definitions.map(async (definition) => {
|
|
345
|
-
const file = createNitroSandboxDefinitionPath(nitro.options.rootDir, nitro.options.buildDir, definition.name);
|
|
346
|
-
await writeFileIfChanged(file, await createNitroSandboxDefinitionContents(definition, compiler));
|
|
347
|
-
registryDefinitions.push({
|
|
348
|
-
handler: file,
|
|
349
|
-
name: definition.name
|
|
350
|
-
});
|
|
351
|
-
}));
|
|
352
|
-
registryDefinitions.sort((left, right) => left.name.localeCompare(right.name));
|
|
353
|
-
await writeRuntimeRegistryFiles({
|
|
354
|
-
createPluginContents: createNitroSandboxPluginContents,
|
|
355
|
-
definitions: registryDefinitions,
|
|
356
|
-
pluginFile,
|
|
357
|
-
registryFile
|
|
358
|
-
});
|
|
359
|
-
return {
|
|
360
|
-
definitions,
|
|
361
|
-
pluginFile,
|
|
362
|
-
registryFile
|
|
363
|
-
};
|
|
364
|
-
}
|
|
365
|
-
//#endregion
|
|
366
|
-
//#region src/nitro/setup.ts
|
|
367
|
-
function resolveRuntimeEntry(srcRelative, packageSubpath) {
|
|
368
|
-
return resolveRuntimeEntry$1(srcRelative, packageSubpath, import.meta.url);
|
|
369
|
-
}
|
|
370
|
-
function createSandboxProviderLoaderAliases(nitro, provider, deps) {
|
|
371
|
-
const providerLoaderTarget = resolveSandboxProviderLoaderTarget(provider ?? getSupportedHostingProvider(detectHosting(nitro), ["cloudflare", "vercel"]), deps);
|
|
372
|
-
const runtimeProviderLoaderPath = resolveRuntimeEntry("../runtime/provider-loader", "@vite-hub/sandbox/runtime/provider-loader");
|
|
373
|
-
const keys = [
|
|
374
|
-
"vitehub-sandbox-provider-loader",
|
|
375
|
-
"@vite-hub/sandbox/runtime/provider-loader",
|
|
376
|
-
"virtual:vitehub-sandbox-provider-loader",
|
|
377
|
-
"#vitehub-sandbox-provider-loader"
|
|
378
|
-
];
|
|
379
|
-
if (!providerLoaderTarget) return {
|
|
380
|
-
providerLoaderTarget,
|
|
381
|
-
aliases: keys.map((key) => ({
|
|
382
|
-
key,
|
|
383
|
-
value: runtimeProviderLoaderPath
|
|
384
|
-
}))
|
|
385
|
-
};
|
|
386
|
-
const providerLoaderPath = resolve$1(nitro.options.rootDir, nitro.options.buildDir, ...sandboxGeneratedDir, "provider-loader.mjs");
|
|
387
|
-
return {
|
|
388
|
-
providerLoaderTarget,
|
|
389
|
-
aliases: keys.map((key) => ({
|
|
390
|
-
key,
|
|
391
|
-
value: providerLoaderPath
|
|
392
|
-
})),
|
|
393
|
-
providerLoaderPath
|
|
394
|
-
};
|
|
395
|
-
}
|
|
396
|
-
function addSandboxAliases(nitro, aliases) {
|
|
397
|
-
nitro.options.alias ||= {};
|
|
398
|
-
for (const alias of aliases) nitro.options.alias[alias.key] = alias.value;
|
|
399
|
-
nitro.options.alias["@vite-hub/sandbox/runtime/state"] = resolveRuntimeEntry("../runtime/state", "@vite-hub/sandbox/runtime/state");
|
|
400
|
-
nitro.options.alias["#vitehub-sandbox-registry"] = resolveRuntimeEntry("../runtime/empty-registry", "@vite-hub/sandbox/runtime/empty-registry");
|
|
401
|
-
nitro.options.alias["@vite-hub/sandbox"] = resolveRuntimeEntry("../index", "@vite-hub/sandbox");
|
|
402
|
-
}
|
|
403
|
-
function addSandboxProviderLoaderResolver(nitro, aliases) {
|
|
404
|
-
const aliasMap = new Map(aliases.map((alias) => [alias.key, alias.value]));
|
|
405
|
-
if (aliasMap.size === 0) return;
|
|
406
|
-
nitro.hooks.hook("rollup:before", (_nitro, config) => {
|
|
407
|
-
config.plugins = [{
|
|
408
|
-
name: "vitehub:sandbox-provider-loader-resolver",
|
|
409
|
-
resolveId(id) {
|
|
410
|
-
return aliasMap.get(id);
|
|
411
|
-
}
|
|
412
|
-
}, ...Array.isArray(config.plugins) ? config.plugins : config.plugins ? [config.plugins] : []];
|
|
413
|
-
});
|
|
414
|
-
}
|
|
415
|
-
function addSandboxImports(nitro) {
|
|
416
|
-
ensureNitroImports(nitro);
|
|
417
|
-
applyServerImportsToNitro(nitro.options, resolveEffectiveViteHubServerImports(nitro.options, "sandbox"));
|
|
418
|
-
}
|
|
419
|
-
function extendSandboxNitro(nitro, config, deps, providerLoaderTarget) {
|
|
420
|
-
const defaultProvider = getSandboxFeatureProvider(config);
|
|
421
|
-
const cloudflareOptions = defaultProvider?.provider === "cloudflare" ? {
|
|
422
|
-
binding: typeof defaultProvider.binding === "string" ? defaultProvider.binding : defaultCloudflareSandboxBinding,
|
|
423
|
-
className: typeof defaultProvider.className === "string" ? defaultProvider.className : defaultCloudflareSandboxClassName,
|
|
424
|
-
migrationTag: typeof defaultProvider.migrationTag === "string" ? defaultProvider.migrationTag : "v1",
|
|
425
|
-
name: typeof defaultProvider.name === "string" ? defaultProvider.name : void 0
|
|
426
|
-
} : void 0;
|
|
427
|
-
if (cloudflareOptions) {
|
|
428
|
-
configureCloudflareSandbox(nitro.options, cloudflareOptions);
|
|
429
|
-
installCloudflareSandboxEntrypoint(nitro.options, cloudflareOptions);
|
|
430
|
-
}
|
|
431
|
-
const nitroOptions = nitro.options;
|
|
432
|
-
nitroOptions.externals ||= {};
|
|
433
|
-
nitroOptions.externals.inline ||= [];
|
|
434
|
-
nitroOptions.externals.traceInclude ||= [];
|
|
435
|
-
const runtimeDependencies = providerLoaderTarget ? [sandboxRuntimeDependencyByProvider[providerLoaderTarget]].filter(Boolean) : sandboxRuntimeDependencies;
|
|
436
|
-
for (const dependency of runtimeDependencies) {
|
|
437
|
-
if (!hasInstalledDependency(deps, dependency)) continue;
|
|
438
|
-
if (dependency !== "@vercel/sandbox" && !nitroOptions.externals.inline.includes(dependency)) nitroOptions.externals.inline.push(dependency);
|
|
439
|
-
const resolved = tryResolveModule(dependency);
|
|
440
|
-
if (resolved.ok && !nitroOptions.externals.traceInclude.includes(resolved.path)) nitroOptions.externals.traceInclude.push(resolved.path);
|
|
441
|
-
}
|
|
442
|
-
if (cloudflareOptions) nitro.hooks.hook("compiled", async () => {
|
|
443
|
-
await writeCloudflareSandboxDockerfile(nitro.options.output.serverDir);
|
|
444
|
-
});
|
|
445
|
-
}
|
|
446
|
-
//#endregion
|
|
447
|
-
//#region src/nitro/module.ts
|
|
448
|
-
async function readWorkspaceDeps(rootDir) {
|
|
449
|
-
const packageJson = await readPackageJSON(rootDir);
|
|
450
|
-
return {
|
|
451
|
-
...packageJson.dependencies,
|
|
452
|
-
...packageJson.devDependencies
|
|
453
|
-
};
|
|
454
|
-
}
|
|
455
|
-
const sandboxNitroModule = {
|
|
456
|
-
name: "@vite-hub/sandbox",
|
|
457
|
-
async setup(nitro) {
|
|
458
|
-
const normalized = normalizeSandboxPublicOptions(nitro.options.sandbox ?? {});
|
|
459
|
-
const runtimeConfig = nitro.options.runtimeConfig ||= {};
|
|
460
|
-
if (!normalized) {
|
|
461
|
-
runtimeConfig.sandbox = false;
|
|
462
|
-
return;
|
|
463
|
-
}
|
|
464
|
-
const hosting = detectHosting(nitro);
|
|
465
|
-
if (hosting) runtimeConfig.hosting ||= hosting;
|
|
466
|
-
const config = resolveSandboxConfig(normalized, hosting);
|
|
467
|
-
assignSandboxRuntimeConfig(runtimeConfig, config);
|
|
468
|
-
addSandboxImports(nitro);
|
|
469
|
-
const deps = await readWorkspaceDeps(nitro.options.rootDir);
|
|
470
|
-
let runtimeFiles = await writeNitroSandboxRuntimeFiles(nitro);
|
|
471
|
-
const provider = getSandboxFeatureProvider(config);
|
|
472
|
-
const providerLoader = createSandboxProviderLoaderAliases(nitro, provider?.provider, deps);
|
|
473
|
-
addSandboxAliases(nitro, providerLoader.aliases);
|
|
474
|
-
addSandboxProviderLoaderResolver(nitro, providerLoader.aliases);
|
|
475
|
-
if (providerLoader.providerLoaderPath && providerLoader.providerLoaderTarget) await writeFileIfChanged(providerLoader.providerLoaderPath, createSandboxProviderLoaderContents(providerLoader.providerLoaderTarget));
|
|
476
|
-
nitro.options.plugins ||= [];
|
|
477
|
-
if (!nitro.options.plugins.includes(runtimeFiles.pluginFile)) nitro.options.plugins.push(runtimeFiles.pluginFile);
|
|
478
|
-
extendSandboxNitro(nitro, config, deps, providerLoader.providerLoaderTarget);
|
|
479
|
-
hookNitroRuntimeRegistryRefresh(nitro, () => writeNitroSandboxRuntimeFiles(nitro), (nextRuntimeFiles) => {
|
|
480
|
-
runtimeFiles = nextRuntimeFiles;
|
|
481
|
-
});
|
|
482
|
-
if (provider?.provider === "vercel" && !hasInstalledDependency(deps, "@vercel/sandbox", { paths: [nitro.options.rootDir] })) nitro.logger.warn("Install `@vercel/sandbox` for Vercel sandbox presets.");
|
|
483
|
-
if (provider?.provider === "cloudflare" && !hasInstalledDependency(deps, "@cloudflare/sandbox", { paths: [nitro.options.rootDir] })) nitro.logger.warn("Install `@cloudflare/sandbox` for Cloudflare sandbox presets.");
|
|
484
|
-
nitro.logger.info(`@vite-hub/sandbox enabled with ${runtimeFiles.definitions.length} sandbox definition${runtimeFiles.definitions.length === 1 ? "" : "s"}`);
|
|
485
|
-
}
|
|
486
|
-
};
|
|
487
|
-
//#endregion
|
|
488
|
-
export { sandboxNitroModule as default };
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
//#region src/internal/shared/provider-detection.ts
|
|
2
|
-
function createProviderDetector(rules) {
|
|
3
|
-
return () => {
|
|
4
|
-
for (const rule of rules) if (rule.when()) return rule.provider;
|
|
5
|
-
};
|
|
6
|
-
}
|
|
7
|
-
function getRuntimeEnv() {
|
|
8
|
-
return typeof process !== "undefined" ? process.env : {};
|
|
9
|
-
}
|
|
10
|
-
const isCloudflare = () => {
|
|
11
|
-
const env = getRuntimeEnv();
|
|
12
|
-
return !!(env.CLOUDFLARE_WORKER || env.CF_PAGES);
|
|
13
|
-
};
|
|
14
|
-
const isVercel = () => {
|
|
15
|
-
const env = getRuntimeEnv();
|
|
16
|
-
return !!(env.VERCEL || env.VERCEL_ENV);
|
|
17
|
-
};
|
|
18
|
-
function getCloudflareEnv(event) {
|
|
19
|
-
const context = typeof event === "object" && event ? event : void 0;
|
|
20
|
-
const globalEnv = globalThis.__env__;
|
|
21
|
-
const env = context?.req?.runtime?.cloudflare?.env || context?.context?.cloudflare?.env || context?.context?._platform?.cloudflare?.env || globalEnv;
|
|
22
|
-
return env && typeof env === "object" ? env : null;
|
|
23
|
-
}
|
|
24
|
-
//#endregion
|
|
25
|
-
export { isVercel as i, getCloudflareEnv as n, isCloudflare as r, createProviderDetector as t };
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { setSandboxRuntimeConfig } from "./state.js";
|
|
2
|
-
import { useRuntimeConfig } from "nitro/runtime-config";
|
|
3
|
-
//#region src/runtime/nitro-plugin.ts
|
|
4
|
-
const sandboxNitroPlugin = () => {
|
|
5
|
-
setSandboxRuntimeConfig(useRuntimeConfig().sandbox);
|
|
6
|
-
};
|
|
7
|
-
//#endregion
|
|
8
|
-
export { sandboxNitroPlugin as default };
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { n as CloudflareSandboxProviderOptions } from "../../common-CS4FcWrh.js";
|
|
2
|
-
import { t as CloudflareSandboxClient } from "../../index-B4j3Mvzr.js";
|
|
3
|
-
|
|
4
|
-
//#region src/sandbox/providers/cloudflare.d.ts
|
|
5
|
-
declare function createCloudflareSandboxClient(provider: CloudflareSandboxProviderOptions): Promise<CloudflareSandboxClient>;
|
|
6
|
-
//#endregion
|
|
7
|
-
export { createCloudflareSandboxClient };
|