@zerogpu/browser-extension-sdk 0.1.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.
Files changed (72) hide show
  1. package/README.md +264 -0
  2. package/bin/zerogpu.mjs +331 -0
  3. package/dist/assets/ort-wasm-simd-threaded.wasm +0 -0
  4. package/dist/assets/ort-wasm-simd.wasm +0 -0
  5. package/dist/assets/ort-wasm-threaded.wasm +0 -0
  6. package/dist/assets/ort-wasm.wasm +0 -0
  7. package/dist/assets/transformers.min.js +107 -0
  8. package/dist/assets/wllama/index.js +3374 -0
  9. package/dist/assets/wllama/multi-thread/wllama.wasm +0 -0
  10. package/dist/assets/wllama/single-thread/wllama.wasm +0 -0
  11. package/dist/assets/zerogpu-assets.json +17 -0
  12. package/dist/extension/zerogpu-offscreen.js +2904 -0
  13. package/dist/extension/zerogpu-offscreen.js.map +1 -0
  14. package/dist/loader.js +2 -0
  15. package/dist/loader.js.map +1 -0
  16. package/dist/manifest.json +7 -0
  17. package/dist/types/adapters/gguf/adapter.d.ts +3 -0
  18. package/dist/types/adapters/gguf/factory.d.ts +3 -0
  19. package/dist/types/adapters/gguf/index.d.ts +2 -0
  20. package/dist/types/adapters/gguf/runtime.d.ts +16 -0
  21. package/dist/types/adapters/index.d.ts +5 -0
  22. package/dist/types/adapters/onnx/adapter.d.ts +3 -0
  23. package/dist/types/adapters/onnx/env-fetch.d.ts +1 -0
  24. package/dist/types/adapters/onnx/factory.d.ts +3 -0
  25. package/dist/types/adapters/onnx/index.d.ts +2 -0
  26. package/dist/types/adapters/onnx/runtime.d.ts +15 -0
  27. package/dist/types/adapters/registry.d.ts +5 -0
  28. package/dist/types/adapters/transformers/adapter.d.ts +10 -0
  29. package/dist/types/adapters/transformers/factory.d.ts +3 -0
  30. package/dist/types/adapters/transformers/index.d.ts +2 -0
  31. package/dist/types/adapters/types.d.ts +64 -0
  32. package/dist/types/auto-init.d.ts +1 -0
  33. package/dist/types/config/defaults.d.ts +2 -0
  34. package/dist/types/config/env.d.ts +7 -0
  35. package/dist/types/config/orchestrator-url.d.ts +1 -0
  36. package/dist/types/config/types.d.ts +34 -0
  37. package/dist/types/device/fingerprint.d.ts +2 -0
  38. package/dist/types/device/telemetry.d.ts +3 -0
  39. package/dist/types/device/types.d.ts +58 -0
  40. package/dist/types/extension/offscreen.d.ts +49 -0
  41. package/dist/types/index.d.ts +1 -0
  42. package/dist/types/loader.d.ts +25 -0
  43. package/dist/types/public-api.d.ts +13 -0
  44. package/dist/types/runtime/lifecycle.d.ts +8 -0
  45. package/dist/types/runtime/router.d.ts +2 -0
  46. package/dist/types/runtime/sdk-state.d.ts +56 -0
  47. package/dist/types/sdk-version.d.ts +1 -0
  48. package/dist/types/storage/cached-model.d.ts +29 -0
  49. package/dist/types/storage/index.d.ts +4 -0
  50. package/dist/types/storage/meta-store.d.ts +2 -0
  51. package/dist/types/storage/model-store.d.ts +9 -0
  52. package/dist/types/storage/types.d.ts +19 -0
  53. package/dist/types/transport/http.d.ts +54 -0
  54. package/dist/types/transport/protocol.d.ts +47 -0
  55. package/dist/types/transport/status.d.ts +1 -0
  56. package/dist/types/transport/websocket.d.ts +25 -0
  57. package/dist/types/utils/errors.d.ts +4 -0
  58. package/dist/types/utils/logger.d.ts +15 -0
  59. package/dist/types/utils/timers.d.ts +7 -0
  60. package/dist/types/utils/uuid.d.ts +1 -0
  61. package/dist/v/zerogpu-browser-sdk.f47bae4f15c9.umd.js +2855 -0
  62. package/dist/v/zerogpu-browser-sdk.f47bae4f15c9.umd.js.map +1 -0
  63. package/dist/zerogpu-browser-sdk.cjs +2849 -0
  64. package/dist/zerogpu-browser-sdk.cjs.map +1 -0
  65. package/dist/zerogpu-browser-sdk.esm.js +2847 -0
  66. package/dist/zerogpu-browser-sdk.esm.js.map +1 -0
  67. package/dist/zerogpu-browser-sdk.umd.js +2855 -0
  68. package/dist/zerogpu-browser-sdk.umd.js.map +1 -0
  69. package/docs/INTEGRATION.md +213 -0
  70. package/docs/auto-update-loader.md +451 -0
  71. package/docs/multi-model-support.md +537 -0
  72. package/package.json +91 -0
package/README.md ADDED
@@ -0,0 +1,264 @@
1
+ # ZeroGPU Browser SDK
2
+
3
+ Device-side JavaScript SDK that downloads a small language model (SLM), registers the device with the ZeroGPU orchestrator, opens a WebSocket for tasks, and executes on-device summarization.
4
+
5
+ ## Building a Chrome extension?
6
+
7
+ Chrome Manifest V3 forbids remotely-hosted code, so the `<script>`/loader path
8
+ below can't be used. Instead, install the package and vendor the runtime into your
9
+ extension:
10
+
11
+ ```bash
12
+ npm install @zerogpu/browser-extension-sdk
13
+ npx zerogpu init # vendors the runtime + scaffolds the offscreen glue
14
+ ```
15
+
16
+ See the full, copy-paste **[Chrome Extension integration guide](docs/INTEGRATION.md)**
17
+ (all model types, run/test locally, and the keep-it-updated loop).
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install
23
+ ```
24
+
25
+ ## Build
26
+
27
+ ```bash
28
+ npm run build
29
+ ```
30
+
31
+ The build produces:
32
+
33
+ - ESM (`dist/zerogpu-browser-sdk.esm.js`) and CJS (`dist/zerogpu-browser-sdk.cjs`) bundles for npm consumers.
34
+ - A UMD bundle (`dist/zerogpu-browser-sdk.umd.js`) plus an immutable, content-hashed copy under `dist/v/` for CDN distribution.
35
+ - `dist/loader.js` — the stable bootstrap apps embed (see [UMD via `<script>`](#umd-via-script-always-latest-loader)).
36
+ - `dist/manifest.json` — points the loader at the current hashed core bundle and records the build version.
37
+
38
+ ## Tests
39
+
40
+ ```bash
41
+ npm run test
42
+ ```
43
+
44
+ ## Lint
45
+
46
+ ```bash
47
+ npm run lint
48
+ ```
49
+
50
+ ## Usage
51
+
52
+ ### ESM
53
+
54
+ ```ts
55
+ import { initZeroGpuSdk } from '@zerogpu/browser-extension-sdk';
56
+
57
+ await initZeroGpuSdk({
58
+ // Optional Telegram user ID or custom app user ID
59
+ appUserId: 'telegram-user-1234',
60
+
61
+ // Sent as header: x-edge-operator-key
62
+ edgeOperatorKey: 'your-edge-operator-key',
63
+
64
+ // Override default settings
65
+ overrides: {
66
+ orchestrator: {
67
+ // Each deployment bakes in its own orchestrator at build time
68
+ // (develop/staging/production). Override only for internal testing.
69
+ baseUrl: 'https://devices.zerogpu.ai'
70
+ },
71
+ telemetry: {
72
+ // Enable/disable detailed console logs
73
+ enableConsoleLogs: true,
74
+ // Request geolocation permission (default: false)
75
+ locationData: true,
76
+ // Request camera permission (default: false) - *Not yet implemented*
77
+ cameraData: false
78
+ }
79
+ }
80
+ });
81
+ ```
82
+
83
+ ### UMD via `<script>` (always-latest loader)
84
+
85
+ Embed the **loader** URL — `dist/loader.js` — and you never have to think about
86
+ SDK versions again. The loader resolves and injects the latest published core
87
+ bundle at runtime, so an integrated app stays up to date with **zero effort**:
88
+ no version pinning, no `?v=` cache-buster to bump.
89
+
90
+ ```html
91
+ <script
92
+ async
93
+ src="https://js-sdk.zerogpu.ai/dist/loader.js"
94
+ edgeOperatorKey="your-edge-operator-key"
95
+ enableConsoleLogs="true"
96
+ ></script>
97
+ ```
98
+
99
+ The SDK auto-initializes when `edgeOperatorKey` is present
100
+ (the loader forwards every attribute to the core bundle).
101
+
102
+ For manual initialization, embed the loader without keys and call
103
+ `ZeroGpuSdk.initZeroGpuSdk(...)`. The loader installs a small queueing stub, so
104
+ calls made before the core bundle finishes loading are replayed automatically:
105
+
106
+ ```html
107
+ <script async src="https://js-sdk.zerogpu.ai/dist/loader.js"></script>
108
+ <script>
109
+ ZeroGpuSdk.initZeroGpuSdk({
110
+ edgeOperatorKey: 'your-edge-operator-key'
111
+ });
112
+ </script>
113
+ ```
114
+
115
+ **How it works:** `loader.js` and `manifest.json` are served fresh (short TTL +
116
+ `stale-while-revalidate`); the manifest points at an immutable, content-hashed
117
+ core bundle (`dist/v/zerogpu-browser-sdk.<hash>.umd.js`) cached for a year. A new
118
+ release simply repoints the manifest at a new hash — and rollback is the same
119
+ operation in reverse. If the manifest is ever unreachable, the loader falls back
120
+ to the stable `dist/zerogpu-browser-sdk.umd.js` bundle.
121
+
122
+ > Loading the core bundle directly (`dist/zerogpu-browser-sdk.umd.js`) still
123
+ > works but pins the app to whatever build is live at load time — prefer the
124
+ > loader so updates are automatic.
125
+
126
+ ## Configuration Options
127
+
128
+ ### `InitOptions`
129
+
130
+ | Option | Type | Default | Description |
131
+ | :--- | :--- | :--- | :--- |
132
+ | `appUserId` | `string` | `undefined` | Optional user identifier (e.g. Telegram ID) for telemetry. |
133
+ | `edgeOperatorKey` | `string` | `undefined` | Operator key forwarded to `/register` as `x-edge-operator-key`. The orchestrator resolves the project from this key. |
134
+ | `overrides` | `Partial<SdkConfig>` | `{}` | Deep merge overrides for internal config. |
135
+
136
+ ### `SdkConfig` Overrides
137
+
138
+ You can override any part of the configuration. Common overrides:
139
+
140
+ - **`orchestrator.baseUrl`**: URL of the ZeroGPU orchestration API.
141
+ - **`slm.modelRepoId`**: Hugging Face repo id used by Transformers.js (default: `Xenova/t5-small`).
142
+ - **`slm.modelUrl`**: Base URL that hosts the model assets (e.g., your CDN).
143
+ - **`slm.sampleSummaryText`**: Text used for the on-device self-test before registration.
144
+ - **`telemetry.locationData`**: If `true`, SDK attempts to gather GPS coordinates (triggers permission prompt).
145
+ - **`telemetry.enableConsoleLogs`**: Force console logging on/off (default `false`).
146
+
147
+ ## Local Testing
148
+
149
+ ## Dashboard + Demo (Vite)
150
+
151
+ The Vite app under `sdk/dashboard-app` serves both:
152
+ - `/` — ZeroGPU Edge SDK Demo
153
+ - `/dashboard` — ZeroGPU Fleet dashboard (analytics)
154
+
155
+ It also proxies API calls so the browser avoids CORS:
156
+ - `/api/*` -> `API_UPSTREAM` (default `http://localhost:4000`)
157
+ - `/analytics/*` -> `ANALYTICS_UPSTREAM` (default `http://localhost:5000`)
158
+
159
+ ```bash
160
+ cd sdk
161
+ npm run dashboard:dev
162
+ ```
163
+
164
+ Build/preview:
165
+
166
+ ```bash
167
+ cd sdk
168
+ npm run dashboard:build
169
+ npm run dashboard:preview
170
+ ```
171
+
172
+ Env config:
173
+ - Copy `sdk/dashboard-app/.env.example` to `sdk/dashboard-app/.env.local` and edit values.
174
+ - By default it uses `/api` + `/analytics` so Vite can proxy and avoid browser CORS.
175
+ - The demo page (`/`) can also read optional defaults from `VITE_ZGPU_SDK_KEY` and `VITE_ZGPU_PROJECT_ID` (recommended via `.env.local`, not committed).
176
+
177
+ ### Testing against a non-production orchestrator
178
+
179
+ Each deployment bakes in its own orchestrator at build time — develop, staging, or
180
+ production (`https://devices.zerogpu.ai`) — via the `ZGPU_ORCHESTRATOR_BASE_URL` build
181
+ env var set by the GitHub deploy workflows. For internal testing against a develop or
182
+ local orchestration API, override `orchestrator.baseUrl` directly:
183
+
184
+ ```ts
185
+ import { initZeroGpuSdk } from '@zerogpu/browser-extension-sdk';
186
+
187
+ await initZeroGpuSdk({
188
+ edgeOperatorKey: 'your-edge-operator-key',
189
+ overrides: {
190
+ orchestrator: {
191
+ // e.g. https://dev.devices.zerogpu.ai or http://localhost:6000
192
+ baseUrl: 'http://localhost:6000'
193
+ },
194
+ telemetry: {
195
+ enableConsoleLogs: true // Enable detailed logging
196
+ }
197
+ }
198
+ });
199
+ ```
200
+
201
+ ### SDK Demo Page
202
+
203
+ Use the built-in demo page served by Vite at `http://localhost:8000/` (it loads the SDK from `/dist/zerogpu-browser-sdk.esm.js`).
204
+
205
+ ## Self-Hosting the Model
206
+
207
+ If you want to serve the SLM artifacts from your own CDN (e.g., Cloudflare R2), download the Hugging Face assets and preserve the folder structure:
208
+
209
+ ```
210
+ t5-small/
211
+ ├── config.json
212
+ ├── generation_config.json
213
+ ├── tokenizer.json
214
+ ├── tokenizer_config.json
215
+ ├── special_tokens_map.json
216
+ ├── spiece.model
217
+ └── onnx/
218
+ ├── encoder_model_quantized.onnx
219
+ └── decoder_model_merged_quantized.onnx
220
+ ```
221
+
222
+ ### Download commands
223
+
224
+ ```bash
225
+ mkdir -p t5-small/onnx
226
+ cd t5-small
227
+
228
+ BASE_META="https://huggingface.co/Xenova/t5-small/resolve/main"
229
+ BASE_ONNX="https://huggingface.co/Xenova/t5-small/resolve/main/onnx"
230
+
231
+ curl -L -o config.json "$BASE_META/config.json"
232
+ curl -L -o generation_config.json "$BASE_META/generation_config.json"
233
+ curl -L -o tokenizer.json "$BASE_META/tokenizer.json"
234
+ curl -L -o tokenizer_config.json "$BASE_META/tokenizer_config.json"
235
+ curl -L -o special_tokens_map.json "$BASE_META/special_tokens_map.json"
236
+ curl -L -o spiece.model "$BASE_META/spiece.model"
237
+ curl -L -o onnx/encoder_model_quantized.onnx "$BASE_ONNX/encoder_model_quantized.onnx"
238
+ curl -L -o onnx/decoder_model_merged_quantized.onnx "$BASE_ONNX/decoder_model_merged_quantized.onnx"
239
+ ```
240
+
241
+ Upload the `t5-small/` directory to your CDN unchanged and ensure responses include permissive CORS headers (`Access-Control-Allow-Origin: *`). Then override the SDK config:
242
+
243
+ ```ts
244
+ await initZeroGpuSdk({
245
+ edgeOperatorKey: 'your-edge-operator-key',
246
+ overrides: {
247
+ slm: {
248
+ modelUrl: 'https://cdn.example.com/models/t5-small'
249
+ }
250
+ }
251
+ });
252
+ ```
253
+
254
+ `slm.modelRepoId` remains `Xenova/t5-small` so Transformers.js can reference the original repo, while the SDK rewrites every network request to your CDN.
255
+
256
+ ## Flow
257
+
258
+ 1. `initZeroGpuSdk` resolves configuration (env defaults + overrides).
259
+ 2. Device fingerprint + metadata are collected.
260
+ 3. Required SLM artifacts are downloaded to IndexedDB and loaded into Transformers.js. Timing metrics are recorded.
261
+ 4. The SDK calls the orchestrator `/register` endpoint with device + model metadata. A shell-friendly cURL string is logged.
262
+ 5. The orchestrator responds with a `wsUrl`. The SDK opens a WebSocket, sends a `hello`, and listens for `summary_request` messages.
263
+ 6. Each `summary_request` executes against the on-device SLM (single flight enforced) and responds with `summary_response` containing the summarized text and rich metadata (timings, device info, model info).
264
+ 7. If the WebSocket closes or errors, the SDK marks the state as `error`. Reloading the host app re-initializes the SDK.
@@ -0,0 +1,331 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * zerogpu — CLI for integrating the ZeroGPU SDK into a Chrome (MV3) extension.
4
+ *
5
+ * npx zerogpu vendor [outDir] Copy the SDK + model runtimes into the extension
6
+ * (default: vendor/zerogpu). Run this in your build.
7
+ * npx zerogpu init [--dir .] Vendor + scaffold offscreen/background glue and
8
+ * patch manifest.json. For a brand-new extension.
9
+ * npx zerogpu doctor [--dir .] Check manifest + that vendored assets are in sync.
10
+ *
11
+ * MV3 forbids remotely-hosted code, so everything must live inside the extension
12
+ * package; `vendor` is the one step that puts the runtime files in place.
13
+ */
14
+ import {
15
+ cpSync,
16
+ existsSync,
17
+ mkdirSync,
18
+ readFileSync,
19
+ readdirSync,
20
+ writeFileSync
21
+ } from 'node:fs';
22
+ import path from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+
25
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
26
+ const pkgRoot = path.resolve(__dirname, '..');
27
+ const distDir = path.join(pkgRoot, 'dist');
28
+ const distAssets = path.join(distDir, 'assets');
29
+ const distOffscreen = path.join(distDir, 'extension', 'zerogpu-offscreen.js');
30
+
31
+ const MODEL_HOST_PERMISSIONS = [
32
+ 'https://*.zerogpu.ai/*',
33
+ 'https://huggingface.co/*',
34
+ 'https://*.hf.co/*',
35
+ 'https://cdn-lfs.huggingface.co/*',
36
+ 'https://cdn-lfs-us-1.huggingface.co/*'
37
+ ];
38
+ const REQUIRED_CSP = "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'";
39
+
40
+ const c = {
41
+ ok: (s) => `\x1b[32m${s}\x1b[0m`,
42
+ warn: (s) => `\x1b[33m${s}\x1b[0m`,
43
+ err: (s) => `\x1b[31m${s}\x1b[0m`,
44
+ dim: (s) => `\x1b[2m${s}\x1b[0m`
45
+ };
46
+
47
+ const log = (...a) => console.log(...a);
48
+ const die = (msg) => {
49
+ console.error(c.err(`✗ ${msg}`));
50
+ process.exit(1);
51
+ };
52
+
53
+ const parseFlags = (argv) => {
54
+ const flags = {};
55
+ const positional = [];
56
+ for (let i = 0; i < argv.length; i += 1) {
57
+ const arg = argv[i];
58
+ if (arg.startsWith('--')) {
59
+ const key = arg.slice(2);
60
+ const next = argv[i + 1];
61
+ if (next && !next.startsWith('--')) {
62
+ flags[key] = next;
63
+ i += 1;
64
+ } else {
65
+ flags[key] = true;
66
+ }
67
+ } else {
68
+ positional.push(arg);
69
+ }
70
+ }
71
+ return { flags, positional };
72
+ };
73
+
74
+ const ensureDistPresent = () => {
75
+ if (!existsSync(distOffscreen) || !existsSync(distAssets)) {
76
+ die(
77
+ 'Built SDK assets not found. Reinstall @zerogpu/browser-extension-sdk (its dist/ ships the runtime).'
78
+ );
79
+ }
80
+ };
81
+
82
+ // --- vendor ------------------------------------------------------------------
83
+
84
+ const vendor = (outDir) => {
85
+ ensureDistPresent();
86
+ const target = path.resolve(process.cwd(), outDir || path.join('vendor', 'zerogpu'));
87
+ mkdirSync(target, { recursive: true });
88
+
89
+ // The offscreen host bundle (contains the SDK itself).
90
+ cpSync(distOffscreen, path.join(target, 'zerogpu-offscreen.js'));
91
+ // All pinned runtime assets (transformers + ONNX wasm, wllama + wasm, manifest).
92
+ cpSync(distAssets, target, { recursive: true });
93
+
94
+ const manifest = readAssetsManifest(target);
95
+ const rel = path.relative(process.cwd(), target) || '.';
96
+ log(c.ok(`✓ Vendored ZeroGPU runtime into ${rel}`));
97
+ if (manifest) {
98
+ log(
99
+ c.dim(
100
+ ` sdk ${manifest.sdkVersion} · transformers ${manifest.transformersVersion} · wllama ${manifest.wllamaVersion}`
101
+ )
102
+ );
103
+ }
104
+ return target;
105
+ };
106
+
107
+ const readAssetsManifest = (dir) => {
108
+ const file = path.join(dir, 'zerogpu-assets.json');
109
+ if (!existsSync(file)) return null;
110
+ try {
111
+ return JSON.parse(readFileSync(file, 'utf8'));
112
+ } catch {
113
+ return null;
114
+ }
115
+ };
116
+
117
+ // --- init (scaffold) ---------------------------------------------------------
118
+
119
+ const OFFSCREEN_HTML = `<!DOCTYPE html>
120
+ <html>
121
+ <head><meta charset="utf-8" /><title>ZeroGPU offscreen</title></head>
122
+ <body>
123
+ <script type="module" src="offscreen.js"></script>
124
+ </body>
125
+ </html>
126
+ `;
127
+
128
+ const OFFSCREEN_JS = `import { registerZeroGpuOffscreenMessaging } from "./vendor/zerogpu/zerogpu-offscreen.js";
129
+
130
+ // The offscreen document is where the SDK runs (it needs window/DOM + workers).
131
+ registerZeroGpuOffscreenMessaging({
132
+ edgeOperatorKey: "REPLACE_WITH_YOUR_OPERATOR_KEY",
133
+ enableConsoleLogs: true
134
+ // orchestratorBaseUrl: "https://dev.devices.zerogpu.ai" // uncomment to test against develop
135
+ });
136
+ `;
137
+
138
+ const BACKGROUND_JS = `// ZeroGPU offscreen bootstrap. Ensures the offscreen document exists and relays
139
+ // the popup/debug messages to it. Merge into your existing service worker if any.
140
+ const OFFSCREEN_PATH = "offscreen.html";
141
+ let creating = null;
142
+
143
+ async function ensureOffscreen() {
144
+ const contexts = await chrome.runtime.getContexts({
145
+ contextTypes: ["OFFSCREEN_DOCUMENT"],
146
+ documentUrls: [chrome.runtime.getURL(OFFSCREEN_PATH)]
147
+ });
148
+ if (contexts.length > 0) return;
149
+ if (!creating) {
150
+ creating = chrome.offscreen.createDocument({
151
+ url: OFFSCREEN_PATH,
152
+ reasons: ["WORKERS"],
153
+ justification: "Run the ZeroGPU SDK, which requires a window/DOM context."
154
+ });
155
+ }
156
+ await creating;
157
+ creating = null;
158
+ }
159
+
160
+ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
161
+ if (!message || typeof message !== "object") return;
162
+ if (message.type === "zerogpu:forceInit") {
163
+ void ensureOffscreen()
164
+ .then(() => chrome.runtime.sendMessage(message))
165
+ .then((r) => sendResponse(r))
166
+ .catch((e) => sendResponse({ ok: false, error: String(e && e.message || e) }));
167
+ return true;
168
+ }
169
+ if (message.type === "zerogpu:getStatus") {
170
+ void ensureOffscreen()
171
+ .then(() => chrome.runtime.sendMessage(message))
172
+ .then((r) => sendResponse(r))
173
+ .catch((e) => sendResponse({ ok: false, error: String(e && e.message || e) }));
174
+ return true;
175
+ }
176
+ if (message.type === "zerogpu:disable") {
177
+ void chrome.offscreen.closeDocument().then(() => sendResponse({ ok: true })).catch(() => sendResponse({ ok: true }));
178
+ return true;
179
+ }
180
+ });
181
+ `;
182
+
183
+ const uniqueMerge = (existing, additions) => {
184
+ const out = Array.isArray(existing) ? [...existing] : [];
185
+ for (const item of additions) {
186
+ if (!out.includes(item)) out.push(item);
187
+ }
188
+ return out;
189
+ };
190
+
191
+ const patchManifest = (dir) => {
192
+ const file = path.join(dir, 'manifest.json');
193
+ if (!existsSync(file)) {
194
+ log(c.warn(' ! manifest.json not found — skipping manifest patch.'));
195
+ return;
196
+ }
197
+ const manifest = JSON.parse(readFileSync(file, 'utf8'));
198
+ manifest.permissions = uniqueMerge(manifest.permissions, ['offscreen', 'storage']);
199
+ manifest.optional_host_permissions = uniqueMerge(
200
+ manifest.optional_host_permissions,
201
+ MODEL_HOST_PERMISSIONS
202
+ );
203
+ manifest.content_security_policy = manifest.content_security_policy || {};
204
+ if (!manifest.content_security_policy.extension_pages) {
205
+ manifest.content_security_policy.extension_pages = REQUIRED_CSP;
206
+ }
207
+ if (!manifest.background) {
208
+ manifest.background = { service_worker: 'background.js' };
209
+ }
210
+ writeFileSync(file, JSON.stringify(manifest, null, 2) + '\n');
211
+ log(c.ok('✓ Patched manifest.json (permissions, CSP, host permissions)'));
212
+ };
213
+
214
+ const scaffoldFile = (dir, name, contents) => {
215
+ const file = path.join(dir, name);
216
+ if (existsSync(file)) {
217
+ log(c.dim(` • ${name} exists — left unchanged`));
218
+ return;
219
+ }
220
+ writeFileSync(file, contents);
221
+ log(c.ok(`✓ Created ${name}`));
222
+ };
223
+
224
+ const init = (dir) => {
225
+ const root = path.resolve(process.cwd(), dir || '.');
226
+ if (!existsSync(root)) die(`Directory not found: ${root}`);
227
+ vendor(path.join(root, 'vendor', 'zerogpu'));
228
+ scaffoldFile(root, 'offscreen.html', OFFSCREEN_HTML);
229
+ scaffoldFile(root, 'offscreen.js', OFFSCREEN_JS);
230
+ scaffoldFile(root, 'background.js', BACKGROUND_JS);
231
+ patchManifest(root);
232
+ log('');
233
+ log(c.ok('ZeroGPU integrated.') + ' Next:');
234
+ log(' 1. Put your operator key in offscreen.js (REPLACE_WITH_YOUR_OPERATOR_KEY).');
235
+ log(' 2. Load the extension unpacked and trigger the offscreen document.');
236
+ log(' 3. Re-run ' + c.dim('npx zerogpu vendor') + ' in your build to stay up to date.');
237
+ };
238
+
239
+ // --- doctor ------------------------------------------------------------------
240
+
241
+ const doctor = (dir) => {
242
+ const root = path.resolve(process.cwd(), dir || '.');
243
+ const vendorDir = path.join(root, 'vendor', 'zerogpu');
244
+ let problems = 0;
245
+
246
+ const installed = readAssetsManifest(distAssets);
247
+ const vendored = readAssetsManifest(vendorDir);
248
+
249
+ if (!vendored) {
250
+ log(c.err('✗ No vendored assets found. Run: npx zerogpu vendor'));
251
+ problems += 1;
252
+ } else {
253
+ for (const f of vendored.files || []) {
254
+ if (!existsSync(path.join(vendorDir, f))) {
255
+ log(c.err(`✗ Missing vendored file: ${f}`));
256
+ problems += 1;
257
+ }
258
+ }
259
+ if (installed && vendored.sdkVersion !== installed.sdkVersion) {
260
+ log(
261
+ c.warn(
262
+ `! Vendored SDK ${vendored.sdkVersion} differs from installed ${installed.sdkVersion}. Run: npx zerogpu vendor`
263
+ )
264
+ );
265
+ problems += 1;
266
+ } else if (installed) {
267
+ log(c.ok(`✓ Vendored assets in sync (sdk ${vendored.sdkVersion})`));
268
+ }
269
+ }
270
+
271
+ const manifestFile = path.join(root, 'manifest.json');
272
+ if (!existsSync(manifestFile)) {
273
+ log(c.warn('! manifest.json not found.'));
274
+ } else {
275
+ const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
276
+ const csp = manifest.content_security_policy?.extension_pages || '';
277
+ if (!csp.includes("'wasm-unsafe-eval'")) {
278
+ log(c.err("✗ CSP extension_pages missing 'wasm-unsafe-eval'"));
279
+ problems += 1;
280
+ }
281
+ if (!(manifest.permissions || []).includes('offscreen')) {
282
+ log(c.err('✗ manifest permissions missing "offscreen"'));
283
+ problems += 1;
284
+ }
285
+ const hosts = manifest.optional_host_permissions || manifest.host_permissions || [];
286
+ if (!hosts.some((h) => h.includes('zerogpu.ai'))) {
287
+ log(c.warn('! No zerogpu.ai host permission found (register/WS may be blocked).'));
288
+ }
289
+ }
290
+
291
+ if (problems === 0) {
292
+ log(c.ok('✓ ZeroGPU integration looks healthy.'));
293
+ } else {
294
+ process.exitCode = 1;
295
+ }
296
+ };
297
+
298
+ // --- main --------------------------------------------------------------------
299
+
300
+ const main = () => {
301
+ const [command, ...rest] = process.argv.slice(2);
302
+ const { flags, positional } = parseFlags(rest);
303
+ switch (command) {
304
+ case 'vendor':
305
+ vendor(positional[0]);
306
+ break;
307
+ case 'init':
308
+ init(flags.dir);
309
+ break;
310
+ case 'doctor':
311
+ doctor(flags.dir);
312
+ break;
313
+ case undefined:
314
+ case 'help':
315
+ case '--help':
316
+ case '-h':
317
+ log(`zerogpu — integrate the ZeroGPU SDK into a Chrome (MV3) extension
318
+
319
+ Usage:
320
+ npx zerogpu vendor [outDir] Copy SDK + model runtimes into the extension
321
+ (default: vendor/zerogpu). Run this in your build.
322
+ npx zerogpu init [--dir .] Vendor + scaffold offscreen/background + patch manifest
323
+ npx zerogpu doctor [--dir .] Verify the integration is wired and in sync
324
+ `);
325
+ break;
326
+ default:
327
+ die(`Unknown command: ${command}. Run "npx zerogpu help".`);
328
+ }
329
+ };
330
+
331
+ main();
Binary file
Binary file