@vite-hub/web-container 0.0.0-stage → 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/LICENSE +201 -0
- package/README.md +220 -2
- package/dist/connect.d.ts +55 -0
- package/dist/connect.js +97 -0
- package/dist/env.d.ts +10 -0
- package/dist/env.js +13 -0
- package/dist/error-diagnostics-DDPkdBo-.js +53 -0
- package/dist/index.d.ts +134 -0
- package/dist/index.js +435 -0
- package/dist/links-Dts2hWjR.js +78 -0
- package/dist/snapshot.d.ts +43 -0
- package/dist/snapshot.js +272 -0
- package/dist/vite.d.ts +21 -0
- package/dist/vite.js +45 -0
- package/dist/vue.d.ts +102 -0
- package/dist/vue.js +334 -0
- package/package.json +101 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { FileSystemAPI, FileSystemAPI as FileSystemAPI$1, FileSystemTree, FileSystemTree as FileSystemTree$1 } from "@webcontainer/api";
|
|
2
|
+
//#region src/index.d.ts
|
|
3
|
+
/** One step of a boot checklist, in the order a UI shows it. */
|
|
4
|
+
export type WebContainerStage = "checking" | "unsupported" | "booting" | "mounting" | "installing" | "starting" | "ready" | "error";
|
|
5
|
+
export interface WebContainerStep {
|
|
6
|
+
stage: WebContainerStage;
|
|
7
|
+
/** `performance.now()` when the stage started. */
|
|
8
|
+
startedAt: number;
|
|
9
|
+
/** Milliseconds the stage took. Unset while the stage runs. */
|
|
10
|
+
ms?: number;
|
|
11
|
+
}
|
|
12
|
+
export interface WebContainerStatus {
|
|
13
|
+
/** The latest stage. */
|
|
14
|
+
stage: WebContainerStage;
|
|
15
|
+
/** Every stage so far, with its timing. */
|
|
16
|
+
steps: readonly WebContainerStep[];
|
|
17
|
+
/** Set when `stage` is `unsupported` or `error`. */
|
|
18
|
+
error?: Error;
|
|
19
|
+
}
|
|
20
|
+
/** Files to mount, keyed by a relative path such as `server/index.js`. */
|
|
21
|
+
export type WebContainerFiles = Record<string, string | Uint8Array>;
|
|
22
|
+
export interface BootWebContainerOptions {
|
|
23
|
+
/** Files to write into the working directory. */
|
|
24
|
+
files?: WebContainerFiles;
|
|
25
|
+
/**
|
|
26
|
+
* A binary snapshot from `container.export()`, `fetchSnapshot()`, or `createNodeModulesSnapshot()` of
|
|
27
|
+
* `@vite-hub/web-container/snapshot`, such as `node_modules` that are already installed. Mounted before `files`.
|
|
28
|
+
* A promise loads while the WebContainer boots.
|
|
29
|
+
*/
|
|
30
|
+
snapshot?: Uint8Array | ArrayBuffer | Promise<Uint8Array | ArrayBuffer>;
|
|
31
|
+
/**
|
|
32
|
+
* The Cross-Origin-Embedder-Policy of the page.
|
|
33
|
+
* @default "credentialless"
|
|
34
|
+
*/
|
|
35
|
+
coep?: "credentialless" | "require-corp";
|
|
36
|
+
/** Folder name of the working directory. */
|
|
37
|
+
workdirName?: string;
|
|
38
|
+
/**
|
|
39
|
+
* The port of the server to preview. `run()` passes it to every process as `PORT`, which Nitro's `vite dev` and
|
|
40
|
+
* `node .output/server/index.mjs` listen on. A run with its own `env.PORT` previews that port instead. Servers on
|
|
41
|
+
* other ports, such as the workers that Nitro starts on random ports first, do not become the preview.
|
|
42
|
+
* @default 3000
|
|
43
|
+
*/
|
|
44
|
+
port?: number;
|
|
45
|
+
/**
|
|
46
|
+
* JavaScript that runs first in every HTML page of the preview, such as a script that reports the page address to
|
|
47
|
+
* the parent page. The preview origin is cross-origin, so this is the only way to run code in its pages.
|
|
48
|
+
*/
|
|
49
|
+
previewScript?: string;
|
|
50
|
+
/** Called on every status change, from the first check on. */
|
|
51
|
+
onStatus?: (status: WebContainerStatus) => void;
|
|
52
|
+
}
|
|
53
|
+
/** `install`, `dev`, and `build` run the npm scripts of the mounted app. An array runs that command line. */
|
|
54
|
+
export type WebContainerCommand = "install" | "dev" | "build" | readonly [string, ...string[]];
|
|
55
|
+
export interface WebContainerRunOptions {
|
|
56
|
+
/** Environment variables for this process only. They stay in the browser tab. `PORT` defaults to the `port` of `bootWebContainer()`. */
|
|
57
|
+
env?: Record<string, string>;
|
|
58
|
+
/** Working directory, relative to the container root. */
|
|
59
|
+
cwd?: string;
|
|
60
|
+
/** Kills the process when aborted. */
|
|
61
|
+
signal?: AbortSignal;
|
|
62
|
+
}
|
|
63
|
+
export interface WebContainerRun {
|
|
64
|
+
/** Terminal output of the process and its children. Read it once. Buffers up to 65,536 characters; excess output is dropped until the reader catches up. */
|
|
65
|
+
output: ReadableStream<string>;
|
|
66
|
+
/** Resolves with the exit code. */
|
|
67
|
+
exit: Promise<number>;
|
|
68
|
+
/** Resolves with the last 65,536 characters of output after the process exits. */
|
|
69
|
+
text: () => Promise<string>;
|
|
70
|
+
/** Writes to the process stdin. */
|
|
71
|
+
write: (input: string) => Promise<void>;
|
|
72
|
+
kill: () => void;
|
|
73
|
+
}
|
|
74
|
+
export interface WebContainerPreviewServer {
|
|
75
|
+
url: string;
|
|
76
|
+
port: number;
|
|
77
|
+
}
|
|
78
|
+
export interface WebContainerPreview {
|
|
79
|
+
/** The URL of the latest server that became ready. */
|
|
80
|
+
readonly url: string | undefined;
|
|
81
|
+
readonly port: number | undefined;
|
|
82
|
+
/** Resolves when the server on `port`, or on the `env.PORT` of a run, becomes ready. Rejects on startup failure or teardown before readiness. */
|
|
83
|
+
ready: Promise<WebContainerPreviewServer>;
|
|
84
|
+
}
|
|
85
|
+
export interface ViteHubWebContainer {
|
|
86
|
+
readonly status: WebContainerStatus;
|
|
87
|
+
preview: WebContainerPreview;
|
|
88
|
+
fs: FileSystemAPI$1;
|
|
89
|
+
/** Only one `dev` run may be active. Stop it and await its exit before starting another. */
|
|
90
|
+
run: (command: WebContainerCommand, options?: WebContainerRunOptions) => Promise<WebContainerRun>;
|
|
91
|
+
/** Serializes the working directory to a binary snapshot that `bootWebContainer({ snapshot })` mounts. */
|
|
92
|
+
export: (options?: {
|
|
93
|
+
path?: string;
|
|
94
|
+
excludes?: string[];
|
|
95
|
+
includes?: string[];
|
|
96
|
+
}) => Promise<Uint8Array>;
|
|
97
|
+
on(event: "status", listener: (status: WebContainerStatus) => void): () => void;
|
|
98
|
+
on(event: "server-ready", listener: (server: WebContainerPreviewServer) => void): () => void;
|
|
99
|
+
/** Stops every process and frees the container. Boot a new one afterwards if needed. */
|
|
100
|
+
teardown: () => void;
|
|
101
|
+
}
|
|
102
|
+
export type WebContainerSupport = {
|
|
103
|
+
supported: true;
|
|
104
|
+
} | {
|
|
105
|
+
supported: false;
|
|
106
|
+
reason: string;
|
|
107
|
+
};
|
|
108
|
+
/** Checks the page, not the browser name: a WebContainer needs a cross-origin isolated page with SharedArrayBuffer. */
|
|
109
|
+
export declare function checkWebContainerSupport(): WebContainerSupport;
|
|
110
|
+
/** Turns `{ "server/index.js": "..." }` into the nested tree that WebContainer mounts. */
|
|
111
|
+
export declare function toFileSystemTree(files: WebContainerFiles): FileSystemTree$1;
|
|
112
|
+
export interface FetchSnapshotOptions {
|
|
113
|
+
/**
|
|
114
|
+
* A Cache Storage name. Parts found there are not downloaded again, so later boots work from the cache. Give each
|
|
115
|
+
* snapshot version its own URLs, such as names with a content hash. Parts of other URLs in this cache are deleted.
|
|
116
|
+
* A part goes into the cache only after the whole snapshot inflates and matches `sha256`.
|
|
117
|
+
*/
|
|
118
|
+
cache?: string;
|
|
119
|
+
/** The SHA-256 of the joined parts, in hex. A snapshot that differs is rejected, and none of its parts is cached. */
|
|
120
|
+
sha256?: string;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Downloads the parts that `packSnapshot()` of `@vite-hub/web-container/snapshot` wrote, joins them in order, and
|
|
124
|
+
* inflates the gzip stream. Pass the result, or the promise, to `bootWebContainer({ snapshot })`.
|
|
125
|
+
*/
|
|
126
|
+
export declare function fetchSnapshot(urls: readonly string[], options?: FetchSnapshotOptions): Promise<Uint8Array>;
|
|
127
|
+
/**
|
|
128
|
+
* Boots a WebContainer in this browser tab and mounts an app into it.
|
|
129
|
+
*
|
|
130
|
+
* Only one WebContainer can run per page. Call `teardown()` before you boot another.
|
|
131
|
+
*/
|
|
132
|
+
export declare function bootWebContainer(options?: BootWebContainerOptions): Promise<ViteHubWebContainer>;
|
|
133
|
+
//#endregion
|
|
134
|
+
export type { FileSystemAPI, FileSystemTree };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { t as webContainerErrorDiagnostics } from "./error-diagnostics-DDPkdBo-.js";
|
|
2
|
+
import { n as restoreLinksScript } from "./links-Dts2hWjR.js";
|
|
3
|
+
import { defineDiagnostics } from "nostics";
|
|
4
|
+
//#region src/index.ts
|
|
5
|
+
const webContainerBrowserDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
6
|
+
docsBase: "https://vitehub.dev/docs/web-container/diagnostics",
|
|
7
|
+
codes: { WEB_CONTAINER_UNSUPPORTED: {
|
|
8
|
+
why: ({ reason }) => reason,
|
|
9
|
+
fix: "Call `bootWebContainer()` in a browser page that is cross-origin isolated: list the page in the `routes` option of `hubWebContainer` in `vitehub()`, or send the isolation headers on its route in production."
|
|
10
|
+
} }
|
|
11
|
+
});
|
|
12
|
+
/** Checks the page, not the browser name: a WebContainer needs a cross-origin isolated page with SharedArrayBuffer. */
|
|
13
|
+
function checkWebContainerSupport() {
|
|
14
|
+
if (Reflect.get(globalThis, "document") === void 0) return {
|
|
15
|
+
supported: false,
|
|
16
|
+
reason: "WebContainers run in a browser page, not on the server."
|
|
17
|
+
};
|
|
18
|
+
if (Reflect.get(globalThis, "crossOriginIsolated") !== true) return {
|
|
19
|
+
supported: false,
|
|
20
|
+
reason: "The page is not cross-origin isolated. Serve it with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: credentialless (see @vite-hub/web-container/vite)."
|
|
21
|
+
};
|
|
22
|
+
if (typeof SharedArrayBuffer === "undefined") return {
|
|
23
|
+
supported: false,
|
|
24
|
+
reason: "This browser has no SharedArrayBuffer."
|
|
25
|
+
};
|
|
26
|
+
return { supported: true };
|
|
27
|
+
}
|
|
28
|
+
const commandLines = {
|
|
29
|
+
install: [
|
|
30
|
+
"npm",
|
|
31
|
+
"install",
|
|
32
|
+
"--no-audit",
|
|
33
|
+
"--no-fund",
|
|
34
|
+
"--no-progress"
|
|
35
|
+
],
|
|
36
|
+
dev: [
|
|
37
|
+
"npm",
|
|
38
|
+
"run",
|
|
39
|
+
"dev"
|
|
40
|
+
],
|
|
41
|
+
build: [
|
|
42
|
+
"npm",
|
|
43
|
+
"run",
|
|
44
|
+
"build"
|
|
45
|
+
]
|
|
46
|
+
};
|
|
47
|
+
const commandStages = {
|
|
48
|
+
install: "installing",
|
|
49
|
+
dev: "starting"
|
|
50
|
+
};
|
|
51
|
+
/** Turns `{ "server/index.js": "..." }` into the nested tree that WebContainer mounts. */
|
|
52
|
+
function toFileSystemTree(files) {
|
|
53
|
+
const root = {};
|
|
54
|
+
for (const [path, contents] of Object.entries(files)) {
|
|
55
|
+
const segments = path.split("/");
|
|
56
|
+
if (path.startsWith("/") || segments.includes("..")) throw webContainerErrorDiagnostics.WEB_CONTAINER_FILE_PATH_INVALID({
|
|
57
|
+
path,
|
|
58
|
+
reason: "invalid"
|
|
59
|
+
});
|
|
60
|
+
const parts = segments.filter((part) => part && part !== ".");
|
|
61
|
+
const name = parts.pop();
|
|
62
|
+
if (!name) throw webContainerErrorDiagnostics.WEB_CONTAINER_FILE_PATH_INVALID({
|
|
63
|
+
path,
|
|
64
|
+
reason: "invalid"
|
|
65
|
+
});
|
|
66
|
+
let tree = root;
|
|
67
|
+
for (const part of parts) {
|
|
68
|
+
let node = Object.hasOwn(tree, part) ? tree[part] : void 0;
|
|
69
|
+
if (!node) {
|
|
70
|
+
node = { directory: {} };
|
|
71
|
+
Object.defineProperty(tree, part, {
|
|
72
|
+
value: node,
|
|
73
|
+
enumerable: true,
|
|
74
|
+
configurable: true,
|
|
75
|
+
writable: true
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
if (!("directory" in node)) throw webContainerErrorDiagnostics.WEB_CONTAINER_FILE_PATH_INVALID({
|
|
79
|
+
part,
|
|
80
|
+
path,
|
|
81
|
+
reason: "through-file"
|
|
82
|
+
});
|
|
83
|
+
tree = node.directory;
|
|
84
|
+
}
|
|
85
|
+
if (Object.hasOwn(tree, name) && "directory" in tree[name]) throw webContainerErrorDiagnostics.WEB_CONTAINER_FILE_PATH_INVALID({
|
|
86
|
+
part: name,
|
|
87
|
+
path,
|
|
88
|
+
reason: "replaces-directory"
|
|
89
|
+
});
|
|
90
|
+
Object.defineProperty(tree, name, {
|
|
91
|
+
value: { file: { contents } },
|
|
92
|
+
enumerable: true,
|
|
93
|
+
configurable: true,
|
|
94
|
+
writable: true
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return root;
|
|
98
|
+
}
|
|
99
|
+
function createStatusTracker(onStatus) {
|
|
100
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
101
|
+
if (onStatus) listeners.add(onStatus);
|
|
102
|
+
const steps = [];
|
|
103
|
+
let status = {
|
|
104
|
+
stage: "checking",
|
|
105
|
+
steps
|
|
106
|
+
};
|
|
107
|
+
function finishOpenStep() {
|
|
108
|
+
const open = steps.at(-1);
|
|
109
|
+
if (open && open.ms === void 0) open.ms = performance.now() - open.startedAt;
|
|
110
|
+
}
|
|
111
|
+
function emit(next) {
|
|
112
|
+
status = next;
|
|
113
|
+
for (const listener of listeners) listener(status);
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
get current() {
|
|
117
|
+
return status;
|
|
118
|
+
},
|
|
119
|
+
listeners,
|
|
120
|
+
enter(stage) {
|
|
121
|
+
finishOpenStep();
|
|
122
|
+
steps.push({
|
|
123
|
+
stage,
|
|
124
|
+
startedAt: performance.now()
|
|
125
|
+
});
|
|
126
|
+
emit({
|
|
127
|
+
stage,
|
|
128
|
+
steps: [...steps]
|
|
129
|
+
});
|
|
130
|
+
},
|
|
131
|
+
finish(stage) {
|
|
132
|
+
const open = steps.at(-1);
|
|
133
|
+
if (open?.stage !== stage || open.ms !== void 0) return;
|
|
134
|
+
finishOpenStep();
|
|
135
|
+
emit({
|
|
136
|
+
...status,
|
|
137
|
+
steps: [...steps]
|
|
138
|
+
});
|
|
139
|
+
},
|
|
140
|
+
fail(stage, error) {
|
|
141
|
+
finishOpenStep();
|
|
142
|
+
steps.push({
|
|
143
|
+
stage,
|
|
144
|
+
startedAt: performance.now(),
|
|
145
|
+
ms: 0
|
|
146
|
+
});
|
|
147
|
+
emit({
|
|
148
|
+
stage,
|
|
149
|
+
steps: [...steps],
|
|
150
|
+
error
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
const outputLimit = 65536;
|
|
156
|
+
function wrapProcess(spawned, signal) {
|
|
157
|
+
let captured = "";
|
|
158
|
+
let outputCancelled = false;
|
|
159
|
+
let outputController;
|
|
160
|
+
const output = new ReadableStream({
|
|
161
|
+
start(controller) {
|
|
162
|
+
outputController = controller;
|
|
163
|
+
},
|
|
164
|
+
cancel() {
|
|
165
|
+
outputCancelled = true;
|
|
166
|
+
}
|
|
167
|
+
}, {
|
|
168
|
+
highWaterMark: outputLimit,
|
|
169
|
+
size: (chunk) => chunk.length
|
|
170
|
+
});
|
|
171
|
+
const collected = spawned.output.pipeTo(new WritableStream({
|
|
172
|
+
write(chunk) {
|
|
173
|
+
captured = (captured + chunk).slice(-65536);
|
|
174
|
+
const available = outputController.desiredSize ?? 0;
|
|
175
|
+
if (!outputCancelled && available > 0 && chunk.length > 0) outputController.enqueue(chunk.slice(0, available));
|
|
176
|
+
},
|
|
177
|
+
close() {
|
|
178
|
+
if (!outputCancelled) outputController.close();
|
|
179
|
+
},
|
|
180
|
+
abort(error) {
|
|
181
|
+
if (!outputCancelled) outputController.error(error);
|
|
182
|
+
}
|
|
183
|
+
})).catch(() => {});
|
|
184
|
+
const kill = () => spawned.kill();
|
|
185
|
+
signal?.addEventListener("abort", kill, { once: true });
|
|
186
|
+
if (signal?.aborted) kill();
|
|
187
|
+
const exit = spawned.exit.finally(() => signal?.removeEventListener("abort", kill));
|
|
188
|
+
return {
|
|
189
|
+
output,
|
|
190
|
+
exit,
|
|
191
|
+
kill,
|
|
192
|
+
async text() {
|
|
193
|
+
await exit;
|
|
194
|
+
await collected;
|
|
195
|
+
return captured;
|
|
196
|
+
},
|
|
197
|
+
async write(input) {
|
|
198
|
+
const writer = spawned.input.getWriter();
|
|
199
|
+
try {
|
|
200
|
+
await writer.write(input);
|
|
201
|
+
} finally {
|
|
202
|
+
writer.releaseLock();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
/** A snapshot from `createNodeModulesSnapshot()` lists its symlinks and executable files. Restore them in one Node run. */
|
|
208
|
+
async function restoreSnapshotLinks(container) {
|
|
209
|
+
if (!await container.fs.readFile(`node_modules/.vitehub-snapshot-links.json`, "utf8").then(() => true, () => false)) return;
|
|
210
|
+
const script = "node_modules/.vitehub-restore-links.cjs";
|
|
211
|
+
await container.fs.writeFile(script, restoreLinksScript);
|
|
212
|
+
const code = await (await container.spawn("node", [script])).exit;
|
|
213
|
+
if (code !== 0) throw webContainerErrorDiagnostics.WEB_CONTAINER_SNAPSHOT_LINKS_FAILED({ code });
|
|
214
|
+
}
|
|
215
|
+
function isCacheStorage(value) {
|
|
216
|
+
return typeof value === "object" && value !== null && "open" in value && typeof value.open === "function";
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Downloads the parts that `packSnapshot()` of `@vite-hub/web-container/snapshot` wrote, joins them in order, and
|
|
220
|
+
* inflates the gzip stream. Pass the result, or the promise, to `bootWebContainer({ snapshot })`.
|
|
221
|
+
*/
|
|
222
|
+
async function fetchSnapshot(urls, options = {}) {
|
|
223
|
+
const storage = Reflect.get(globalThis, "caches");
|
|
224
|
+
const cache = options.cache && isCacheStorage(storage) ? await storage.open(options.cache).catch(() => void 0) : void 0;
|
|
225
|
+
if (cache) {
|
|
226
|
+
const keep = new Set(urls.map((url) => new Request(url).url));
|
|
227
|
+
for (const request of await cache.keys()) if (!keep.has(request.url)) cache.delete(request);
|
|
228
|
+
}
|
|
229
|
+
const parts = await Promise.all(urls.map(async (url) => {
|
|
230
|
+
const cached = await cache?.match(url);
|
|
231
|
+
if (cached) return {
|
|
232
|
+
url,
|
|
233
|
+
blob: await cached.blob(),
|
|
234
|
+
downloaded: false
|
|
235
|
+
};
|
|
236
|
+
const response = await fetch(url);
|
|
237
|
+
if (!response.ok) throw webContainerErrorDiagnostics.WEB_CONTAINER_SNAPSHOT_PART_FAILED({
|
|
238
|
+
status: response.status,
|
|
239
|
+
url
|
|
240
|
+
});
|
|
241
|
+
return {
|
|
242
|
+
url,
|
|
243
|
+
blob: await response.blob(),
|
|
244
|
+
downloaded: true
|
|
245
|
+
};
|
|
246
|
+
}));
|
|
247
|
+
const joined = new Blob(parts.map((part) => part.blob));
|
|
248
|
+
let data;
|
|
249
|
+
try {
|
|
250
|
+
if (options.sha256) {
|
|
251
|
+
const hex = [...new Uint8Array(await crypto.subtle.digest("SHA-256", await joined.arrayBuffer()))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
252
|
+
if (hex !== options.sha256.toLowerCase()) throw webContainerErrorDiagnostics.WEB_CONTAINER_SNAPSHOT_DAMAGED({
|
|
253
|
+
detail: `The snapshot has SHA-256 ${hex}, not ${options.sha256}.`,
|
|
254
|
+
url: urls[0]
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
data = new Uint8Array(await new Response(joined.stream().pipeThrough(new DecompressionStream("gzip"))).arrayBuffer());
|
|
258
|
+
} catch (cause) {
|
|
259
|
+
await Promise.all(urls.map((url) => cache?.delete(new Request(url)).catch(() => false)));
|
|
260
|
+
if (webContainerErrorDiagnostics.WEB_CONTAINER_SNAPSHOT_DAMAGED.is(cause)) throw cause;
|
|
261
|
+
throw webContainerErrorDiagnostics.WEB_CONTAINER_SNAPSHOT_DAMAGED({
|
|
262
|
+
cause,
|
|
263
|
+
detail: cause instanceof Error ? cause.message : String(cause),
|
|
264
|
+
url: urls[0]
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
for (const part of parts) if (part.downloaded) await cache?.put(part.url, new Response(part.blob)).catch(() => {});
|
|
268
|
+
return data;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Boots a WebContainer in this browser tab and mounts an app into it.
|
|
272
|
+
*
|
|
273
|
+
* Only one WebContainer can run per page. Call `teardown()` before you boot another.
|
|
274
|
+
*/
|
|
275
|
+
async function bootWebContainer(options = {}) {
|
|
276
|
+
const status = createStatusTracker(options.onStatus);
|
|
277
|
+
status.enter("checking");
|
|
278
|
+
const support = checkWebContainerSupport();
|
|
279
|
+
if (!support.supported) {
|
|
280
|
+
const error = webContainerBrowserDiagnostics.WEB_CONTAINER_UNSUPPORTED({ reason: support.reason });
|
|
281
|
+
status.fail("unsupported", error);
|
|
282
|
+
throw error;
|
|
283
|
+
}
|
|
284
|
+
let booted;
|
|
285
|
+
try {
|
|
286
|
+
status.enter("booting");
|
|
287
|
+
const loading = Promise.resolve(options.snapshot);
|
|
288
|
+
loading.catch(() => {});
|
|
289
|
+
const { WebContainer } = await import("@webcontainer/api");
|
|
290
|
+
booted = await WebContainer.boot({
|
|
291
|
+
coep: options.coep ?? "credentialless",
|
|
292
|
+
workdirName: options.workdirName
|
|
293
|
+
});
|
|
294
|
+
if (options.previewScript) await booted.setPreviewScript(options.previewScript);
|
|
295
|
+
if (options.snapshot || options.files) {
|
|
296
|
+
status.enter("mounting");
|
|
297
|
+
const snapshot = await loading;
|
|
298
|
+
if (snapshot) {
|
|
299
|
+
await booted.mount(snapshot);
|
|
300
|
+
await restoreSnapshotLinks(booted);
|
|
301
|
+
}
|
|
302
|
+
if (options.files) await booted.mount(toFileSystemTree(options.files));
|
|
303
|
+
}
|
|
304
|
+
status.finish(status.current.stage);
|
|
305
|
+
} catch (cause) {
|
|
306
|
+
const error = cause instanceof Error ? cause : new Error(String(cause));
|
|
307
|
+
booted?.teardown();
|
|
308
|
+
status.fail("error", error);
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
const container = booted;
|
|
312
|
+
let server;
|
|
313
|
+
let resolveReady;
|
|
314
|
+
let rejectReady;
|
|
315
|
+
let readySettled = false;
|
|
316
|
+
let serverReadyCount = 0;
|
|
317
|
+
let devRunning = false;
|
|
318
|
+
const ready = new Promise((resolve, reject) => {
|
|
319
|
+
resolveReady = resolve;
|
|
320
|
+
rejectReady = reject;
|
|
321
|
+
});
|
|
322
|
+
ready.catch(() => {});
|
|
323
|
+
function rejectPendingReady(error) {
|
|
324
|
+
if (readySettled) return;
|
|
325
|
+
readySettled = true;
|
|
326
|
+
rejectReady(error);
|
|
327
|
+
}
|
|
328
|
+
function fail(error) {
|
|
329
|
+
rejectPendingReady(error);
|
|
330
|
+
status.fail("error", error);
|
|
331
|
+
}
|
|
332
|
+
const defaultPort = String(options.port ?? 3e3);
|
|
333
|
+
const previewPorts = /* @__PURE__ */ new Map();
|
|
334
|
+
container.on("server-ready", (port, url) => {
|
|
335
|
+
if (!previewPorts.has(port)) return;
|
|
336
|
+
serverReadyCount++;
|
|
337
|
+
server = {
|
|
338
|
+
port,
|
|
339
|
+
url
|
|
340
|
+
};
|
|
341
|
+
if (!readySettled) {
|
|
342
|
+
readySettled = true;
|
|
343
|
+
resolveReady(server);
|
|
344
|
+
}
|
|
345
|
+
if (status.current.stage === "starting") status.enter("ready");
|
|
346
|
+
});
|
|
347
|
+
container.on("error", ({ message }) => fail(new Error(message)));
|
|
348
|
+
return {
|
|
349
|
+
get status() {
|
|
350
|
+
return status.current;
|
|
351
|
+
},
|
|
352
|
+
preview: {
|
|
353
|
+
get url() {
|
|
354
|
+
return server?.url;
|
|
355
|
+
},
|
|
356
|
+
get port() {
|
|
357
|
+
return server?.port;
|
|
358
|
+
},
|
|
359
|
+
ready
|
|
360
|
+
},
|
|
361
|
+
fs: container.fs,
|
|
362
|
+
async run(command, runOptions = {}) {
|
|
363
|
+
const [file, ...args] = typeof command === "string" ? commandLines[command] : command;
|
|
364
|
+
const stage = typeof command === "string" ? commandStages[command] : void 0;
|
|
365
|
+
if (stage === "starting") {
|
|
366
|
+
if (devRunning) throw webContainerErrorDiagnostics.WEB_CONTAINER_DEV_RUNNING();
|
|
367
|
+
devRunning = true;
|
|
368
|
+
}
|
|
369
|
+
const readyCountAtStart = serverReadyCount;
|
|
370
|
+
if (stage) status.enter(stage);
|
|
371
|
+
const env = {
|
|
372
|
+
PORT: defaultPort,
|
|
373
|
+
NODE_OPTIONS: "--disable-warning=ExperimentalWarning",
|
|
374
|
+
...runOptions.env
|
|
375
|
+
};
|
|
376
|
+
const previewPort = Number(env.PORT);
|
|
377
|
+
previewPorts.set(previewPort, (previewPorts.get(previewPort) ?? 0) + 1);
|
|
378
|
+
function releasePreviewPort() {
|
|
379
|
+
const remaining = previewPorts.get(previewPort) - 1;
|
|
380
|
+
if (remaining) previewPorts.set(previewPort, remaining);
|
|
381
|
+
else previewPorts.delete(previewPort);
|
|
382
|
+
}
|
|
383
|
+
let spawned;
|
|
384
|
+
try {
|
|
385
|
+
spawned = await container.spawn(file, args, {
|
|
386
|
+
cwd: runOptions.cwd,
|
|
387
|
+
env
|
|
388
|
+
});
|
|
389
|
+
} catch (cause) {
|
|
390
|
+
releasePreviewPort();
|
|
391
|
+
const error = cause instanceof Error ? cause : new Error(String(cause));
|
|
392
|
+
if (stage === "starting") devRunning = false;
|
|
393
|
+
if (stage) fail(error);
|
|
394
|
+
throw error;
|
|
395
|
+
}
|
|
396
|
+
const run = wrapProcess(spawned, runOptions.signal);
|
|
397
|
+
run.exit.then(releasePreviewPort, releasePreviewPort);
|
|
398
|
+
if (stage === "installing") run.exit.then(async (code) => {
|
|
399
|
+
if (code === 0) return status.finish("installing");
|
|
400
|
+
fail(/* @__PURE__ */ new Error(`npm install exited with code ${code}.\n${(await run.text()).slice(-2e3)}`));
|
|
401
|
+
});
|
|
402
|
+
if (stage === "starting") run.exit.then((code) => {
|
|
403
|
+
devRunning = false;
|
|
404
|
+
if (serverReadyCount === readyCountAtStart) fail(/* @__PURE__ */ new Error(`The dev server exited with code ${code} before it was ready.`));
|
|
405
|
+
});
|
|
406
|
+
return run;
|
|
407
|
+
},
|
|
408
|
+
export(exportOptions = {}) {
|
|
409
|
+
const { path = ".", ...rest } = exportOptions;
|
|
410
|
+
return container.export(path, {
|
|
411
|
+
...rest,
|
|
412
|
+
format: "binary"
|
|
413
|
+
});
|
|
414
|
+
},
|
|
415
|
+
on(...args) {
|
|
416
|
+
if (args[0] === "server-ready") {
|
|
417
|
+
const listener = args[1];
|
|
418
|
+
return container.on("server-ready", (port, url) => listener({
|
|
419
|
+
port,
|
|
420
|
+
url
|
|
421
|
+
}));
|
|
422
|
+
}
|
|
423
|
+
const listener = args[1];
|
|
424
|
+
status.listeners.add(listener);
|
|
425
|
+
return () => status.listeners.delete(listener);
|
|
426
|
+
},
|
|
427
|
+
teardown() {
|
|
428
|
+
rejectPendingReady(/* @__PURE__ */ new Error("The WebContainer was torn down before the preview was ready."));
|
|
429
|
+
status.listeners.clear();
|
|
430
|
+
container.teardown();
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
//#endregion
|
|
435
|
+
export { bootWebContainer, checkWebContainerSupport, fetchSnapshot, toFileSystemTree };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
//#region src/links.ts
|
|
2
|
+
/** The file in `node_modules` that lists what a snapshot cannot hold. */
|
|
3
|
+
const snapshotLinksFile = ".vitehub-snapshot-links.json";
|
|
4
|
+
/**
|
|
5
|
+
* A Node script that restores the links and executable bits of a mounted snapshot, from the working directory.
|
|
6
|
+
* WebContainer `mount()` drops executable bits (https://github.com/stackblitz/webcontainer-core/issues/2186).
|
|
7
|
+
*
|
|
8
|
+
* The snapshot bytes come from the network, so the list is not trusted: a path must be relative and stay inside the
|
|
9
|
+
* working directory, and so must the place that a link points to. Destination paths through symlinks are rejected.
|
|
10
|
+
* Targets are checked after restoration so aliases are followed regardless of their order in the list.
|
|
11
|
+
* Other entries are skipped and printed.
|
|
12
|
+
*/
|
|
13
|
+
const restoreLinksScript = [
|
|
14
|
+
`const fs = require("node:fs")`,
|
|
15
|
+
`const path = require("node:path")`,
|
|
16
|
+
`const root = process.cwd()`,
|
|
17
|
+
`const inside = target => target === root || target.startsWith(root + path.sep)`,
|
|
18
|
+
`const local = file => {`,
|
|
19
|
+
` if (typeof file !== "string" || file === "" || path.isAbsolute(file) || !inside(path.resolve(root, file))) return false`,
|
|
20
|
+
` let current = root`,
|
|
21
|
+
` for (const segment of file.split(path.sep)) {`,
|
|
22
|
+
` current = path.join(current, segment)`,
|
|
23
|
+
` try { if (fs.lstatSync(current).isSymbolicLink()) return false } catch (error) { if (error.code !== "ENOENT") throw error }`,
|
|
24
|
+
` }`,
|
|
25
|
+
` return true`,
|
|
26
|
+
`}`,
|
|
27
|
+
`const localTarget = (file, target) => {`,
|
|
28
|
+
` let current = path.resolve(root, path.dirname(file))`,
|
|
29
|
+
` let segments = target.split(path.sep)`,
|
|
30
|
+
` let followed = 0`,
|
|
31
|
+
` while (segments.length > 0) {`,
|
|
32
|
+
` const segment = segments.shift()`,
|
|
33
|
+
` if (segment === "" || segment === ".") continue`,
|
|
34
|
+
` const next = path.resolve(current, segment)`,
|
|
35
|
+
` if (!inside(next)) return false`,
|
|
36
|
+
` try {`,
|
|
37
|
+
` if (fs.lstatSync(next).isSymbolicLink()) {`,
|
|
38
|
+
` if (++followed > 40) return false`,
|
|
39
|
+
` const alias = fs.readlinkSync(next)`,
|
|
40
|
+
` if (path.isAbsolute(alias)) {`,
|
|
41
|
+
` if (!inside(alias)) return false`,
|
|
42
|
+
` current = root`,
|
|
43
|
+
` segments = alias.slice(root.length).split(path.sep).concat(segments)`,
|
|
44
|
+
` } else segments = alias.split(path.sep).concat(segments)`,
|
|
45
|
+
` continue`,
|
|
46
|
+
` }`,
|
|
47
|
+
` } catch (error) { if (error.code === "ENOTDIR") return false; if (error.code !== "ENOENT") throw error }`,
|
|
48
|
+
` current = next`,
|
|
49
|
+
` }`,
|
|
50
|
+
` return true`,
|
|
51
|
+
`}`,
|
|
52
|
+
`const { links = [], executables = [] } = JSON.parse(fs.readFileSync(${JSON.stringify(`node_modules/${snapshotLinksFile}`)}, "utf8"))`,
|
|
53
|
+
`const skipped = []`,
|
|
54
|
+
`const restored = []`,
|
|
55
|
+
`for (const file of executables) { if (local(file)) fs.chmodSync(file, 0o755); else skipped.push(file) }`,
|
|
56
|
+
`for (const [file, target] of links) {`,
|
|
57
|
+
` if (!local(file) || typeof target !== "string" || path.isAbsolute(target) || !inside(path.resolve(root, path.dirname(file), target))) { skipped.push(file); continue }`,
|
|
58
|
+
` try { fs.symlinkSync(target, file); restored.push([file, target]) } catch (error) { if (error.code !== "EEXIST") throw error }`,
|
|
59
|
+
`}`,
|
|
60
|
+
`for (const [file, target] of restored) {`,
|
|
61
|
+
` if (!localTarget(file, target)) { fs.unlinkSync(file); skipped.push(file) }`,
|
|
62
|
+
`}`,
|
|
63
|
+
`if (skipped.length > 0) console.warn("Skipped snapshot links outside the project or through symlinks: " + skipped.join(", "))`
|
|
64
|
+
].join("\n");
|
|
65
|
+
/** True when `target`, relative to the folder of the link at `path`, stays inside the root. Both use `/`. */
|
|
66
|
+
function linkStaysInside(path, target) {
|
|
67
|
+
if (target.startsWith("/") || path.startsWith("/")) return false;
|
|
68
|
+
const segments = [...path.split("/").slice(0, -1), ...target.split("/")];
|
|
69
|
+
let depth = 0;
|
|
70
|
+
for (const segment of segments) {
|
|
71
|
+
if (segment === "..") depth--;
|
|
72
|
+
else if (segment !== "." && segment !== "") depth++;
|
|
73
|
+
if (depth < 0) return false;
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
export { restoreLinksScript as n, snapshotLinksFile as r, linkStaysInside as t };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
//#region src/snapshot.d.ts
|
|
2
|
+
export interface CreateNodeModulesSnapshotOptions {
|
|
3
|
+
/** A folder with the `package.json` (and `.npmrc`) of the app. The install writes `node_modules` here and preserves `package.json`. */
|
|
4
|
+
dir: string;
|
|
5
|
+
/** Keep `devDependencies`. @default false */
|
|
6
|
+
dev?: boolean;
|
|
7
|
+
/**
|
|
8
|
+
* The `lockfile` of an earlier snapshot of this app. The install then runs `npm ci`, so the same lockfile gives the
|
|
9
|
+
* same `node_modules` and the same snapshot bytes. Without it, npm resolves the versions and returns a new lockfile.
|
|
10
|
+
*/
|
|
11
|
+
lockfile?: string;
|
|
12
|
+
/**
|
|
13
|
+
* With `false`, a `lockfile` that no longer matches the app is updated with `npm install`, which keeps the versions it
|
|
14
|
+
* can, instead of an error. @default true
|
|
15
|
+
*/
|
|
16
|
+
frozenLockfile?: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface NodeModulesSnapshot {
|
|
19
|
+
/** The binary snapshot for `bootWebContainer({ snapshot })`. */
|
|
20
|
+
snapshot: Uint8Array;
|
|
21
|
+
/** The `package-lock.json` of the install. Keep it and pass it back as `lockfile` to get the same snapshot. */
|
|
22
|
+
lockfile: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Installs the dependencies of an app on this machine as npm in a WebContainer does, and returns a snapshot that holds
|
|
26
|
+
* only `node_modules`. Mount it with `bootWebContainer({ snapshot })`, so the container skips `npm install`.
|
|
27
|
+
*
|
|
28
|
+
* Native binaries are left out: the install uses `--cpu=wasm32`, swaps packages for their wasm builds, and adds the
|
|
29
|
+
* wasm binding of rolldown. Install scripts do not run. Source maps are dropped.
|
|
30
|
+
* The snapshot cannot hold symlinks or executable bits, so it lists them, and `bootWebContainer` restores them.
|
|
31
|
+
* It is encoded with msgpack directly: @webcontainer/snapshot runs out of memory on large trees
|
|
32
|
+
* (https://github.com/stackblitz/webcontainer-core/issues/2187).
|
|
33
|
+
* Creation requires a POSIX host (Linux, macOS, or WSL); Windows npm shims cannot be restored as POSIX bin links.
|
|
34
|
+
*/
|
|
35
|
+
export declare function createNodeModulesSnapshot(options: CreateNodeModulesSnapshotOptions): Promise<NodeModulesSnapshot>;
|
|
36
|
+
/**
|
|
37
|
+
* Compresses a snapshot with gzip and splits it into parts of at most `partBytes`, for hosts that limit the size of a
|
|
38
|
+
* static file, such as the 25 MiB of Cloudflare Workers assets. `fetchSnapshot` joins the parts again.
|
|
39
|
+
*/
|
|
40
|
+
export declare function packSnapshot(data: Uint8Array, options?: {
|
|
41
|
+
partBytes?: number;
|
|
42
|
+
}): Uint8Array[];
|
|
43
|
+
//#endregion
|