@vivari/react 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # @vivari/react
2
+
3
+ React bindings for [Vivari](../core) — run Node.js projects fully client-side in
4
+ the browser, embedded in your React app.
5
+
6
+ ```bash
7
+ npm install @vivari/react @vivari/core react
8
+ ```
9
+
10
+ > Like all of Vivari, this needs a **cross-origin isolated** page
11
+ > (`Cross-Origin-Opener-Policy: same-origin` + `Cross-Origin-Embedder-Policy:
12
+ > require-corp`). See the [core README](../core/README.md).
13
+
14
+ ## `<Vivari>` component
15
+
16
+ Boots an instance, mounts `files`, runs `install` then `run`, and renders the
17
+ resulting dev-server preview in an `<iframe>`.
18
+
19
+ ```tsx
20
+ import { Vivari } from "@vivari/react";
21
+
22
+ const files = {
23
+ "package.json": {
24
+ file: { contents: JSON.stringify({ name: "app", scripts: { dev: "vite" } }) },
25
+ },
26
+ "index.html": { file: { contents: "<h1>Hello from Vivari</h1>" } },
27
+ };
28
+
29
+ export function Playground() {
30
+ return (
31
+ <Vivari
32
+ files={files}
33
+ run="npm run dev"
34
+ onServerReady={(port, url) => console.log("ready", port, url)}
35
+ onOutput={(chunk) => console.log(chunk)}
36
+ style={{ width: "100%", height: 480, border: 0 }}
37
+ fallback={<p>Booting Vivari…</p>}
38
+ />
39
+ );
40
+ }
41
+ ```
42
+
43
+ ### Props
44
+
45
+ Extends `BootOptions` (`compress`, `serviceWorkerUrl`, `workerName`), plus:
46
+
47
+ | prop | type | default |
48
+ | --------------- | ----------------------------------- | -------------------- |
49
+ | `files` | `FileSystemTree` | – |
50
+ | `install` | `string \| string[] \| false` | `["npm", "install"]` |
51
+ | `run` | `string \| string[]` | – |
52
+ | `onReady` | `(vivari) => void` | – |
53
+ | `onServerReady` | `(port, url) => void` | – |
54
+ | `onOutput` | `(chunk) => void` | – |
55
+ | `showPreview` | `boolean` | `true` |
56
+ | `className` | `string` | – |
57
+ | `style` | `CSSProperties` | – |
58
+ | `fallback` | `ReactNode` | `null` |
59
+
60
+ ## `useVivari()` hook
61
+
62
+ For full control, boot an instance and drive it yourself:
63
+
64
+ ```tsx
65
+ import { useVivari } from "@vivari/react";
66
+
67
+ function Terminal() {
68
+ const { vivari, status, error } = useVivari();
69
+
70
+ useEffect(() => {
71
+ if (status !== "ready" || !vivari) return;
72
+ (async () => {
73
+ const proc = await vivari.spawn("node", ["-e", "console.log(2 + 2)"]);
74
+ await proc.output.pipeTo(new WritableStream({ write: console.log }));
75
+ })();
76
+ }, [status, vivari]);
77
+
78
+ if (status === "error") return <p>Failed: {error?.message}</p>;
79
+ return <p>{status}</p>;
80
+ }
81
+ ```
82
+
83
+ The instance is torn down on unmount. Options are read once — change them by
84
+ remounting (e.g. with a React `key`).
85
+
86
+ ## License
87
+
88
+ MIT © Duc Trung Mai
@@ -0,0 +1,34 @@
1
+ import { type CSSProperties, type ReactNode } from "react";
2
+ import type { BootOptions, FileSystemTree, Vivari as VivariInstance } from "@vivari/core";
3
+ import { type VivariStatus } from "./useVivari";
4
+ export interface VivariProps extends BootOptions {
5
+ /** Files to mount into the VM before running commands. */
6
+ files?: FileSystemTree;
7
+ /** Install step. Default `["npm", "install"]`; pass `false` to skip. */
8
+ install?: string | string[] | false;
9
+ /** Command to run after install, e.g. `["npm", "run", "dev"]` or `"npm run dev"`. */
10
+ run?: string | string[];
11
+ /** Called once the instance is booted and files are mounted. */
12
+ onReady?: (vivari: VivariInstance) => void;
13
+ /** Called when an in-VM server starts listening; `url` is the preview URL. */
14
+ onServerReady?: (port: number, url: string) => void;
15
+ /** Called for each stdout/stderr chunk of the install + run commands. */
16
+ onOutput?: (chunk: string) => void;
17
+ /** Render the preview <iframe> when a server is ready. Default `true`. */
18
+ showPreview?: boolean;
19
+ className?: string;
20
+ style?: CSSProperties;
21
+ /** Shown while booting / before a preview URL exists. */
22
+ fallback?: ReactNode;
23
+ }
24
+ /**
25
+ * Drop-in embed: boots Vivari, mounts `files`, runs `install` then `run`, and
26
+ * renders the resulting dev-server preview in an <iframe>.
27
+ *
28
+ * <Vivari files={tree} run="npm run dev" style={{ height: 480 }} />
29
+ *
30
+ * The host page must be cross-origin isolated (COOP + COEP).
31
+ */
32
+ export declare function Vivari(props: VivariProps): ReactNode;
33
+ export type { VivariStatus };
34
+ //# sourceMappingURL=Vivari.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Vivari.d.ts","sourceRoot":"","sources":["../src/Vivari.tsx"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,aAAa,EAAE,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AACxF,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,IAAI,cAAc,EAAE,MAAM,cAAc,CAAC;AAC1F,OAAO,EAAa,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3D,MAAM,WAAW,WAAY,SAAQ,WAAW;IAC9C,0DAA0D;IAC1D,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,KAAK,CAAC;IACpC,qFAAqF;IACrF,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACxB,gEAAgE;IAChE,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,cAAc,KAAK,IAAI,CAAC;IAC3C,8EAA8E;IAC9E,aAAa,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IACpD,yEAAyE;IACzE,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,0EAA0E;IAC1E,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,yDAAyD;IACzD,QAAQ,CAAC,EAAE,SAAS,CAAC;CACtB;AAyDD;;;;;;;GAOG;AACH,wBAAgB,MAAM,CAAC,KAAK,EAAE,WAAW,GAAG,SAAS,CA8GpD;AAED,YAAY,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1,6 @@
1
+ export { Vivari } from "./Vivari";
2
+ export type { VivariProps, VivariStatus } from "./Vivari";
3
+ export { useVivari } from "./useVivari";
4
+ export type { UseVivariResult } from "./useVivari";
5
+ export type { BootOptions, FileSystemTree, SpawnOptions, Vivari as VivariInstance, } from "@vivari/core";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,YAAY,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAGnD,YAAY,EACV,WAAW,EACX,cAAc,EACd,YAAY,EACZ,MAAM,IAAI,cAAc,GACzB,MAAM,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,172 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { Vivari as Vivari$1 } from "@vivari/core";
3
+ import { jsx, jsxs } from "react/jsx-runtime";
4
+ //#region src/useVivari.ts
5
+ /**
6
+ * Boot a {@link Vivari} instance for the lifetime of the component.
7
+ *
8
+ * The instance is torn down on unmount. Options are read once, on the first
9
+ * render — change them by remounting (e.g. with a React `key`).
10
+ */
11
+ function useVivari(options) {
12
+ const [vivari, setVivari] = useState(null);
13
+ const [status, setStatus] = useState("booting");
14
+ const [error, setError] = useState(null);
15
+ useEffect(() => {
16
+ let cancelled = false;
17
+ let instance = null;
18
+ setStatus("booting");
19
+ Vivari$1.boot(options).then((v) => {
20
+ instance = v;
21
+ if (cancelled) {
22
+ v.teardown();
23
+ return;
24
+ }
25
+ setVivari(v);
26
+ setStatus("ready");
27
+ }).catch((e) => {
28
+ if (cancelled) return;
29
+ setError(e instanceof Error ? e : new Error(String(e)));
30
+ setStatus("error");
31
+ });
32
+ return () => {
33
+ cancelled = true;
34
+ instance?.teardown();
35
+ setVivari(null);
36
+ };
37
+ }, []);
38
+ return {
39
+ vivari,
40
+ status,
41
+ error
42
+ };
43
+ }
44
+ //#endregion
45
+ //#region src/Vivari.tsx
46
+ function toCommand(cmd) {
47
+ const parts = Array.isArray(cmd) ? cmd : cmd.trim().split(/\s+/);
48
+ return [parts[0], parts.slice(1)];
49
+ }
50
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
51
+ /**
52
+ * Wait until the in-VM dev server at `url` is actually serving, then warm it, so
53
+ * the preview iframe loads a working (and already-optimized) page.
54
+ *
55
+ * Why: a dev server (Vite/rolldown) binds -> closes -> rebinds its port several
56
+ * times during startup, so the first `listen` event is transient. Pointing the
57
+ * iframe there immediately races that window and the Service Worker preview proxy
58
+ * returns `502 No server listening on port N`. This mirrors the studio's
59
+ * kernel-side `waitServing` + `warmDevServer`, but over the same SW proxy the
60
+ * iframe uses (so it needs no extra kernel API). Best-effort throughout: any
61
+ * failure just falls through so the iframe still gets a chance to load.
62
+ */
63
+ async function waitForPreview(url, timeoutMs = 6e4) {
64
+ const deadline = Date.now() + timeoutMs;
65
+ for (;;) {
66
+ try {
67
+ const res = await fetch(url, { cache: "no-store" });
68
+ if (res.status !== 502 && res.status !== 503 && res.status !== 504) break;
69
+ } catch {}
70
+ if (Date.now() > deadline) return;
71
+ await sleep(150);
72
+ }
73
+ try {
74
+ const html = await (await fetch(url, { cache: "no-store" })).text();
75
+ const mods = /* @__PURE__ */ new Set(["/@vite/client"]);
76
+ const re = /<script[^>]*type=["']module["'][^>]*src=["']([^"']+)["']/gi;
77
+ for (let m; m = re.exec(html);) if (m[1].startsWith("/")) mods.add(m[1]);
78
+ const origin = new URL(url).origin;
79
+ const base = url.replace(origin, "").replace(/\/$/, "");
80
+ await Promise.all([...mods].map((p) => fetch(origin + base + p, { cache: "no-store" }).catch(() => {})));
81
+ } catch {}
82
+ }
83
+ /**
84
+ * Drop-in embed: boots Vivari, mounts `files`, runs `install` then `run`, and
85
+ * renders the resulting dev-server preview in an <iframe>.
86
+ *
87
+ * <Vivari files={tree} run="npm run dev" style={{ height: 480 }} />
88
+ *
89
+ * The host page must be cross-origin isolated (COOP + COEP).
90
+ */
91
+ function Vivari(props) {
92
+ const { files, install = ["npm", "install"], run, onReady, onServerReady, onOutput, showPreview = true, className, style, fallback, ...bootOptions } = props;
93
+ const { vivari, status, error } = useVivari(bootOptions);
94
+ const [previewSrc, setPreviewSrc] = useState(null);
95
+ const cbs = useRef({
96
+ onReady,
97
+ onServerReady,
98
+ onOutput
99
+ });
100
+ cbs.current = {
101
+ onReady,
102
+ onServerReady,
103
+ onOutput
104
+ };
105
+ const startedRef = useRef(false);
106
+ const previewStartedRef = useRef(false);
107
+ const frameRef = useRef(null);
108
+ useEffect(() => {
109
+ if (!vivari || startedRef.current) return;
110
+ startedRef.current = true;
111
+ let disposed = false;
112
+ const relay = (type) => vivari.bridge.on(type, (m) => {
113
+ const win = frameRef.current?.contentWindow;
114
+ const msg = m.msg;
115
+ if (win && msg) win.postMessage({
116
+ ...msg,
117
+ type,
118
+ dir: "in"
119
+ }, "*");
120
+ });
121
+ const offWs = relay("vv-ws");
122
+ const offSse = relay("vv-sse");
123
+ const offServer = vivari.on("server-ready", (port, url) => {
124
+ if (disposed || previewStartedRef.current) return;
125
+ previewStartedRef.current = true;
126
+ waitForPreview(url).then(() => {
127
+ if (disposed) return;
128
+ setPreviewSrc(url);
129
+ cbs.current.onServerReady?.(port, url);
130
+ });
131
+ });
132
+ const pump = (proc) => proc.output.pipeTo(new WritableStream({ write: (chunk) => cbs.current.onOutput?.(chunk) })).catch(() => {});
133
+ (async () => {
134
+ if (files) await vivari.mount(files);
135
+ cbs.current.onReady?.(vivari);
136
+ if (install !== false) {
137
+ const [cmd, args] = toCommand(install);
138
+ const proc = await vivari.spawn(cmd, args);
139
+ pump(proc);
140
+ if (await proc.exit !== 0 || disposed) return;
141
+ }
142
+ if (run) {
143
+ const [cmd, args] = toCommand(run);
144
+ const proc = await vivari.spawn(cmd, args);
145
+ pump(proc);
146
+ }
147
+ })().catch(() => {});
148
+ return () => {
149
+ disposed = true;
150
+ offServer();
151
+ offWs();
152
+ offSse();
153
+ };
154
+ }, [vivari]);
155
+ if (status === "error") return fallback ?? /* @__PURE__ */ jsxs("div", {
156
+ className,
157
+ style,
158
+ children: ["Vivari failed to boot: ", error?.message]
159
+ });
160
+ if (!showPreview) return null;
161
+ if (!previewSrc) return fallback ?? null;
162
+ return /* @__PURE__ */ jsx("iframe", {
163
+ ref: frameRef,
164
+ src: previewSrc,
165
+ className,
166
+ style,
167
+ title: "Vivari preview",
168
+ allow: "cross-origin-isolated"
169
+ });
170
+ }
171
+ //#endregion
172
+ export { Vivari, useVivari };
@@ -0,0 +1,16 @@
1
+ import { Vivari, type BootOptions } from "@vivari/core";
2
+ export type VivariStatus = "booting" | "ready" | "error";
3
+ export interface UseVivariResult {
4
+ /** The booted instance, or `null` until `status === "ready"`. */
5
+ vivari: Vivari | null;
6
+ status: VivariStatus;
7
+ error: Error | null;
8
+ }
9
+ /**
10
+ * Boot a {@link Vivari} instance for the lifetime of the component.
11
+ *
12
+ * The instance is torn down on unmount. Options are read once, on the first
13
+ * render — change them by remounting (e.g. with a React `key`).
14
+ */
15
+ export declare function useVivari(options?: BootOptions): UseVivariResult;
16
+ //# sourceMappingURL=useVivari.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useVivari.d.ts","sourceRoot":"","sources":["../src/useVivari.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AAExD,MAAM,MAAM,YAAY,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;AAEzD,MAAM,WAAW,eAAe;IAC9B,iEAAiE;IACjE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,MAAM,EAAE,YAAY,CAAC;IACrB,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;CACrB;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,OAAO,CAAC,EAAE,WAAW,GAAG,eAAe,CAkChE"}
package/package.json CHANGED
@@ -1,12 +1,59 @@
1
1
  {
2
2
  "name": "@vivari/react",
3
- "version": "0.0.1",
4
- "description": "",
5
- "main": "index.js",
3
+ "version": "1.0.0",
4
+ "description": "React bindings for Vivari — an embeddable browser-native WebContainer.",
5
+ "keywords": [
6
+ "webcontainer",
7
+ "vivari",
8
+ "react",
9
+ "browser",
10
+ "nodejs",
11
+ "sandbox"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "Duc Trung Mai <maitrungduc1410@gmail.com>",
15
+ "homepage": "https://vivari.pages.dev",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/maitrungduc1410/vivari.git",
19
+ "directory": "packages/react"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/maitrungduc1410/vivari/issues"
23
+ },
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "files": [
27
+ "dist",
28
+ "README.md"
29
+ ],
30
+ "main": "./dist/index.js",
31
+ "module": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "default": "./dist/index.js"
37
+ },
38
+ "./package.json": "./package.json"
39
+ },
6
40
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
41
+ "build": "vite build && tsc -p tsconfig.build.json",
42
+ "typecheck": "tsc -p tsconfig.json --noEmit"
43
+ },
44
+ "peerDependencies": {
45
+ "react": ">=18"
46
+ },
47
+ "dependencies": {
48
+ "@vivari/core": "^1.0.0"
49
+ },
50
+ "devDependencies": {
51
+ "@types/react": "^19.2.17",
52
+ "react": "^19.2.7",
53
+ "typescript": "~6.0.2",
54
+ "vite": "^8.1.1"
8
55
  },
9
- "keywords": [],
10
- "author": "",
11
- "license": "ISC"
56
+ "publishConfig": {
57
+ "access": "public"
58
+ }
12
59
  }