@vite-hub/web-container 0.0.0 → 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/dist/vue.js ADDED
@@ -0,0 +1,334 @@
1
+ import { bootWebContainer, checkWebContainerSupport } from "./index.js";
2
+ import { computed, getCurrentInstance, getCurrentScope, onMounted, onScopeDispose, readonly, ref, shallowRef, toValue } from "vue";
3
+ //#region src/vue.ts
4
+ function browserWindow() {
5
+ return globalThis.window;
6
+ }
7
+ function toError(cause) {
8
+ return cause instanceof Error ? cause : new Error(String(cause));
9
+ }
10
+ function parentDirectory(path) {
11
+ const index = path.lastIndexOf("/");
12
+ return index > 0 ? path.slice(0, index) : void 0;
13
+ }
14
+ /**
15
+ * Runs an app in a WebContainer and keeps its state in Vue refs, for the workspace components of `@vite-hub/ui/workspace`
16
+ * or your own. Only one WebContainer runs per page.
17
+ */
18
+ function useWebContainer(options) {
19
+ const initial = { ...options.files };
20
+ const installCommand = options.install ?? "install";
21
+ const startCommand = options.start ?? "dev";
22
+ const status = ref("idle");
23
+ const steps = shallowRef([]);
24
+ const support = shallowRef();
25
+ const failure = shallowRef();
26
+ const files = shallowRef({ ...initial });
27
+ const fs = shallowRef();
28
+ const container = shallowRef();
29
+ const previewUrl = ref();
30
+ const logs = shallowRef(Object.assign([], { offset: 0 }));
31
+ const online = ref(true);
32
+ const modified = computed(() => {
33
+ const current = files.value;
34
+ return [.../* @__PURE__ */ new Set([...Object.keys(initial), ...Object.keys(current)])].filter((path) => initial[path] !== current[path]).sort();
35
+ });
36
+ const logLimit = 65536;
37
+ const logChunkLimit = 1e3;
38
+ const retainedLogs = [];
39
+ let retainedLength = 0;
40
+ let logEnd = 0;
41
+ let flushTimer;
42
+ function appendLog(chunk) {
43
+ if (disposed || !chunk) return;
44
+ logEnd += chunk.length;
45
+ const tail = chunk.slice(-65536);
46
+ retainedLogs.push(tail);
47
+ retainedLength += tail.length;
48
+ while (retainedLogs.length > logChunkLimit || retainedLength > logLimit) {
49
+ const first = retainedLogs[0];
50
+ const excess = retainedLength - logLimit;
51
+ if (retainedLogs.length > logChunkLimit || first.length <= excess) {
52
+ retainedLogs.shift();
53
+ retainedLength -= first.length;
54
+ } else {
55
+ retainedLogs[0] = first.slice(excess);
56
+ retainedLength -= excess;
57
+ }
58
+ }
59
+ flushTimer ??= setTimeout(() => {
60
+ flushTimer = void 0;
61
+ logs.value = Object.assign([...retainedLogs], { offset: logEnd - retainedLength });
62
+ }, 32);
63
+ }
64
+ let written = {};
65
+ let writes = Promise.resolve();
66
+ let booting;
67
+ let devRun;
68
+ let devPort;
69
+ let serverActive = false;
70
+ let recovery = Promise.resolve();
71
+ let disposed = false;
72
+ /** Writes `files` to the container. Rejects when a write fails. A later call tries the remaining writes again. */
73
+ function sync() {
74
+ const pending = writes.then(async () => {
75
+ const target = fs.value;
76
+ if (!target) return;
77
+ const current = files.value;
78
+ const conflictingDirectories = /* @__PURE__ */ new Set();
79
+ for (const path of Object.keys(written)) {
80
+ if (Object.hasOwn(current, path)) continue;
81
+ await target.rm(path, { force: true });
82
+ delete written[path];
83
+ let directory = parentDirectory(path);
84
+ while (directory) {
85
+ if (Object.keys(current).some((file) => directory === file || directory?.startsWith(`${file}/`))) conflictingDirectories.add(directory);
86
+ directory = parentDirectory(directory);
87
+ }
88
+ }
89
+ for (const directory of [...conflictingDirectories].sort((a, b) => b.length - a.length)) await target.rm(directory, { force: true });
90
+ for (const [path, contents] of Object.entries(current)) {
91
+ if (written[path] === contents) continue;
92
+ const directory = parentDirectory(path);
93
+ if (directory) await target.mkdir(directory, { recursive: true });
94
+ await target.writeFile(path, contents);
95
+ written[path] = contents;
96
+ }
97
+ }).catch((cause) => {
98
+ appendLog(`\r\nCould not write the files: ${toError(cause).message}\r\n`);
99
+ throw cause;
100
+ });
101
+ writes = pending.catch(() => {});
102
+ return pending;
103
+ }
104
+ function pipe(run) {
105
+ run.output.pipeTo(new WritableStream({ write: appendLog })).catch(() => {});
106
+ }
107
+ function env() {
108
+ const value = toValue(options.env);
109
+ return value && Object.keys(value).length > 0 ? { ...value } : void 0;
110
+ }
111
+ function enter(stage) {
112
+ const now = performance.now();
113
+ const previous = steps.value.map((step) => step.ms === void 0 ? {
114
+ ...step,
115
+ ms: now - step.startedAt
116
+ } : step);
117
+ status.value = stage;
118
+ steps.value = [...previous, {
119
+ stage,
120
+ startedAt: now,
121
+ ...stage === "ready" ? { ms: 0 } : {}
122
+ }];
123
+ }
124
+ async function startServer(target) {
125
+ if (disposed) return;
126
+ if (startCommand === false) {
127
+ enter("ready");
128
+ return;
129
+ }
130
+ serverActive = true;
131
+ enter("starting");
132
+ try {
133
+ const runEnv = env();
134
+ devPort = Number(runEnv?.PORT ?? options.port ?? 3e3);
135
+ const run = await target.run(startCommand, { env: runEnv });
136
+ if (disposed) {
137
+ run.kill();
138
+ return;
139
+ }
140
+ devRun = run;
141
+ pipe(run);
142
+ run.exit.then((exitCode) => {
143
+ if (devRun !== run) return;
144
+ devRun = void 0;
145
+ serverActive = false;
146
+ if (disposed) return;
147
+ previewUrl.value = void 0;
148
+ failure.value = {
149
+ kind: "server",
150
+ exitCode,
151
+ error: /* @__PURE__ */ new Error(`The dev server exited with code ${exitCode}.`)
152
+ };
153
+ status.value = "error";
154
+ });
155
+ } catch (cause) {
156
+ serverActive = false;
157
+ failure.value = {
158
+ kind: "server",
159
+ error: toError(cause)
160
+ };
161
+ status.value = "error";
162
+ }
163
+ }
164
+ async function installAndStart(target) {
165
+ failure.value = void 0;
166
+ if (installCommand !== false) {
167
+ enter("installing");
168
+ try {
169
+ const run = await target.run(installCommand, { env: env() });
170
+ pipe(run);
171
+ const exitCode = await run.exit;
172
+ if (disposed) return;
173
+ if (exitCode !== 0) {
174
+ failure.value = {
175
+ kind: "install",
176
+ exitCode,
177
+ error: target.status.error ?? /* @__PURE__ */ new Error(`npm install exited with code ${exitCode}.`)
178
+ };
179
+ status.value = "error";
180
+ return;
181
+ }
182
+ if (failure.value) return;
183
+ } catch (cause) {
184
+ failure.value = {
185
+ kind: "install",
186
+ error: toError(cause)
187
+ };
188
+ status.value = "error";
189
+ return;
190
+ }
191
+ }
192
+ await startServer(target);
193
+ }
194
+ function boot() {
195
+ if (booting) return booting;
196
+ if (container.value) return Promise.resolve();
197
+ failure.value = void 0;
198
+ steps.value = [];
199
+ booting = (async () => {
200
+ written = { ...files.value };
201
+ try {
202
+ const target = await bootWebContainer({
203
+ files: written,
204
+ snapshot: typeof options.snapshot === "function" ? options.snapshot() : options.snapshot,
205
+ port: options.port,
206
+ previewScript: options.previewScript,
207
+ onStatus(next) {
208
+ if (disposed) return;
209
+ if (next.stage === "error") {
210
+ failure.value ??= {
211
+ kind: status.value === "installing" ? "install" : container.value ? "server" : "boot",
212
+ error: next.error ?? /* @__PURE__ */ new Error("The workspace stopped unexpectedly.")
213
+ };
214
+ previewUrl.value = void 0;
215
+ }
216
+ status.value = failure.value ? "error" : next.stage;
217
+ steps.value = next.steps;
218
+ }
219
+ });
220
+ if (disposed) return target.teardown();
221
+ container.value = target;
222
+ fs.value = target.fs;
223
+ target.on("server-ready", (server) => {
224
+ if (!serverActive || disposed || failure.value) return;
225
+ if (server.port !== devPort) return;
226
+ previewUrl.value = server.url;
227
+ enter("ready");
228
+ });
229
+ await sync();
230
+ if (!failure.value) await installAndStart(target);
231
+ } catch (cause) {
232
+ const error = toError(cause);
233
+ failure.value = Reflect.get(error, "code") === "WEB_CONTAINER_UNSUPPORTED" ? {
234
+ kind: "unsupported",
235
+ error
236
+ } : {
237
+ kind: "boot",
238
+ error
239
+ };
240
+ status.value = failure.value.kind === "unsupported" ? "unsupported" : "error";
241
+ } finally {
242
+ booting = void 0;
243
+ }
244
+ })();
245
+ return booting;
246
+ }
247
+ async function stopServer() {
248
+ const run = devRun;
249
+ devRun = void 0;
250
+ serverActive = false;
251
+ previewUrl.value = void 0;
252
+ if (!run) return;
253
+ run.kill();
254
+ await run.exit.catch(() => {});
255
+ }
256
+ function recover(action) {
257
+ const pending = recovery.then(async () => {
258
+ if (booting) await booting;
259
+ if (disposed) return;
260
+ const target = container.value;
261
+ if (!target) return boot();
262
+ await stopServer();
263
+ if (!disposed) {
264
+ failure.value = void 0;
265
+ await action(target);
266
+ }
267
+ });
268
+ recovery = pending.catch(() => {});
269
+ return pending;
270
+ }
271
+ function install() {
272
+ return recover(installAndStart);
273
+ }
274
+ function restart() {
275
+ return recover(startServer);
276
+ }
277
+ async function setFiles(next, setOptions = {}) {
278
+ files.value = setOptions.mode === "replace" ? { ...next } : {
279
+ ...files.value,
280
+ ...next
281
+ };
282
+ await sync();
283
+ }
284
+ function teardown() {
285
+ disposed = true;
286
+ if (flushTimer) clearTimeout(flushTimer);
287
+ devRun = void 0;
288
+ container.value?.teardown();
289
+ container.value = void 0;
290
+ fs.value = void 0;
291
+ }
292
+ const browser = browserWindow();
293
+ if (browser) {
294
+ const update = () => {
295
+ online.value = browser.navigator.onLine;
296
+ };
297
+ browser.addEventListener("online", update);
298
+ browser.addEventListener("offline", update);
299
+ if (getCurrentScope()) onScopeDispose(() => {
300
+ browser.removeEventListener("online", update);
301
+ browser.removeEventListener("offline", update);
302
+ });
303
+ }
304
+ if (getCurrentScope()) onScopeDispose(teardown);
305
+ const start = () => {
306
+ if (browser) online.value = browser.navigator.onLine;
307
+ support.value = checkWebContainerSupport();
308
+ if (options.immediate !== false) boot();
309
+ };
310
+ if (getCurrentInstance()) onMounted(start);
311
+ else if (browser) start();
312
+ return {
313
+ status: readonly(status),
314
+ steps,
315
+ support,
316
+ failure,
317
+ error: computed(() => failure.value?.error),
318
+ files,
319
+ modified,
320
+ fs,
321
+ container,
322
+ previewUrl: readonly(previewUrl),
323
+ logs,
324
+ online: readonly(online),
325
+ boot,
326
+ install,
327
+ restart,
328
+ setFiles,
329
+ reset: () => setFiles(initial, { mode: "replace" }),
330
+ teardown
331
+ };
332
+ }
333
+ //#endregion
334
+ export { useWebContainer };
package/package.json CHANGED
@@ -1,14 +1,104 @@
1
1
  {
2
2
  "name": "@vite-hub/web-container",
3
- "version": "0.0.0",
4
- "description": "Placeholder. The first real release comes from github.com/vite-hub/vitehub.",
3
+ "version": "0.3.0",
4
+ "description": "Run a ViteHub app inside a StackBlitz WebContainer in the browser.",
5
+ "keywords": [
6
+ "browser",
7
+ "playground",
8
+ "stackblitz",
9
+ "typescript",
10
+ "vite",
11
+ "vitehub",
12
+ "vue",
13
+ "webcontainer"
14
+ ],
15
+ "homepage": "https://vitehub.dev",
16
+ "bugs": "https://github.com/vite-hub/vitehub/issues",
5
17
  "license": "Apache-2.0",
6
18
  "author": "onmax <maximogarciamtnez@gmail.com>",
7
- "homepage": "https://github.com/vite-hub/vitehub#readme",
8
19
  "repository": {
9
20
  "type": "git",
10
21
  "url": "git+https://github.com/vite-hub/vitehub.git",
11
22
  "directory": "packages/web-container"
12
23
  },
13
- "files": ["README.md"]
14
- }
24
+ "files": [
25
+ "dist",
26
+ "package.json"
27
+ ],
28
+ "type": "module",
29
+ "sideEffects": false,
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "import": "./dist/index.js",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "./connect": {
38
+ "types": "./dist/connect.d.ts",
39
+ "import": "./dist/connect.js",
40
+ "default": "./dist/connect.js"
41
+ },
42
+ "./env": {
43
+ "types": "./dist/env.d.ts",
44
+ "import": "./dist/env.js",
45
+ "default": "./dist/env.js"
46
+ },
47
+ "./snapshot": {
48
+ "types": "./dist/snapshot.d.ts",
49
+ "import": "./dist/snapshot.js",
50
+ "default": "./dist/snapshot.js"
51
+ },
52
+ "./vite": {
53
+ "types": "./dist/vite.d.ts",
54
+ "import": "./dist/vite.js",
55
+ "default": "./dist/vite.js"
56
+ },
57
+ "./vue": {
58
+ "types": "./dist/vue.d.ts",
59
+ "import": "./dist/vue.js",
60
+ "default": "./dist/vue.js"
61
+ },
62
+ "./package.json": "./package.json"
63
+ },
64
+ "dependencies": {
65
+ "@msgpack/msgpack": "3.1.3",
66
+ "@webcontainer/api": "1.6.4",
67
+ "nostics": "1.4.0"
68
+ },
69
+ "devDependencies": {
70
+ "@types/node": "^24.19.1",
71
+ "@vite-hub/internal": "0.0.1",
72
+ "@vue/test-utils": "2.5.1",
73
+ "happy-dom": "21.0.3",
74
+ "playwright-core": "^1.63.0",
75
+ "publint": "^0.3.25",
76
+ "typescript": "^6.0.3",
77
+ "vite": "^8.2.2",
78
+ "vite-plus": "^0.3.3",
79
+ "vitest": "^4.1.11",
80
+ "vue": "3.5.44"
81
+ },
82
+ "peerDependencies": {
83
+ "vite": ">=8.0.0",
84
+ "vue": "^3.5.0"
85
+ },
86
+ "peerDependenciesMeta": {
87
+ "vite": {
88
+ "optional": true
89
+ },
90
+ "vue": {
91
+ "optional": true
92
+ }
93
+ },
94
+ "engines": {
95
+ "node": ">=22.18.0"
96
+ },
97
+ "scripts": {
98
+ "build": "vp pack",
99
+ "dev": "vp pack --watch",
100
+ "typecheck": "vp run --cache -t @vite-hub/web-container#build && node ../../test/package-typecheck.mjs --noEmit -p ./tsconfig.json",
101
+ "test": "vp run --cache -t @vite-hub/web-container#build && vp test",
102
+ "test:browser": "vp run --cache -t @vite-hub/web-container#build && node --test test/browser/boot.browser.mjs"
103
+ }
104
+ }