@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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,221 @@
1
- # Temporary Holding Version
1
+ # @vite-hub/web-container
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://comark-ui.onmax.me/badge.svg?source=npm-version&package=%40vite-hub%2Fweb-container&icon=npm)](https://npmx.dev/package/@vite-hub/web-container)
4
+ [![npm downloads](https://comark-ui.onmax.me/badge.svg?source=npm-downloads&package=%40vite-hub%2Fweb-container&period=month&icon=npm)](https://npmx.dev/package/@vite-hub/web-container)
5
+ [![license](https://comark-ui.onmax.me/badge.svg?label=license&value=Apache-2.0)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
+ [![docs](https://comark-ui.onmax.me/badge.svg?label=docs&value=vitehub.dev)](https://vitehub.dev/docs)
7
+
8
+ `@vite-hub/web-container` runs a ViteHub app in the reader's browser tab, inside a [StackBlitz WebContainer](https://webcontainers.io). Docs tutorials and playgrounds use it to install, start, and preview an app without a server of ours.
9
+
10
+ Read the [WebContainer docs](https://vitehub.dev/docs/web-container) for a tutorial, snapshots, and the API reference.
11
+
12
+ Install this owner package directly, or import the same API from `vite-hub/web-container` when your app already uses the `vite-hub` framework distribution.
13
+
14
+ ```sh
15
+ pnpm add @vite-hub/web-container
16
+ ```
17
+
18
+ | Entry | Runs in | Use it to |
19
+ | --- | --- | --- |
20
+ | `@vite-hub/web-container` | Browser | Boot a container, mount files, run commands, read the preview |
21
+ | `@vite-hub/web-container/vite` | Vite config | Make the playground pages cross-origin isolated |
22
+ | `@vite-hub/web-container/env` | Any | Detect code that runs inside a WebContainer |
23
+ | `@vite-hub/web-container/connect` | Any | Describe which accounts a reader can connect, and map them to `env` |
24
+ | `@vite-hub/web-container/vue` | Browser, Vue | Run an app with `useWebContainer()` and keep its state in refs |
25
+
26
+ ## Make the page cross-origin isolated
27
+
28
+ A WebContainer needs `SharedArrayBuffer`, so the page that boots it must send `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: credentialless`. Set these headers only on the pages that boot a container. Other pages keep cross-origin embeds, such as videos, working.
29
+
30
+ ```ts
31
+ import { defineConfig } from "vite"
32
+ import { hubWebContainer } from "@vite-hub/web-container/vite"
33
+
34
+ export default defineConfig({
35
+ plugins: [hubWebContainer({ routes: ["/playground/**"] })],
36
+ })
37
+ ```
38
+
39
+ The plugin sets the headers in `vite dev` and `vite preview`. `/playground` matches that path only. `/playground/**` matches it and every path below it.
40
+
41
+ In production, set the same headers with Nitro route rules:
42
+
43
+ ```ts fragment
44
+ import { webContainerHeaders } from "@vite-hub/web-container/vite"
45
+
46
+ export default defineNitroConfig({
47
+ routeRules: {
48
+ "/playground/**": { headers: webContainerHeaders },
49
+ },
50
+ })
51
+ ```
52
+
53
+ ## Boot an app and open its preview
54
+
55
+ ```ts
56
+ import { bootWebContainer } from "@vite-hub/web-container"
57
+
58
+ const container = await bootWebContainer({
59
+ files: {
60
+ "package.json": JSON.stringify({ type: "module", scripts: { dev: "node server.js" } }),
61
+ "server.js": `import { createServer } from "node:http"
62
+ createServer((req, res) => res.end("Hello from " + process.version)).listen(process.env.PORT)`,
63
+ },
64
+ })
65
+
66
+ await (await container.run("install")).exit
67
+ const dev = await container.run("dev")
68
+ dev.output.pipeTo(new WritableStream({ write: chunk => console.log(chunk) }))
69
+
70
+ const { url } = await container.preview.ready
71
+ document.querySelector("iframe")!.src = url
72
+ ```
73
+
74
+ - `run("install")` runs `npm install`. `run("dev")` and `run("build")` run the npm scripts of the app. Pass an array, such as `run(["node", "scripts/seed.js"])`, to run any command line.
75
+ - Only one `run("dev")` may be active, including while it is spawning. Another call rejects until the process exits; call `kill()` and await `exit` before restarting it.
76
+ - A run returns `output` (a stream that you read once), `exit` (the exit code), `text()` (the last 65,536 output characters after exit), `write(input)`, and `kill()`. The stream buffers up to 65,536 characters and drops excess output until its reader catches up, so an idle terminal cannot accumulate unlimited logs. Pass `signal` to kill it with an `AbortController`.
77
+ - `container.preview.ready` resolves with the app server. It rejects if startup fails or the container is torn down before readiness. `run()` passes `PORT=3000` to every process, and `vite dev` with `vitehub()` and `node .output/server/index.mjs` listen on it. Only the server on that port becomes the preview, not the workers that Nitro starts on random ports first. Pass `bootWebContainer({ port })` to use another port, or `env: { PORT }` on one run. Read `url` from it, because the preview origin is not `localhost`. `run()` also passes `NODE_OPTIONS=--disable-warning=ExperimentalWarning`, because Vite loads the WASI build of Rolldown here and Node warns on each load. Pass your own `NODE_OPTIONS` to replace it.
78
+ - `container.on("server-ready", ({ url, port }) => …)` subscribes to every server readiness event, including custom commands and later restarts. It returns an unsubscribe function.
79
+ - Show the preview in an `<iframe>` on the same page. The preview origin does not answer a `fetch()` from the page.
80
+ - Pass `bootWebContainer({ previewScript })` to run JavaScript first in every HTML page of the preview. The page cannot reach into the cross-origin preview frame, so this is how it learns the address of the preview page, or sends it Back and Forward. `WorkspacePreview` of `@vite-hub/ui/workspace` exports such a script as `workspacePreviewScript`.
81
+ - `container.fs` is the WebContainer file system API (`readFile`, `writeFile`, `readdir`, `mkdir`, `rm`, `watch`).
82
+ - Only one container runs per page. Call `container.teardown()` before you boot another.
83
+
84
+ ### Render a boot checklist
85
+
86
+ Each status change carries the latest stage and every step so far, with its duration in milliseconds:
87
+
88
+ ```ts fragment
89
+ const container = await bootWebContainer({
90
+ files,
91
+ onStatus: ({ stage, steps, error }) => renderChecklist(stage, steps, error),
92
+ })
93
+ container.on("status", status => renderChecklist(status.stage, status.steps, status.error))
94
+ ```
95
+
96
+ The stages are `checking`, `unsupported`, `booting`, `mounting`, `installing`, `starting`, `ready`, and `error`. `installing` starts with `run("install")`. `starting` starts with `run("dev")` and becomes `ready` when the preview server is ready.
97
+
98
+ To show a notice before the reader clicks run, call `checkWebContainerSupport()`. It checks `crossOriginIsolated` and `SharedArrayBuffer`, not the browser name. `bootWebContainer()` throws `WEB_CONTAINER_UNSUPPORTED` with the same reason.
99
+
100
+ ### Skip the install with a snapshot
101
+
102
+ An `npm install` of a ViteHub Agent app in a WebContainer takes minutes. Build the `node_modules` snapshot on your machine or in CI instead, and the container never installs:
103
+
104
+ ```ts
105
+ import { createHash } from "node:crypto"
106
+ import { existsSync, readFileSync, writeFileSync } from "node:fs"
107
+
108
+ // Node, at build time
109
+ import { createNodeModulesSnapshot, packSnapshot } from "@vite-hub/web-container/snapshot"
110
+
111
+ const lockfile = existsSync("app.package-lock.json") ? readFileSync("app.package-lock.json", "utf8") : undefined
112
+ // Runs `npm ci` in build/app with the lockfile, or `npm install` without one.
113
+ const { snapshot, lockfile: next } = await createNodeModulesSnapshot({ dir: "build/app", lockfile })
114
+ writeFileSync("app.package-lock.json", next) // keep it, so the next build installs the same versions
115
+ const parts = packSnapshot(snapshot) // gzip, split into parts of at most 20 MiB
116
+ const sha256 = createHash("sha256").update(Buffer.concat(parts)).digest("hex")
117
+ parts.forEach((part, index) => writeFileSync(`public/app-modules.${sha256.slice(0, 12)}.${index}.bin`, part))
118
+ ```
119
+
120
+ ```ts fragment
121
+ // Browser
122
+ import { bootWebContainer, fetchSnapshot } from "@vite-hub/web-container"
123
+
124
+ const container = await bootWebContainer({
125
+ snapshot: fetchSnapshot(partUrls, { cache: "my-app-modules", sha256 }),
126
+ files,
127
+ })
128
+ await container.run("dev")
129
+ ```
130
+
131
+ `createNodeModulesSnapshot()` requires Linux, macOS, or WSL. It rejects Windows before changing files, because npm's Windows command shims cannot be restored as POSIX bin links. It installs as npm in a WebContainer does: it uses `--cpu=wasm32`, so no native binaries download, it swaps `esbuild`, `lightningcss`, and `@libsql/client` for their wasm builds, and it adds `@rolldown/binding-wasm32-wasi`, which rolldown otherwise downloads on first use. The wasm builds install as npm aliases in the same install, so the returned `lockfile` pins every version: pass it back and the install runs `npm ci`, and the same lockfile gives the same snapshot bytes. A lockfile that no longer matches the app throws `WEB_CONTAINER_SNAPSHOT_LOCKFILE_MISMATCH`, and so does one that installs a `file:` tarball that the app no longer has; pass `frozenLockfile: false` to update it. The update reads every `file:` tarball again and keeps the registry versions it can. Other install and snapshot errors propagate unchanged. The original `package.json` is restored exactly on success and failure. The integrity of `file:` tarballs is left out of the lockfile, because a rebuilt tarball changes it. Install scripts do not run, and source maps are left out. A snapshot cannot hold symlinks or executable bits, so it lists them, and `bootWebContainer()` restores them after the mount. Link and executable paths must stay inside the working directory, and so must link targets: the builder leaves out other links, and the restore step skips other entries, because the snapshot bytes come from the network.
132
+
133
+ `fetchSnapshot()` downloads the parts in parallel and inflates them. With `sha256`, it rejects parts whose hash differs. With `cache`, it keeps the parts in Cache Storage, so a later boot downloads nothing. A part goes into the cache only after the whole snapshot inflates and matches its hash; a damaged snapshot removes its parts from the cache, so the next boot downloads them again. Give each snapshot version its own URLs, such as names with a content hash, and each app its own cache name: parts of other URLs in that cache are deleted. `bootWebContainer()` boots while the snapshot loads.
134
+
135
+ To reuse a container's own install, `container.export()` returns a binary snapshot of the working directory. Pass `excludes` (glob patterns) to leave files out. `files` is mounted after the snapshot, so it can replace files from it.
136
+
137
+ Use one container for each app. One container failed with `RangeError: Offset is outside the bounds of the DataView` after two full ViteHub installs.
138
+
139
+ ## Run it from Vue
140
+
141
+ `useWebContainer()` from `@vite-hub/web-container/vue` boots an app and keeps its state in Vue refs. The workspace parts of [`@vite-hub/ui/workspace`](../ui/README.md#run-an-app-in-the-browser) render that state. Only one WebContainer runs per page.
142
+
143
+ ```ts
144
+ import { useWebContainer } from "@vite-hub/web-container/vue"
145
+
146
+ const app = useWebContainer({ files: { "package.json": "...", "server.js": "..." } })
147
+ ```
148
+
149
+ - `useWebContainer({ files, snapshot?, install?, start?, port?, env?, immediate? })` boots when the component mounts, installs, and starts the dev server. Pass `snapshot: () => fetchSnapshot(urls)` with `install: false` to skip the install; the function runs only when the workspace boots. Only the server on `port` (default `3000`, given to the dev server as `PORT`), or on `env.PORT`, becomes the preview. Pass `port` when the dev server listens on another port. It returns `status`, `steps` (with timings), `support`, `failure` (`unsupported`, `boot`, `install`, or `server`, with the exit code), `files`, `modified`, `fs`, `previewUrl`, `logs`, and `online`.
150
+ - `setFiles(files, { mode: "merge" | "replace" })` writes to the container and rejects when a write fails. Edits made before the mount ends are written when it ends. `reset()` puts back the original files. `install()` runs the install again, and `restart()` restarts the dev server.
151
+ - `env` is read on each run, so pass a getter or a computed, such as `useConnectStore().env(connect)` from `@vite-hub/ui/workspace`.
152
+ - `logs` retains the latest output, up to 65,536 characters and 1,000 chunks. Older output is dropped. Its array carries an `offset` counting dropped characters; pass it directly to `WorkspaceTerminal` to keep writes incremental across rollover. Ordinary arrays still append by prefix and clear the terminal when replaced.
153
+
154
+ ## Pass secrets per process
155
+
156
+ `run()` takes `env` for that process only. Nothing is stored in the container or sent to a ViteHub server:
157
+
158
+ ```ts fragment
159
+ await container.run("dev", { env: { OPENAI_API_KEY: key } })
160
+ ```
161
+
162
+ ## Describe connectable accounts
163
+
164
+ `@vite-hub/web-container/connect` describes the accounts that a page offers. It runs no OAuth flow yet.
165
+
166
+ ```ts fragment
167
+ import { connectEnv, defineConnect } from "@vite-hub/web-container/connect"
168
+
169
+ const connect = defineConnect({
170
+ vercel: { clientId: "oac_..." }, // without clientId, the reader pastes a token
171
+ github: true, // without { app }, the reader pastes a fine-grained token
172
+ netlify: true,
173
+ openai: true,
174
+ anthropic: true,
175
+ cloudflare: { relay: "reader" }, // the Cloudflare API has no CORS, so calls go through a relay that the reader deploys
176
+ })
177
+
178
+ await container.run("dev", { env: connectEnv(connect, { openai: key }) })
179
+ ```
180
+
181
+ Each provider has a `kind` (`deploy`, `source`, or `model`), a `reach` (`browser` or `relay`), an `auth` (`oauth` or `token`), and the `env` variable that receives the credential.
182
+
183
+ | Provider | Kind | Reach | Env |
184
+ | --- | --- | --- | --- |
185
+ | `anthropic` | model | browser | `ANTHROPIC_API_KEY` |
186
+ | `cloudflare` | deploy | relay | `CLOUDFLARE_API_TOKEN` |
187
+ | `github` | source | browser | `GITHUB_TOKEN` |
188
+ | `netlify` | deploy | browser | `NETLIFY_AUTH_TOKEN` |
189
+ | `openai` | model | browser | `OPENAI_API_KEY` |
190
+ | `vercel` | deploy | browser | `VERCEL_TOKEN` |
191
+
192
+ ## Detect a WebContainer
193
+
194
+ ```ts
195
+ import { isWebContainer } from "@vite-hub/web-container/env"
196
+
197
+ const driver = isWebContainer() ? "libsql" : "sqlite"
198
+ ```
199
+
200
+ Primitive packages use this to choose a driver that works in a WebContainer.
201
+
202
+ ## Limits
203
+
204
+ - Node is 22.22.3 and cannot be changed. `engines` and `.nvmrc` are ignored.
205
+ - `node:sqlite` loads but has no `exec()` or `prepare()`. Use `@libsql/client` with a `file:` URL.
206
+ - workerd and Miniflare cannot run, so the Cloudflare host cannot run locally in a container.
207
+ - Outbound `fetch()` from the app is subject to CORS from a StackBlitz origin. A blocked request fails with `SocketError: other side closed`.
208
+ - Spawned arguments lose backslashes. Mount a script file and run it instead of `node -e`.
209
+
210
+ ## Inspect
211
+
212
+ Everything this package does runs in the reader's tab, so there is no server state to list yet. Read `container.status` for the stages and timings of a run. The docs build writes the tutorial snapshots with `createNodeModulesSnapshot()` (`docs/modules/tutorials/snapshots.ts`).
213
+
214
+ ## Test
215
+
216
+ ```sh
217
+ pnpm --filter @vite-hub/web-container test # unit tests in Node
218
+ pnpm --filter @vite-hub/web-container test:browser # boots a real WebContainer in headless Chromium
219
+ ```
220
+
221
+ The browser test needs a Playwright Chromium (`pnpm exec playwright-core install chromium`) and network access to StackBlitz. Set `WEB_CONTAINER_TEST_PORT` to change its port (default `4793`).
@@ -0,0 +1,55 @@
1
+ //#region src/connect.d.ts
2
+ export type ConnectProviderName = "anthropic" | "cloudflare" | "github" | "netlify" | "openai" | "vercel";
3
+ /** `deploy` targets a host. `source` reads and writes repositories. `model` calls an AI model. */
4
+ export type ConnectProviderKind = "deploy" | "model" | "source";
5
+ /**
6
+ * `browser`: the provider API accepts requests from a StackBlitz origin (CORS).
7
+ * `relay`: the provider API has no CORS, so calls need a relay that the reader deploys.
8
+ */
9
+ export type ConnectReach = "browser" | "relay";
10
+ /** `oauth`: the reader signs in through the configured app. `token`: the reader pastes a token or key. */
11
+ export type ConnectAuth = "oauth" | "token";
12
+ export interface ConnectProvider {
13
+ name: ConnectProviderName;
14
+ kind: ConnectProviderKind;
15
+ reach: ConnectReach;
16
+ auth: ConnectAuth;
17
+ /** The environment variable that receives the credential. */
18
+ env: string;
19
+ /** OAuth client ID (Vercel). */
20
+ clientId?: string;
21
+ /** GitHub App slug. */
22
+ app?: string;
23
+ /** Who deploys the relay. Only `reader` exists today. */
24
+ relay?: "reader";
25
+ }
26
+ export interface ConnectConfig {
27
+ /** Without `clientId` the reader pastes a Vercel token. */
28
+ vercel?: true | {
29
+ clientId?: string;
30
+ };
31
+ /** Without `app` the reader pastes a fine-grained token. */
32
+ github?: true | {
33
+ app?: string;
34
+ };
35
+ netlify?: true;
36
+ openai?: true;
37
+ anthropic?: true;
38
+ /** The Cloudflare API has no CORS, so the reader deploys a relay. */
39
+ cloudflare?: {
40
+ relay: "reader";
41
+ };
42
+ }
43
+ export interface Connect {
44
+ providers: readonly ConnectProvider[];
45
+ }
46
+ /** Connected credentials, keyed by provider name. */
47
+ export type ConnectCredentials = Partial<Record<ConnectProviderName, string>>;
48
+ /** Describes the providers a page offers, in a fixed order. */
49
+ export declare function defineConnect(config: ConnectConfig): Connect;
50
+ /**
51
+ * Maps connected credentials to the `env` of one `container.run()` call.
52
+ * Providers that are not configured, or have no credential, are left out.
53
+ */
54
+ export declare function connectEnv(connect: Connect, credentials: ConnectCredentials): Record<string, string>;
55
+ //#endregion
@@ -0,0 +1,97 @@
1
+ import { t as webContainerErrorDiagnostics } from "./error-diagnostics-DDPkdBo-.js";
2
+ //#region src/connect.ts
3
+ /**
4
+ * Accounts a reader can connect to a WebContainer app: deploy targets, a source host, and model providers.
5
+ *
6
+ * This entry only describes providers. It runs no OAuth flow yet. A connected credential stays in the
7
+ * browser tab and reaches the app only as an environment variable of one `container.run()` call.
8
+ */
9
+ const defaults = {
10
+ anthropic: {
11
+ name: "anthropic",
12
+ kind: "model",
13
+ reach: "browser",
14
+ env: "ANTHROPIC_API_KEY"
15
+ },
16
+ cloudflare: {
17
+ name: "cloudflare",
18
+ kind: "deploy",
19
+ reach: "relay",
20
+ env: "CLOUDFLARE_API_TOKEN"
21
+ },
22
+ github: {
23
+ name: "github",
24
+ kind: "source",
25
+ reach: "browser",
26
+ env: "GITHUB_TOKEN"
27
+ },
28
+ netlify: {
29
+ name: "netlify",
30
+ kind: "deploy",
31
+ reach: "browser",
32
+ env: "NETLIFY_AUTH_TOKEN"
33
+ },
34
+ openai: {
35
+ name: "openai",
36
+ kind: "model",
37
+ reach: "browser",
38
+ env: "OPENAI_API_KEY"
39
+ },
40
+ vercel: {
41
+ name: "vercel",
42
+ kind: "deploy",
43
+ reach: "browser",
44
+ env: "VERCEL_TOKEN"
45
+ }
46
+ };
47
+ function isProviderName(name) {
48
+ return Object.hasOwn(defaults, name);
49
+ }
50
+ /** Describes the providers a page offers, in a fixed order. */
51
+ function defineConnect(config) {
52
+ for (const name of Object.keys(config)) if (!isProviderName(name)) throw webContainerErrorDiagnostics.WEB_CONTAINER_CONNECT_PROVIDER_UNKNOWN({
53
+ choices: Object.keys(defaults).sort().join(", "),
54
+ name
55
+ });
56
+ const providers = [];
57
+ for (const name of Object.keys(defaults).sort()) {
58
+ if (!isProviderName(name)) continue;
59
+ const options = config[name];
60
+ if (!options) continue;
61
+ const base = defaults[name];
62
+ if (name === "vercel" && options !== true && "clientId" in options && options.clientId) providers.push({
63
+ ...base,
64
+ auth: "oauth",
65
+ clientId: options.clientId
66
+ });
67
+ else if (name === "github" && options !== true && "app" in options && options.app) providers.push({
68
+ ...base,
69
+ auth: "oauth",
70
+ app: options.app
71
+ });
72
+ else if (name === "cloudflare") providers.push({
73
+ ...base,
74
+ auth: "token",
75
+ relay: "reader"
76
+ });
77
+ else providers.push({
78
+ ...base,
79
+ auth: "token"
80
+ });
81
+ }
82
+ return { providers };
83
+ }
84
+ /**
85
+ * Maps connected credentials to the `env` of one `container.run()` call.
86
+ * Providers that are not configured, or have no credential, are left out.
87
+ */
88
+ function connectEnv(connect, credentials) {
89
+ const env = {};
90
+ for (const provider of connect.providers) {
91
+ const credential = credentials[provider.name];
92
+ if (credential) env[provider.env] = credential;
93
+ }
94
+ return env;
95
+ }
96
+ //#endregion
97
+ export { connectEnv, defineConnect };
package/dist/env.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ //#region src/env.d.ts
2
+ /**
3
+ * Returns true when this code runs inside a StackBlitz WebContainer.
4
+ *
5
+ * Primitive packages use it to pick a local driver that works there, for example libSQL instead of `node:sqlite`.
6
+ * WebContainers set `process.versions.webcontainer`. `@webcontainer/env` reads the same field after it requires a
7
+ * StackBlitz-only module, which a Worker bundle cannot leave external, so server code that imports this stays bundleable.
8
+ */
9
+ export declare function isWebContainer(): boolean;
10
+ //#endregion
package/dist/env.js ADDED
@@ -0,0 +1,13 @@
1
+ //#region src/env.ts
2
+ /**
3
+ * Returns true when this code runs inside a StackBlitz WebContainer.
4
+ *
5
+ * Primitive packages use it to pick a local driver that works there, for example libSQL instead of `node:sqlite`.
6
+ * WebContainers set `process.versions.webcontainer`. `@webcontainer/env` reads the same field after it requires a
7
+ * StackBlitz-only module, which a Worker bundle cannot leave external, so server code that imports this stays bundleable.
8
+ */
9
+ function isWebContainer() {
10
+ return typeof process !== "undefined" && process.versions?.webcontainer != null;
11
+ }
12
+ //#endregion
13
+ export { isWebContainer };
@@ -0,0 +1,53 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/error-diagnostics.ts
3
+ const webContainerErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
4
+ docsBase: "https://vitehub.dev/docs/web-container/diagnostics",
5
+ codes: {
6
+ WEB_CONTAINER_CONNECT_PROVIDER_UNKNOWN: {
7
+ why: ({ choices, name }) => `Unknown connect provider "${name}". Use one of: ${choices}.`,
8
+ fix: "Pass only the provider names that the message lists as keys of `defineConnect()`."
9
+ },
10
+ WEB_CONTAINER_DEV_RUNNING: {
11
+ why: "A dev process is already running. Stop it and await its exit before starting another.",
12
+ fix: "Call `kill()` on the running `run(\"dev\")` result and await its `exit` before you call `run(\"dev\")` again."
13
+ },
14
+ WEB_CONTAINER_FILE_PATH_INVALID: {
15
+ why: ({ part, path, reason }) => reason === "through-file" ? `WebContainer path ${path} goes through the file ${part}.` : reason === "replaces-directory" ? `WebContainer path ${path} replaces the directory ${part}.` : `Invalid WebContainer file path: ${path}`,
16
+ fix: "Give each key of `files` a relative path to a file, such as `server/index.js`, without `..`, a leading `/`, or a path that is also a file or folder of another key."
17
+ },
18
+ WEB_CONTAINER_ROUTES_MISSING: {
19
+ why: "hubWebContainer() needs at least one route, such as \"/playground/**\".",
20
+ fix: "List the pages that boot a WebContainer in the `routes` option of `hubWebContainer`, such as `routes: [\"/playground/**\"]`."
21
+ },
22
+ WEB_CONTAINER_ROUTE_INVALID: {
23
+ why: ({ route }) => `hubWebContainer() route "${route}" must start with "/".`,
24
+ fix: "Start each route in the `routes` option of `hubWebContainer` with `/`, such as `\"/playground/**\"`."
25
+ },
26
+ WEB_CONTAINER_SNAPSHOT_DAMAGED: {
27
+ why: ({ detail, url }) => `The snapshot from ${url} is damaged: ${detail}`,
28
+ fix: "Serve the parts that `packSnapshot()` wrote, in order and unchanged, and pass the `sha256` of the same build to `fetchSnapshot()`. Build the snapshot again if the parts changed."
29
+ },
30
+ WEB_CONTAINER_SNAPSHOT_LINKS_FAILED: {
31
+ why: ({ code }) => `Restoring the links of the snapshot exited with code ${code}.`,
32
+ fix: "Build the snapshot again with `createNodeModulesSnapshot()` from `@vite-hub/web-container/snapshot`, and pass it to `bootWebContainer({ snapshot })`."
33
+ },
34
+ WEB_CONTAINER_SNAPSHOT_LOCKFILE_MISMATCH: {
35
+ why: ({ file, wasm }) => file ? `The lockfile installs ${file}, which the app does not have.` : wasm ? "The lockfile does not match the app: its wasm builds have other versions. Pass frozenLockfile: false to update it." : "The lockfile does not match the app. Pass frozenLockfile: false to update it.",
36
+ fix: "Pass `frozenLockfile: false` to `createNodeModulesSnapshot()` to update the lockfile, then save the `lockfile` of its result."
37
+ },
38
+ WEB_CONTAINER_SNAPSHOT_PART_BYTES_INVALID: {
39
+ why: "partBytes must be a positive safe integer.",
40
+ fix: "Pass a whole number of bytes above 0 as `partBytes` to `packSnapshot()`, such as `20 * 2 ** 20`, or leave it out."
41
+ },
42
+ WEB_CONTAINER_SNAPSHOT_PART_FAILED: {
43
+ why: ({ status, url }) => `Snapshot part ${url} returned ${status}.`,
44
+ fix: "Check that the host serves each URL that you pass to `fetchSnapshot()`, for example the files that `packSnapshot()` wrote in the public folder. A retry helps only for a temporary server error."
45
+ },
46
+ WEB_CONTAINER_SNAPSHOT_POSIX_REQUIRED: {
47
+ why: "createNodeModulesSnapshot requires a POSIX host (Linux, macOS, or WSL).",
48
+ fix: "Run `createNodeModulesSnapshot()` on Linux or macOS, or in WSL on Windows."
49
+ }
50
+ }
51
+ });
52
+ //#endregion
53
+ export { webContainerErrorDiagnostics as t };