@ohtaman/washi 0.8.2 → 0.9.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 (47) hide show
  1. package/README.md +3 -0
  2. package/dist/browser/solvers/{highs-__vite-browser-external-Dn-83hnF.js → highs-__vite-browser-external-xcxOpLMD.js} +1 -1
  3. package/dist/browser/solvers/{highs-browser-runtime-0Bgq5ksG.js → highs-browser-runtime-ccRmE4qj.js} +1 -1
  4. package/dist/browser/solvers/highs-inline.js +51 -0
  5. package/dist/{lib/solvers/loader-CDpPXN_F.js → browser/solvers/highs-loader-Csn3-0tq.js} +241 -149
  6. package/dist/browser/solvers/highs-worker.js +17 -16
  7. package/dist/browser/solvers/highs.js +295 -255
  8. package/dist/browser/solvers/pumpkin-inline.js +51 -0
  9. package/dist/{lib/solvers/loader-Ow74Fa1B.js → browser/solvers/pumpkin-loader-BI3n3dWO.js} +145 -55
  10. package/dist/browser/solvers/pumpkin-worker.js +24 -23
  11. package/dist/browser/solvers/pumpkin.js +307 -288
  12. package/dist/browser/washi.js +365 -316
  13. package/dist/browser/washi.min.js +4 -4
  14. package/dist/lib/solvers/embedded-wasm-CSFlLV5N.js +49 -0
  15. package/dist/lib/solvers/highs-node-runtime.js +1 -7
  16. package/dist/lib/solvers/highs-worker.js +19 -17
  17. package/dist/lib/solvers/highs.js +153 -112
  18. package/dist/{browser/solvers/highs-loader-BLY3wzDH.js → lib/solvers/loader-DCtyxsfF.js} +56 -36
  19. package/dist/{browser/solvers/pumpkin-loader-CvdaKxf4.js → lib/solvers/loader-b5PNpCmX.js} +58 -33
  20. package/dist/lib/solvers/pumpkin-worker.js +25 -23
  21. package/dist/lib/solvers/pumpkin.js +212 -192
  22. package/dist/lib/washi.js +365 -316
  23. package/dist/types/modeler/model.d.ts +7 -0
  24. package/dist/types/modeler/model.d.ts.map +1 -1
  25. package/dist/types/modeler/solvers/embedded-wasm.d.ts +36 -0
  26. package/dist/types/modeler/solvers/embedded-wasm.d.ts.map +1 -0
  27. package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
  28. package/dist/types/modeler/solvers/highs/node-runtime.d.ts.map +1 -1
  29. package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
  30. package/dist/types/modeler/solvers/inline-pack.d.ts +6 -0
  31. package/dist/types/modeler/solvers/inline-pack.d.ts.map +1 -0
  32. package/dist/types/modeler/solvers/pumpkin/loader.d.ts +1 -1
  33. package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -1
  34. package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -1
  35. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -1
  36. package/dist/types/modeler/solvers/pumpkin/worker.d.ts +1 -0
  37. package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -1
  38. package/docs/getting-started/ai-agents.md +56 -1
  39. package/docs/getting-started/coding-agents.md +38 -5
  40. package/docs/getting-started/runtimes.md +63 -1
  41. package/docs/solvers/highs.md +2 -0
  42. package/docs/solvers/pumpkin.md +2 -0
  43. package/llms-full.txt +123 -2
  44. package/llms.txt +56 -1
  45. package/package.json +12 -1
  46. package/skills/washi/SKILL.md +75 -14
  47. package/skills/washi/references/single-html.md +330 -0
@@ -0,0 +1,330 @@
1
+ # WaSHI Single-File Offline HTML App Guide
2
+
3
+ Build self-contained, single-file `index.html` applications that bundle `@ohtaman/washi` (HiGHS and Pumpkin WASM solvers) together with any third-party npm UI, charting, or math libraries so end users can double-click the file (`file://`) offline with zero local servers, zero external CDN requests, and zero extra asset files.
4
+
5
+ ## Architecture Overview
6
+
7
+ > **When to use this offline Vite guide vs. `*-inline.js`**: Use **`references/single-html.md`** when Vite-bundling a zero-network, double-clickable offline `file://` HTML app with gzipped WASM and third-party npm UI libraries (`react`, `katex`, `chart.js`, `tailwindcss`). For zero-build HTML snippets hosted inside CSP-restricted AI sandboxes (`connect-src 'none'`, such as Claude.ai Artifacts, ChatGPT/Codex inline visualizations, or Gemini Canvas / Google Sites), use WaSHI's CDN `solvers/highs-inline.js` / `solvers/pumpkin-inline.js` packs with ESM `<script type="module">` instead (see [`../SKILL.md`](../SKILL.md)). Note that embedded previews whose CSP omits `'wasm-unsafe-eval'` (such as Antigravity's HTML artifact preview) cannot compile WebAssembly; open the exported `dist/index.html` directly in Chrome/Safari or via a local server.
8
+
9
+ A standard `vite-plugin-singlefile` build already inlines JS modules, CSS, web fonts, and images from any npm dependency (`react`, `katex`, `chart.js`, `tailwindcss`, etc.) into one HTML file. WaSHI adds three extra single-file constraints that standard plugins do not handle alone:
10
+
11
+ 1. **Blocked `fetch()` on `file://`**: Browsers block relative `fetch("./highs.wasm")` requests on opaque `file://` origins. Embed compressed WASM inside inert `<script type="text/plain">` tags and hydrate via `FileReader.readAsDataURL()` (`data:application/wasm;base64,...`) passed to `setHighsWasmUrl()` / `setPumpkinWasmUrl()`. Avoid `URL.createObjectURL()` because opaque `file://` origins produce restricted `blob:null/...` URLs.
12
+ 2. **No external Worker scripts**: Intercept WaSHI's internal solver asset and worker-factory modules during bundling so Vite emits zero sidecar `.wasm` or `*-worker.js` files, and always pass `{ useWorker: false }` in `solve()` / `check()` so the same HTML also stays single-file if hosted over `http://` or `https://`.
13
+ 3. **Small file size via gzip**: Raw Base64-encoded `.wasm` in JS swells the HTML past 8.5 MiB and slows script parsing. Gzipping (`level: 9`) into inert `<script type="text/plain" id="washi-wasm-*-gz">` tags shrinks the combined HiGHS + Pumpkin payload to roughly **1.8–2.4 MiB Base64** and decompresses in milliseconds via standard `DecompressionStream("gzip")`.
14
+
15
+ ## Supported Solvers & Hard Exclusions
16
+
17
+ - **Supported**:
18
+ - **HiGHS** (`LP` / `MIP`) via `@ohtaman/washi` and `@ohtaman/washi/solvers/highs` (`highs.wasm`, ~1.36 MiB gzipped)
19
+ - **Pumpkin** (`CP` / `SAT` / `unsatCore`) via `@ohtaman/washi` and `@ohtaman/washi/solvers/pumpkin` (`pumpkin.wasm`, ~398 KiB gzipped)
20
+ - WaSHI decomposition (`benders`, `dantzigWolfe`), `m.verify()`, and arbitrary third-party npm packages
21
+ - **Unsupported in single-file offline HTML**:
22
+ - **Z3** (`@ohtaman/washi/solvers/z3`): Requires `SharedArrayBuffer` pthreads, which demand a secure context (`https://` or `localhost`) and `Cross-Origin-Opener-Policy: same-origin` + `Cross-Origin-Embedder-Policy: require-corp` (`COOP`/`COEP`) response headers. Z3 cannot run over `file://` or in a single headerless HTML file.
23
+ - **GLPK** (`glpk.js`): Optional peer dependency not bundled by default; exclude it in offline single-file builds unless you intentionally install and inline `glpk.js` (`{ useWorker: false }`).
24
+
25
+ ## Project Setup
26
+
27
+ Create a standard Vite app and install `@ohtaman/washi` plus `vite` and `vite-plugin-singlefile`:
28
+
29
+ ```bash
30
+ npm install @ohtaman/washi
31
+ npm install -D vite vite-plugin-singlefile
32
+ # Install any third-party libraries your app needs, e.g.:
33
+ # npm install katex chart.js react react-dom
34
+ ```
35
+
36
+ Include only the WaSHI solvers your app actually uses (`["highs"]`, `["pumpkin"]`, or `["highs", "pumpkin"]`) to keep the output HTML as small as possible.
37
+
38
+ ## Step 1: Add the Vite WaSHI Offline WASM Plugin
39
+
40
+ Save this plugin as `vite-washi-offline.mjs` next to `vite.config.ts`. It prevents Vite from emitting external `.wasm`, `*-worker.js`, `node:*`, or optional Z3/GLPK artifacts, and injects gzipped Base64 WASM payloads into `index.html`.
41
+
42
+ <!-- washi-single-html:vite-plugin -->
43
+ ```js
44
+ import { existsSync, readFileSync } from "node:fs";
45
+ import { createRequire } from "node:module";
46
+ import path from "node:path";
47
+ import { gzipSync } from "node:zlib";
48
+
49
+ const VIRTUAL_PREFIX = "\0washi-single-html:";
50
+
51
+ function resolveDefaultWasmDir() {
52
+ const require = createRequire(import.meta.url);
53
+ return path.dirname(require.resolve("@ohtaman/washi/solvers/highs"));
54
+ }
55
+
56
+ /**
57
+ * Vite plugin that strips external WaSHI WASM/worker/Node/optional-solver
58
+ * emissions and injects gzipped Base64 WASM payloads into index.html.
59
+ *
60
+ * @param {{ wasmDir?: string; solvers?: Array<"highs" | "pumpkin"> }} [options]
61
+ * @returns {import("vite").Plugin}
62
+ */
63
+ export function washiSingleHtmlWasmPlugin(options = {}) {
64
+ const solvers = options.solvers ?? ["highs", "pumpkin"];
65
+ const resolveWasmDir = () => options.wasmDir ?? resolveDefaultWasmDir();
66
+
67
+ return {
68
+ name: "washi-single-html-wasm",
69
+ enforce: "pre",
70
+ resolveId(source, importer) {
71
+ const normalizedImporter = importer?.replaceAll("\\", "/") ?? "";
72
+ const fromSolverDir = (dirName, relBase) =>
73
+ normalizedImporter.includes(`/solvers/${dirName}/`) &&
74
+ new RegExp(`^\\.\\.?\\/${relBase}(?:\\.[jt]s)?$`).test(source);
75
+
76
+ if (source === "./highs-assets.js" || source.endsWith("/highs-assets.js") || fromSolverDir("highs", "assets")) {
77
+ return `${VIRTUAL_PREFIX}highs-assets`;
78
+ }
79
+ if (source === "./pumpkin-assets.js" || source.endsWith("/pumpkin-assets.js") || fromSolverDir("pumpkin", "assets")) {
80
+ return `${VIRTUAL_PREFIX}pumpkin-assets`;
81
+ }
82
+ if (
83
+ source === "./highs-worker-factory.js" ||
84
+ source.endsWith("/highs-worker-factory.js") ||
85
+ fromSolverDir("highs", "worker-factory")
86
+ ) {
87
+ return `${VIRTUAL_PREFIX}highs-worker-factory`;
88
+ }
89
+ if (
90
+ source === "./pumpkin-worker-factory.js" ||
91
+ source.endsWith("/pumpkin-worker-factory.js") ||
92
+ fromSolverDir("pumpkin", "worker-factory")
93
+ ) {
94
+ return `${VIRTUAL_PREFIX}pumpkin-worker-factory`;
95
+ }
96
+ if (
97
+ source === "./highs-node-runtime.js" ||
98
+ source.endsWith("/highs-node-runtime.js") ||
99
+ fromSolverDir("highs", "node-runtime")
100
+ ) {
101
+ return `${VIRTUAL_PREFIX}highs-node-runtime`;
102
+ }
103
+ if (
104
+ source === "./pumpkin-node-runtime.js" ||
105
+ source.endsWith("/pumpkin-node-runtime.js") ||
106
+ fromSolverDir("pumpkin", "node-runtime")
107
+ ) {
108
+ return `${VIRTUAL_PREFIX}pumpkin-node-runtime`;
109
+ }
110
+ if (source === "./z3-assets.js" || source.endsWith("/z3-assets.js") || fromSolverDir("z3", "assets")) {
111
+ return `${VIRTUAL_PREFIX}z3-assets`;
112
+ }
113
+ if (source === "z3-solver") {
114
+ return `${VIRTUAL_PREFIX}z3-solver`;
115
+ }
116
+ if (source === "glpk.js" || source === "glpk.js/node") {
117
+ return `${VIRTUAL_PREFIX}glpk`;
118
+ }
119
+ if (source.startsWith("node:") || source === "module") {
120
+ return `${VIRTUAL_PREFIX}node-stub`;
121
+ }
122
+ return null;
123
+ },
124
+ load(id) {
125
+ if (!id.startsWith(VIRTUAL_PREFIX)) {
126
+ return null;
127
+ }
128
+ const key = id.slice(VIRTUAL_PREFIX.length);
129
+ switch (key) {
130
+ case "highs-assets":
131
+ return "export function getBundledWasmUrl() { return ''; }\n";
132
+ case "pumpkin-assets":
133
+ return "export function getBundledPumpkinWasmUrl() { return ''; }\n";
134
+ case "highs-worker-factory":
135
+ return "export function createHighsWorker() { throw new Error('Workers are disabled in single-file offline builds; pass { useWorker: false }.'); }\n";
136
+ case "pumpkin-worker-factory":
137
+ return "export function createPumpkinWorker() { throw new Error('Workers are disabled in single-file offline builds; pass { useWorker: false }.'); }\n";
138
+ case "highs-node-runtime":
139
+ return "export async function loadNodeHighs() { throw new Error('Node runtime is unavailable in browser builds.'); }\n";
140
+ case "pumpkin-node-runtime":
141
+ return [
142
+ "export async function readPumpkinWasmFileUrl() { throw new Error('Node runtime is unavailable in browser builds.'); }",
143
+ "export async function readBundledPumpkinWasmBytes() { throw new Error('Node runtime is unavailable in browser builds.'); }",
144
+ ].join("\n");
145
+ case "z3-assets":
146
+ return "export function getBundledZ3AssetUrls() { throw new Error('Z3 is unsupported in offline single-file HTML builds (SharedArrayBuffer requires COOP/COEP headers).'); }\n";
147
+ case "z3-solver":
148
+ return "export function init() { throw new Error('Z3 is unsupported in offline single-file HTML builds (SharedArrayBuffer requires COOP/COEP headers).'); }\nexport default { init };\n";
149
+ case "glpk":
150
+ return "export default function glpkStub() { throw new Error('GLPK is not bundled in this single-file build.'); }\n";
151
+ case "node-stub":
152
+ return [
153
+ "export default {};",
154
+ "export const existsSync = () => false;",
155
+ "export const fileURLToPath = () => '';",
156
+ "export const createRequire = () => () => { throw new Error('Node runtime is unavailable in browser builds.'); };",
157
+ "export const readFile = async () => { throw new Error('Node runtime is unavailable in browser builds.'); };",
158
+ "export const dirname = () => '';",
159
+ "export const resolve = () => '';",
160
+ "export const join = (...parts) => parts.join('/');",
161
+ ].join("\n");
162
+ default:
163
+ return null;
164
+ }
165
+ },
166
+ transformIndexHtml: {
167
+ order: "post",
168
+ handler(html) {
169
+ const wasmDir = resolveWasmDir();
170
+ const tags = solvers.map((solver) => {
171
+ const wasmPath = path.join(wasmDir, `${solver}.wasm`);
172
+ if (!existsSync(wasmPath)) {
173
+ throw new Error(`WaSHI offline plugin could not find ${wasmPath}`);
174
+ }
175
+ const b64Gz = gzipSync(readFileSync(wasmPath), { level: 9 }).toString("base64");
176
+ return {
177
+ tag: "script",
178
+ attrs: { type: "text/plain", id: `washi-wasm-${solver}-gz` },
179
+ children: b64Gz,
180
+ injectTo: "head-prepend",
181
+ };
182
+ });
183
+ return { html, tags };
184
+ },
185
+ },
186
+ };
187
+ }
188
+ ```
189
+
190
+ ## Step 2: Configure `vite.config.ts`
191
+
192
+ Pair `viteSingleFile()` with `washiSingleHtmlWasmPlugin(...)` and inline all assets (`assetsInlineLimit: 100_000_000`, `cssCodeSplit: false`, `minify: true`):
193
+
194
+ > **Vite 8 Note**: Use `minify: true` (or omit `minify` to keep Vite's default minifier). Do **not** set `minify: "esbuild"` unless `esbuild` is explicitly installed, because Vite 8 uses Oxc/Rolldown by default.
195
+
196
+ ```ts
197
+ import { defineConfig } from "vite";
198
+ import { viteSingleFile } from "vite-plugin-singlefile";
199
+ import { washiSingleHtmlWasmPlugin } from "./vite-washi-offline.mjs";
200
+
201
+ export default defineConfig({
202
+ plugins: [
203
+ washiSingleHtmlWasmPlugin({ solvers: ["highs", "pumpkin"] }),
204
+ viteSingleFile(),
205
+ ],
206
+ build: {
207
+ outDir: "dist",
208
+ assetsInlineLimit: 100_000_000,
209
+ cssCodeSplit: false,
210
+ minify: true,
211
+ },
212
+ });
213
+ ```
214
+
215
+ ## Step 3: Add Browser Gzip-WASM Hydration (`src/washi-offline.ts`)
216
+
217
+ Add `src/washi-offline.ts` to decompress the embedded `<script type="text/plain">` blocks at startup, encode them as `data:application/wasm;base64,...` data URLs via `FileReader.readAsDataURL`, and register them with WaSHI before solving:
218
+
219
+ <!-- washi-single-html:runtime-helper -->
220
+ ```ts
221
+ import { setHighsWasmUrl } from "@ohtaman/washi/solvers/highs";
222
+ import { setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
223
+
224
+ export type OfflineSolverName = "highs" | "pumpkin";
225
+
226
+ let hydrationPromise: Promise<void> | null = null;
227
+
228
+ export async function inflateGzipBase64ToBytes(base64Gz: string): Promise<Uint8Array<ArrayBuffer>> {
229
+ const binary = atob(base64Gz.trim());
230
+ const compressed = new Uint8Array(binary.length);
231
+ for (let i = 0; i < binary.length; i++) {
232
+ compressed[i] = binary.charCodeAt(i);
233
+ }
234
+ const stream = new Blob([compressed]).stream().pipeThrough(new DecompressionStream("gzip"));
235
+ const buffer = await new Response(stream).arrayBuffer();
236
+ return new Uint8Array(buffer);
237
+ }
238
+
239
+ export function bytesToWasmDataUrl(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
240
+ return new Promise((resolve, reject) => {
241
+ const reader = new FileReader();
242
+ reader.onload = () => {
243
+ if (typeof reader.result === "string") {
244
+ resolve(reader.result);
245
+ } else {
246
+ reject(new Error("Expected FileReader.readAsDataURL() to produce a string."));
247
+ }
248
+ };
249
+ reader.onerror = () => reject(reader.error ?? new Error("Failed to encode WASM bytes as data URL."));
250
+ reader.readAsDataURL(new Blob([bytes], { type: "application/wasm" }));
251
+ });
252
+ }
253
+
254
+ async function loadSolverDataUrl(solver: OfflineSolverName): Promise<string> {
255
+ const el = document.getElementById(`washi-wasm-${solver}-gz`);
256
+ const payload = el?.textContent?.trim();
257
+ if (!payload) {
258
+ throw new Error(`Missing embedded gzipped WASM element #washi-wasm-${solver}-gz.`);
259
+ }
260
+ const wasmBytes = await inflateGzipBase64ToBytes(payload);
261
+ return bytesToWasmDataUrl(wasmBytes);
262
+ }
263
+
264
+ /**
265
+ * Hydrates embedded gzipped WASM payloads once before calling Model.solve() or Model.check().
266
+ */
267
+ export function hydrateOfflineWashiSolvers(
268
+ solvers: ReadonlyArray<OfflineSolverName> = ["highs", "pumpkin"],
269
+ ): Promise<void> {
270
+ if (!hydrationPromise) {
271
+ hydrationPromise = (async () => {
272
+ const unique = Array.from(new Set(solvers));
273
+ await Promise.all(
274
+ unique.map(async (solver) => {
275
+ const dataUrl = await loadSolverDataUrl(solver);
276
+ if (solver === "highs") {
277
+ setHighsWasmUrl(dataUrl);
278
+ } else {
279
+ setPumpkinWasmUrl(dataUrl);
280
+ }
281
+ }),
282
+ );
283
+ })();
284
+ }
285
+ return hydrationPromise;
286
+ }
287
+ ```
288
+
289
+ ## Step 4: Model, Solve with `{ useWorker: false }`, and Verify
290
+
291
+ Always call `await hydrateOfflineWashiSolvers(...)` once before solving, pass `{ useWorker: false }` in every `solve()` / `check()` call, and assert `m.verify().valid` (never hardcode solver answers in UI state). Because `{ useWorker: false }` runs on the browser main thread, set a sensible `timeLimit` (e.g. `{ useWorker: false, timeLimit: 5 }`) for non-trivial MIP/CP models so the UI does not appear frozen and always yields a frame before displaying loading indicators:
292
+
293
+ ```ts
294
+ import katex from "katex";
295
+ import "katex/dist/katex.min.css";
296
+ import { Model, expr, maximize } from "@ohtaman/washi";
297
+ import { hydrateOfflineWashiSolvers } from "./washi-offline";
298
+
299
+ async function runOptimization() {
300
+ await hydrateOfflineWashiSolvers(["highs", "pumpkin"]);
301
+
302
+ const m = new Model({ name: "production-mix" });
303
+ const x = m.continuous("x", { lb: 0, ub: 4 });
304
+ const y = m.continuous("y", { lb: 0, ub: 6 });
305
+ m.constraint(expr`${x} + ${y} <= 7`, "capacity");
306
+ m.objective(maximize(expr`3 * ${x} + 2 * ${y}`));
307
+
308
+ const status = await m.solve({ useWorker: false });
309
+ const report = m.verify();
310
+ if (!report.valid) {
311
+ throw new Error(`Solution verification failed: ${JSON.stringify(report.violations)}`);
312
+ }
313
+
314
+ document.getElementById("formula")!.innerHTML = katex.renderToString(
315
+ String.raw`\max\; 3x + 2y = ${m.objectiveValue}\quad (\text{${status}})`,
316
+ );
317
+ }
318
+
319
+ void runOptimization();
320
+ ```
321
+
322
+ ## Verification Checklist (Mandatory Before Delivering)
323
+
324
+ 1. **Build output check**: Verify `npm run build` outputs **only** `dist/index.html` (no emitted `.wasm`, `.js`, `.css`, or font files) and keeps WASM compressed (`~2.4 MiB` for HiGHS + Pumpkin Base64 gzip before JS/CSS/fonts, compared to `> 8.6 MiB` uncompressed Base64).
325
+ 2. **No external URLs in HTML**: Check `dist/index.html` for `<script src="http...`, `<link href="http...`, or CDN fallback URLs.
326
+ 3. **Headless Chrome `file://` E2E check**:
327
+ - Open `file:///absolute/path/to/dist/index.html` in Chromium/Playwright.
328
+ - Intercept `page.on("request", ...)` and assert **zero** `http://` or `https://` requests occur (`data:` only).
329
+ - Assert **zero** `console` errors and **zero** `pageerror` exceptions.
330
+ - Interact with inputs and confirm real solver output (`Optimal` / `Sat` / `Unsat` / `unsatCore`) plus third-party UI rendering updates cleanly.