Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Rebuild Data Studio into a checked, reusable local analyst (#142)

Dee368eeb9c3831
diff --git a/.github/workflows/experience-checks.yml b/.github/workflows/experience-checks.yml
index 1c5224289..acca0a95a 100644
--- a/.github/workflows/experience-checks.yml
+++ b/.github/workflows/experience-checks.yml
@@ -39,6 +39,8 @@ jobs:
run: node --test store/agents/openscad/test/*.test.mjs
- name: Check OrcaSlicer briefs, G-code and delivery (native suite is opt-in)
run: node --test store/agents/orca-slicer/test/*.test.mjs
+ - name: Check Data Studio imports, SQL, real SQLite delivery and failure guards
+ run: node --test store/agents/data-studio/test/*.test.mjs
authoring-browser:
runs-on: ubuntu-latest
@@ -62,6 +64,13 @@ jobs:
python3 -m venv /tmp/music-delivery-reader
/tmp/music-delivery-reader/bin/pip install mido==1.3.3
/tmp/music-delivery-reader/bin/python store/tools/experience-tests/verify-music-delivery.py work/experience-evidence/afterhours-production.zip
+ - name: Revise and reopen real Data Studio projects in the sandboxed browser
+ env:
+ PLAYWRIGHT_MODULE: store/tools/experience-tests/node_modules/playwright-core/index.mjs
+ DATA_EVIDENCE_DIR: work/data-studio-evidence
+ run: node store/agents/data-studio/test/browser.mjs
+ - name: Independently verify Data Studio exports with Python CSV, Decimal and SQLite
+ run: python3 store/agents/data-studio/test/verify-exports.py work/data-studio-evidence
- name: Revise three brand briefs and verify real print deliveries
run: |
sudo apt-get update -qq
diff --git a/store/agents/creative-direction/README.md b/store/agents/creative-direction/README.md
index fd935a9a3..de9721130 100644
--- a/store/agents/creative-direction/README.md
+++ b/store/agents/creative-direction/README.md
@@ -72,7 +72,7 @@ python3 store/agents/creative-direction/test/verify-delivery.py PATH_TO_RUN
Browser/export checks require Chrome/Chromium; independent PDF inspection requires Poppler.
Technical tools retain `ready:false` until the agent has inspected the actual delivered work.
-## Identity and stewardship
+## Credit and stewardship
The original [icon](brand/icon.svg), [PNG](brand/icon.png), [light logo](brand/logo.svg) and
[dark logo](brand/logo-dark.svg) appear in the studio and desktop identity system.
diff --git a/store/agents/data-studio/.gitattributes b/store/agents/data-studio/.gitattributes
new file mode 100644
index 000000000..17b0a15b6
--- /dev/null
+++ b/store/agents/data-studio/.gitattributes
@@ -0,0 +1,8 @@
+# Preserve byte-pinned upstream assets exactly, including upstream whitespace.
+template/vendor/sqlite3.js -text -whitespace linguist-vendored
+template/vendor/sqlite3.wasm -text linguist-vendored
+template/vendor/EMSCRIPTEN-LICENSE.txt -text -whitespace linguist-vendored
+template/vendor/MUSL-COPYRIGHT.txt -text -whitespace linguist-vendored
+# CSV fixtures intentionally exercise CRLF and must retain exact source bytes.
+template/sources/*.csv -text whitespace=cr-at-eol
+test/fixtures/**/sources/*.csv -text whitespace=cr-at-eol
diff --git a/store/agents/data-studio/AGENTS.md b/store/agents/data-studio/AGENTS.md
index 6377174f1..fd78f46f6 100644
--- a/store/agents/data-studio/AGENTS.md
+++ b/store/agents/data-studio/AGENTS.md
@@ -1,13 +1,24 @@
# Data Studio
-Read the `data` skill. Build an exploratory dashboard around the user's actual data and question.
-The starter uses `index.html`, `dashboard.mjs` and `data.mjs`, with `data.csv` as its source.
-The shared viewer serves local modules and data; no CDN, build step or separate server is needed.
+Read the `data` skill. Turn the user's files and question into a repeatable local
+analysis, not a screenshot or a generic sample chart. Work one question through
+explicit import rules, saved SQLite queries, traceable evidence, a substantive
+revision and independent export/reopening checks.
-Preserve the meaning of the data: units, missing values, time order and filtering rules must be
-explicit. A load or parsing error is an error, never a reason to silently substitute sample data.
-Derive axes, labels, groups and totals from the source rather than hardcoding the starter's values.
+The workspace is self-contained: analysis.json, sources/*.csv, queries/*.sql,
+checks/*.sql, the browser UI and tools/*.mjs. Never infer numeric IDs, time order,
+currency, join cardinality, missing-value treatment or rate denominators.
+Keep original CSV text. An import error must never substitute example data.
+Use clearly labelled synthetic data only when requested or agreed.
-Provide useful filters, exact-value inspection, a clear empty state and a downloadable selection.
-Keep `proof.json` current. `update-verdict.sh` now runs a real browser proof, not a file-existence
-check. Inspect the screenshot and exercise changed datasets before reporting completion.
+Run the native build and actual browser proof before readiness. A successful
+build alone leaves ready=false. Test another schema, not just renamed starter
+columns. Check meaningful data/query revisions, empty and missing states,
+source-record links, saved JSON, independent SQLite readers and portable ZIPs.
+Preserve prior outputs when a candidate fails. Keep proof.json specific to the
+current project's real controls and exact results.
+
+Do not upload source data, execute extensions, install remote services or read
+unrelated local files. Exported projects/databases include the declared raw
+inputs; explain that before sharing. Leave legacy workspaces intact; create a
+new workspace or adapt their data explicitly rather than overwriting files.
diff --git a/store/agents/data-studio/PROVENANCE.md b/store/agents/data-studio/PROVENANCE.md
index 99dcadec8..fc42eddfc 100644
--- a/store/agents/data-studio/PROVENANCE.md
+++ b/store/agents/data-studio/PROVENANCE.md
@@ -1,5 +1,33 @@
# Data Studio provenance
-The dashboard, CSV parser, aggregation, starter data, instructions and tests are original
-OpenHarness work, licensed MIT. The starter does not include D3, Plotly or any chart-library CDN.
-`data.csv` is synthetic demonstration data, not a report of real business results.
+The import contracts, CSV parser, SQLite adapters, query guards, viewer,
+portable-delivery helpers, synthetic example records, instructions and tests
+are original OpenHarness work (MIT). ZIP and filesystem transaction helpers
+are adapted from OpenHarness's OpenSCAD/OrcaSlicer workflows under the same MIT
+license. Neither example represents real people, sales, shipments or carriers.
+
+## Native and browser engines
+
+The build uses Node's built-in node:sqlite; Node is supplied by the host or the
+Harness-managed runtime, not bundled here. API:
+https://nodejs.org/download/release/v22.17.0/docs/api/sqlite.html
+
+The browser uses the **unmodified official SQLite 3.53.4** JavaScript/WebAssembly
+assets from https://www.sqlite.org/2026/sqlite-wasm-3530400.zip.
+The archive's SHA3-256 was verified against the official download page:
+e4fa7e1750b42f6954115d8e69ffff7dc08da7e9fee6e28a2a0ea6bf228a49f2.
+Individual SHA-256 hashes are committed in template/vendor/checksums.json and
+checked by setup, build and browser loading.
+
+SQLite is public-domain software. Its generated Emscripten glue has MIT and
+University of Illinois/NCSA terms. The upstream banner, exact Emscripten 5.0.1
+license and musl copyright notice are retained in template/vendor/ and every
+portable project. See vendor/NOTICE.md and https://www.sqlite.org/copyright.html.
+
+Implementation references:
+https://www.sqlite.org/wasm/doc/trunk/api-oo1.md
+https://www.sqlite.org/wasm/doc/trunk/cookbook.md
+
+No OPFS, localStorage, CDN, npm runtime dependency or hosted database is used.
+All source data remains local unless the user chooses to share an export.
+No upstream endorsement or warranty is implied.
diff --git a/store/agents/data-studio/README.md b/store/agents/data-studio/README.md
index a821b54af..e743c1fa2 100644
--- a/store/agents/data-studio/README.md
+++ b/store/agents/data-studio/README.md
@@ -1,28 +1,77 @@
# Data Studio
-Drop a CSV into a working analytical dashboard. Change measures, compare groups, narrow the period,
-switch between trends and bars, inspect exact values and export the filtered rows. Charts and
-summaries derive from your data. Errors and empty selections stay visible.
+Ask a question of your files, then keep an answer you can inspect and repeat.
-The starter runs entirely locally with no chart-library CDN. It includes a quoted-field CSV parser,
-safe imports and keyboard-accessible point inspection. Browser imports are temporary until exported.
-The default view expects two text dimensions plus a numeric measure; the agent can adapt that schema.
+Join CSVs with explicit types and checked keys. Compare periods, calculate rates
+from the right denominator, follow a result to original records, revise the SQL
+or replace a source, then export a report, SQLite database and editable project.
+The data and calculations stay local; there is no CDN or hosted analysis service.
-Try: “Compare regional revenue across quarters, show what changed, and let me explore the raw rows.”
+Try: “Join these sales and product files. Explain which categories contributed
+to the change in net sales, show the source transactions, and give me a report
+I can rerun next month.”
-Choose **Data Studio** in the Harness Store, then New Harness and an empty folder. Local development:
+The included sales example is synthetic. A separate delivery-performance
+acceptance case exercises a different schema, missing delivery dates, as-of
+controls and ratio calculations. Neither claims real-world business results.
+
+## Start and use
+
+Choose **Data Studio** in the Harness Store, then New Harness and an empty folder.
+The initializer builds the sample's real SQLite database. Ask the agent to adapt
+analysis.json and the readable SQL to your own question and files. Existing
+legacy dashboards are not silently migrated or overwritten.
+
+The browser lets you apply controls, trace category bars, inspect original CSV
+records, replace a file with the same schema, revise read-only SQL, and download
+the current project, database, exact JSON, spreadsheet-safe CSV or inert HTML
+report. Use **Save project** to retain browser changes; they are not autosaved
+into the workspace. **Open project** recalculates a saved JSON project.
+Exported SQLite databases require a SQLite 3.37+ reader for STRICT tables.
+
+A portable ZIP contains the last workspace build, source files, SQL, viewer,
+pinned SQLite browser runtime and standalone helpers. After extracting:
```sh
-harness dsh install "$PWD/store/agents/data-studio" --link
-harness dsh doctor autonomous/data-studio
+node tools/build.mjs
+node tools/serve.mjs
```
-Requires Node 20+ and the shared Web Viewer. Browser proofs are optional development tooling, but
-the readiness helper requires a successful real-browser check; file existence is not proof.
+Open the exact loopback URL it prints. Saved JSON can also be restored into a
+new folder with `node tools/restore.mjs saved.data-studio.json NEW_FOLDER`.
+See [the portable project guide](template/PROJECT.md) for units, export semantics
+and exact limits.
+
+Requires Node 22.16+ with native SQLite; setup reuses the Harness-managed runtime.
+No npm installation is needed. Real-browser verification requires the shared
+isolated viewer and Playwright/Chromium; missing browser tooling never becomes
+a passing verdict.
+
+## Checks and limits
+
+Explicit text/date/integer/scaled-decimal/real columns; required vs nullable
+values; unique keys; declared many-to-one joins; saved reconciliation queries;
+read-only SQL; bounded execution; source hashes; staged publication; previous
+outputs retained; independent read-only reopening of the actual SQLite file.
+The browser's initial results must agree with the saved native build.
+
+At most 8 CSVs, 50 columns each, 100,000 total records and 6 MiB CSV combined.
+At most 1,000,000 source cells, 12 queries, 10,000 rows / 4 MiB per result and
+8 MiB of combined results. No spreadsheet formula
+evaluation or Excel workbook import. Ask the agent to export workbook data as
+CSV with explicit types when needed. This does not infer causation, certify
+arbitrary SQL, or replace domain review.
+
+Exported projects, databases and reports contain the source data. Review before
+sharing. Raw CSVs can contain formula-looking text; the safe result CSV adds an
+apostrophe, while SQLite/JSON retain exact types and nulls.
+
+See [acceptance evidence](test/ACCEPTANCE.md) for tested workflows and limits.
## Credit and stewardship
-The original wrapper and starter are MIT-licensed OpenHarness work. See
-[PROVENANCE.md](PROVENANCE.md) for upstream tools, datasets and their separate
-licenses. No upstream ownership or endorsement is implied. Wrapper issues belong
-in OpenHarness; upstream maintainers are welcome to take stewardship of a package.
+The original wrapper, analysis engine, UI, synthetic data and tests are
+MIT-licensed OpenHarness work. See [PROVENANCE.md](PROVENANCE.md) for the pinned
+SQLite and Emscripten runtime and their separate terms. No upstream ownership
+or endorsement is implied. Wrapper issues belong in OpenHarness; upstream
+maintainers are welcome to take stewardship of a package.
diff --git a/store/agents/data-studio/harness.json b/store/agents/data-studio/harness.json
index 535a46d99..045cfa76f 100644
--- a/store/agents/data-studio/harness.json
+++ b/store/agents/data-studio/harness.json
@@ -4,7 +4,7 @@
"name": "Data Studio",
"category": "Data",
"author": "OpenHarness contributors",
- "description": "Turn CSV into a local interactive dashboard with dynamic metrics, filtering, exact-value inspection, safe imports and selection export.",
+ "description": "Turn CSV files and a question into a repeatable local analysis: checked joins, exact calculations, source-record drilldown, revisions and portable SQLite/report/project exports.",
"engine": "claude",
"workspace": {
"template": "template",
diff --git a/store/agents/data-studio/package.json b/store/agents/data-studio/package.json
index dd9647a1e..b66083471 100644
--- a/store/agents/data-studio/package.json
+++ b/store/agents/data-studio/package.json
@@ -7,6 +7,6 @@
"perf": "node skills/data/scripts/perf.mjs"
},
"engines": {
- "node": ">=20"
+ "node": ">=22.16"
}
}
diff --git a/store/agents/data-studio/skills/data/SKILL.md b/store/agents/data-studio/skills/data/SKILL.md
index 03ad0e811..0a5ad9f6c 100644
--- a/store/agents/data-studio/skills/data/SKILL.md
+++ b/store/agents/data-studio/skills/data/SKILL.md
@@ -1,38 +1,84 @@
---
name: data
-description: Build and verify interactive CSV dashboards in Data Studio, with truthful metrics, filtering, inspection and export.
+description: Turn user CSV files and a question into a typed, joined, repeatable local SQLite analysis with traceable records, browser revisions and verified portable exports.
---
# Data Studio
-Read the source before choosing a chart. `data.mjs` contains the tested CSV parser and aggregation;
-`dashboard.mjs` binds it to the interface. The default parser supports quoted fields, embedded
-newlines, escaped quotes, BOM and CRLF, and rejects duplicate headers or ragged records.
+Deliver an answer the user can inspect, revise and rerun with their next data
+file. Do not stop at a starter screenshot or a watch-only visualization.
+Read [the analysis contract](references/analysis-contract.md) before changing a
+schema, query, join, unit, missing-value rule or chart.
-The starter needs two text dimensions (period and group) and at least one fully numeric column.
-Uploads are limited to 5 MB. Numeric-looking year columns will be inferred as measures: adapt the
-mapping when the user's schema differs. Periods use natural string order; parse dates explicitly
-for formats that do not sort chronologically. Missing period/group combinations aggregate to zero.
-Blank numeric values are not silently imputed. Do not assume revenue means USD; currency suffixes
-such as `_usd` are explicit units.
+## Understand the question
-Use the source data for every metric, tooltip and exported row. Labels and uploaded text go through
-`textContent`. The browser's imported data is temporary; export it to persist a selection. Exported
-CSV preserves source values, including formula-looking text; treat it as untrusted in spreadsheet apps.
+Use the user's files and known intent. Ask only for materially missing facts:
+what decision/question, field meanings, units/currency, period boundaries,
+join keys, duplicates and missing-data treatment. Never ask again for answers
+already supplied. If example data was approved, keep example=true and make
+the synthetic-data label visible in the UI and every report.
-## Verification
+Inspect a bounded sample and counts. Preserve original CSV text; map columns
+explicitly in analysis.json. IDs that look numeric remain text. ISO dates are
+strictly parsed. For money, use decimal with a declared scale and unit:
+values such as 12.30 become integer cents, with no implicit rounding.
+
+## Build the useful workflow
+
+1. Write the question, method, source mappings, keys, joins, controls and
+ limitations in analysis.json. Add readable queries/*.sql and checks/*.sql.
+2. Make the queries answer the actual question. Rates come from matched totals,
+ not sums/averages of ratios. Missing remains missing unless the question
+ explicitly defines an absent record as zero. Do not infer causality.
+3. Add source-record links and a matching detail query. Check the detail rows
+ reconcile to the aggregate under the same filters. A valid record number
+ alone does not prove the link supports the interpretation.
+4. Use controls, exact tables, charts with truthful axes and empty states, and
+ visible calculation explanations. Changing SQL in the browser labels the
+ old explanation as needing review. Update the description when formalizing
+ that revision in the workspace.
+5. Rebuild, revise an input or query substantially, and independently check the
+ new result. Include an alternative schema/question in package acceptance.
+ Do not use the same aggregation helper as your only reference calculation.
```sh
+bash "$DATA_TOOLCHAIN/node.sh" "$HARNESS_WORKSPACE/tools/build.mjs" "$HARNESS_WORKSPACE"
sh "$DATA_SKILLS/data/scripts/update-verdict.sh"
-node "$DATA_SKILLS/data/scripts/perf.mjs" "$HARNESS_WORKSPACE/index.html"
```
-The first command runs the shared browser proof and writes the verdict, screenshot and
-`.harness/browser-proof.json` with hashes of loaded local files. It requires Playwright + Chromium
-in the shared isolated-web-viewer package, or `PLAYWRIGHT_MODULE` pointing to `playwright/index.mjs`.
-Keep `proof.json` as real control actions and exact text/attribute assertions. Update it when the
-dashboard changes. A failed or unavailable browser check must not become `ready: true`.
+The one-stop command rebuilds and runs the actual isolated browser proof.
+Node 22.16+ is supplied by the host or Harness-managed runtime. The build writes
+ready=false until a browser proof passes. Missing Playwright/viewer is a failed
+or unavailable check, never permission to manually write ready=true.
+
+## Verify and hand off
+
+Keep proof.json specific to the current data, actual controls and exact
+expected results. Its recipe must wait on the resulting state (not a fixed
+sleep). The default proof is for the synthetic sales project; replace it for a
+different question. The shared probe records loaded-file hashes and screenshots.
+Inspect desktop and 390px layouts, errors, nulls, zero denominators, no matches,
+negative changes, quoting, duplicate keys and invalid imports.
+
+Exercise controls, keyboard drilldown, source records, revised SQL and CSV
+replacement. Save JSON, change the view, reopen the JSON and verify the edits,
+applied parameters and notes survive. Download the actual SQLite database and
+query it with an independent reader. Extract the original ZIP into another
+directory, rebuild with its own tools, and open its standalone server. A failed
+candidate must preserve the last good outputs and keep readiness false.
+
+The result CSV prefixes formula-looking text and encodes null as an empty
+field; JSON/SQLite retain exact text and null. Explain decimal storage units.
+Do not substitute screenshots for usable exports. Reports must include applied
+controls, method, limitations, checks and the revision.
+
+Browser edits are not filesystem autosaves. **Save project** captures current
+data/rules/queries/applied controls/notes; unapplied drafts are not saved.
+**Original built project ZIP** is the last CLI build. To create a ZIP of browser
+edits, restore the saved JSON to a new directory, then rebuild it. The portable
+PROJECT.md documents these commands and bounds.
-Inspect desktop and narrow layouts. Test another dataset, no matching rows, negative/zero values,
-malformed CSV, changed column names, keyboard point inspection and export. The performance helper
-exercises controls while measuring frame delays/long tasks; do not claim an unmeasured frame rate.
+Never overwrite a legacy workspace while upgrading. Never share, upload,
+redact or delete user data without authority. Only declared source files enter
+the portable project. Warn that saved JSON, SQLite and ZIP contain raw inputs.
+Do not edit vendored SQLite; its hashes and notices must remain intact.
diff --git a/store/agents/data-studio/skills/data/references/analysis-contract.md b/store/agents/data-studio/skills/data/references/analysis-contract.md
new file mode 100644
index 000000000..81464bc0b
--- /dev/null
+++ b/store/agents/data-studio/skills/data/references/analysis-contract.md
@@ -0,0 +1,83 @@
+# Analysis contract and verification
+
+The canonical, executable contract is template/core.js. A workspace carries the
+same core.js for Node, the page and its worker. Read analysis.json for a complete
+sales example; test/fixtures/delivery is a second, independent question.
+
+## Project files
+
+- analysis.json: spec=1, title, question, example boolean, method, limitations,
+ tables, relationships, parameters, queries and checks. Unknown fields fail.
+- sources/*.csv: original UTF-8 text. Quoted/multiline fields, BOM and CRLF work.
+ Duplicate/blank headers, ragged records, blank records and invalid quoting
+ fail. _record is the CSV record number (header=1), not physical line number.
+- queries/*.sql: one read-only SELECT/WITH per file. Only named :parameters.
+- checks/*.sql: each returns one violations column, one row, exactly zero.
+- optional view.json: parameters, selectedQuery and notes. Save project captures
+ these settings with sources and SQL in a checksum-bound JSON envelope.
+
+## Types and joins
+
+Each table has an id, file, label, columns and optional key array. Each column
+has a safe SQL name, an exact source header, a type and explicit nullable boolean.
+Supported types: text, integer, decimal (scale 0–6), real, date (YYYY-MM-DD).
+The default missing token is the empty string. Set missing explicitly to change
+it. Whitespace is preserved unless trim=true. Extra/unmapped CSV headers fail;
+do not silently discard columns or source rows. Integer/scaled-decimal values
+must stay within JavaScript's exact integer range. Hex, grouped numbers,
+currency symbols and implicit precision rounding are rejected. REAL is binary
+floating point, not exact money. All source and result values must be finite.
+
+A relationship declares from/to table and column plus allowMissing. The target
+must have a single-column unique, non-null key; key types/scales must agree.
+Duplicate keys fail before a join can multiply rows. If unmatched rows are
+explicitly allowed, name their treatment in the method and query; inner joins
+may otherwise drop them. Many-to-many analysis needs an explicitly prepared
+bridge and independent reconciliation, not a claim of many-to-one validation.
+
+## Parameters and queries
+
+Parameters have id, label, type, default, optional text choices and hidden.
+Dates and numeric controls are validated before binding. Values never enter SQL
+through interpolation. Each query has id, title, file, kind, explanation and
+optional formats. Kinds: metric (exactly one result row), bar (explicit x/y,
+at most 100 categories), table and detail. Result aliases must be unique.
+Every chart plots the returned result values; it does not re-aggregate rates or
+invent missing combinations. The query defines ordering. Percent charts include
+0–100% as well as any out-of-range values; change charts include zero.
+
+Formats map output aliases to style number/currency/percent/text, optional
+positive divisor, digits 0–6 and unit. Currency requires a three-letter code.
+Example: cents use {style:"currency",currency:"USD",divisor:100,digits:2}.
+Formatting never changes the exported stored numeric value.
+
+A trace has a detail query id and bindings mapping hidden parameter ids to
+aggregate result aliases. sourceLinks maps detail result aliases to table ids.
+Return the table's actual _record; browser links show the original CSV record.
+The build checks existence, but authors must verify that the linked record and
+detail filters really support the aggregate. Reconcile the arithmetic with an
+independent reader/calculation. Do not present record links as automatic proof
+of arbitrary SQL semantics.
+
+## Safety and lifecycle
+
+Only one SELECT/WITH statement is accepted. Writes, PRAGMA, file functions,
+extension functions and positional parameters are disabled. Native execution
+uses an isolated child process; browser execution uses a disposable in-memory
+worker. Both have a 20-second budget and 128 MiB SQLite heap. SQL extensions,
+origin storage and network services are not needed.
+Source bounds: 8 files, 50 columns each, 100,000 total records, 1,000,000 cells,
+6 MiB CSV combined. Result bounds: 12 queries, 10,000 rows / 4 MiB per query,
+8 MiB combined. Browser runs can also be cancelled without losing good results.
+
+Builds lock, snapshot declared sources/runtime assets, calculate in staging,
+reopen SQLite read-only, rerun every query, compare results, validate links,
+hash outputs and verify inputs did not change before publishing. The previous
+output is retained in .harness/history. Failed builds clear readiness. Do not
+remove a lock unless its recorded process is confirmed stopped.
+
+The standalone server serves an exact file allowlist over a tokenized loopback
+URL. There is no write/SQL/upload endpoint. Project source files and queries
+are editable through the agent; browser edits persist only through download.
+Native file checks and browser proofs do not establish real-world correctness
+of user-entered assumptions. Name unverified assumptions and remaining review.
diff --git a/store/agents/data-studio/skills/data/scripts/update-verdict.sh b/store/agents/data-studio/skills/data/scripts/update-verdict.sh
index b96ab9178..b0fa35cfa 100755
--- a/store/agents/data-studio/skills/data/scripts/update-verdict.sh
+++ b/store/agents/data-studio/skills/data/scripts/update-verdict.sh
@@ -1,3 +1,7 @@
#!/bin/sh
set -eu
-exec node "$(dirname "$0")/screenshot.mjs" "${HARNESS_WORKSPACE:-$PWD}/index.html"
+here="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
+toolchain="${DATA_TOOLCHAIN:-$here/../../../toolchain}"
+workspace="${HARNESS_WORKSPACE:-$PWD}"
+bash "$toolchain/node.sh" "$workspace/tools/build.mjs" "$workspace"
+exec bash "$toolchain/node.sh" "$here/screenshot.mjs" "$workspace/index.html"
diff --git a/store/agents/data-studio/store.json b/store/agents/data-studio/store.json
index b79b9bb33..936d1c6a8 100644
--- a/store/agents/data-studio/store.json
+++ b/store/agents/data-studio/store.json
@@ -1,17 +1,29 @@
{
- "listed": false,
+ "listed": true,
"homepage": "https://github.com/autonomous-ai/openharness/tree/main/store/agents/data-studio",
"upstream": "https://github.com/autonomous-ai/openharness/tree/main/store/agents/data-studio",
"license": "MIT",
- "tagline": "Explore CSV data with live charts, filters and exact values",
+ "tagline": "Turn your files into answers you can trace, revise and reuse",
"screenshots": [
- "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/data-studio/starter.jpg"
+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/data-studio/starter.jpg",
+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/data-studio/evidence.jpg",
+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/data-studio/delivery.jpg"
],
"examples": [
{
- "prompt": "Explore the included sample data, filter a region, compare metrics, and export the selected rows.",
+ "prompt": "Join transaction and product CSVs. Explain which categories contributed to the change in net sales, show the source records, and save an analysis I can rerun next month.",
"image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/data-studio/starter.jpg",
- "caption": "Synthetic data · working filters, charts and CSV export"
+ "caption": "Synthetic sales example · checked joins, exact money and reusable analysis"
+ },
+ {
+ "prompt": "Show the transactions behind the Outdoor category change. Let me inspect the original records, replace a source file and export the revised project.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/data-studio/evidence.jpg",
+ "caption": "Original source records · explicit types, editable queries and portable exports"
+ },
+ {
+ "prompt": "Which routes missed promised delivery, and which shipments are still open? Keep missing delivery dates distinct from zero and give me a reusable report.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/data-studio/delivery.jpg",
+ "caption": "Independent delivery example · as-of controls, correct denominators and missing values"
}
]
}
diff --git a/store/agents/data-studio/template/LICENSE b/store/agents/data-studio/template/LICENSE
new file mode 100644
index 000000000..d3eab18ed
--- /dev/null
+++ b/store/agents/data-studio/template/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 OpenHarness contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/data-studio/template/PROJECT.md b/store/agents/data-studio/template/PROJECT.md
new file mode 100644
index 000000000..5d637c3d1
--- /dev/null
+++ b/store/agents/data-studio/template/PROJECT.md
@@ -0,0 +1,71 @@
+# Your Data Studio project
+
+This is an editable local analysis, not a screenshot. The included sales data is
+synthetic. Read analysis.json for the question, method, types, units, joins,
+controls, saved queries, checks and limitations. Replace the sources only with
+files you are authorized to analyze and share.
+
+## Run and reopen
+
+Requires Node 22.16+ with node:sqlite (the Harness-managed Node works). No npm
+installation, CDN or network service is required. From this directory:
+
+ node tools/build.mjs
+ node tools/serve.mjs
+
+Open the exact loopback URL printed by the preview server. The app also runs in
+Harness's isolated viewer. The browser re-imports the data and checks that its
+SQLite results match the saved native build. Stop the server with Ctrl-C.
+
+Edit analysis.json and queries/*.sql through the agent, or use the browser's
+explicit controls and read-only SQL editor. Replace a source CSV with the same
+headers/types. For a new schema, change the explicit mappings with the agent.
+No type guessing, silent row dropping, automatic missing-to-zero conversion or
+automatic date/number cleanup is performed. A failed build/import leaves the
+last good results intact and does not mark the candidate ready.
+
+## Save and share
+
+Save project downloads current CSVs, schema, SQL, applied controls and review
+notes as one .data-studio.json. Reopen with Open project in any Data Studio
+workspace. To restore files for editing outside the app:
+
+ node tools/restore.mjs /path/to/analysis.data-studio.json /path/to/NEW_FOLDER
+
+Then build in that folder. Restore refuses to overwrite a nonempty directory.
+Unapplied SQL/control drafts are not saved. Browser changes never silently write
+to the original workspace. The original built ZIP is a snapshot of the last CLI
+build, not a browser autosave. Rebuild a restored JSON project to make a new ZIP.
+
+output/analysis.sqlite opens in SQLite 3.37+ tools (STRICT tables). It stores source tables
+with typed fields and a _record column: original CSV record number, including
+the header as record 1. Decimal fields are stored as scaled integers, NOT REAL;
+analysis.json records the scale/unit. Queries live separately as readable SQL.
+output/report.html is a standalone, inert report with applied parameters,
+results, method, checks, notes and limitations. CSV exports protect against
+formula-looking text with an apostrophe; use SQLite/project JSON for exact types
+and nulls. Do not open untrusted original CSVs with formula evaluation enabled.
+
+Project files, databases and reports contain the source data. Review before
+sharing; no automatic redaction or encryption is performed.
+
+## Limits and verification
+
+8 files / 50 columns each / 100,000 total records / 6 MiB source CSV combined.
+1,000,000 source cells, 12 saved queries, 10,000 result rows and 4 MiB per result
+(8 MiB combined); 20-second execution
+budget, 128 MiB SQLite heap. Query language is one read-only SELECT/WITH using
+named :parameters; no extension, file or write operations. All required query
+checks must return exactly one column named violations and one value 0.
+Declared many-to-one relationships require a unique target key. Result links
+are checked for valid source records; the agent must also test that drilldown
+queries match the intended calculation. Checks are evidence, not a guarantee
+that an arbitrary analytical interpretation is correct. Do not infer causation
+from descriptive comparisons.
+
+Builds stage outputs, reopen the actual SQLite file read-only, compare every
+query, verify input hashes before publication, and retain previous output under
+.harness/history. The build alone leaves readiness false: the agent must run a
+real interaction proof, inspect the interface and independently check the data.
+
+MIT wrapper; see LICENSE and vendor/NOTICE.md for upstream terms.
diff --git a/store/agents/data-studio/template/analysis.json b/store/agents/data-studio/template/analysis.json
new file mode 100644
index 000000000..3a9dfbc56
--- /dev/null
+++ b/store/agents/data-studio/template/analysis.json
@@ -0,0 +1,288 @@
+{
+ "spec": 1,
+ "title": "What changed in sales?",
+ "question": "Which categories contributed to the change in net sales between two months, and which transactions make up those numbers?",
+ "example": true,
+ "method": "Join transaction lines to a unique product catalog. Net sales = quantity × unit price − line discount − line refund. Include completed lines only. Compare calendar months using the recorded sale date; refunds are attributed to that sale, not cash receipt dates. Store USD amounts as exact integer cents. Category deltas describe contributions, not causes.",
+ "limitations": [
+ "Synthetic example data, not real business results or accounting statements.",
+ "No exchange-rate conversion, tax, shipping costs or profit calculation. A missing category/month is explicitly treated as no recorded completed sales for this question.",
+ "A sales-line count is not an order count. Growth is missing when baseline sales are zero."
+ ],
+ "tables": [
+ {
+ "id": "transactions",
+ "file": "sources/transactions.csv",
+ "label": "Transaction lines · synthetic",
+ "key": [
+ "line_id"
+ ],
+ "columns": [
+ {
+ "name": "line_id",
+ "source": "line_id",
+ "type": "text",
+ "nullable": false
+ },
+ {
+ "name": "sold_on",
+ "source": "sold_on",
+ "type": "date",
+ "nullable": false
+ },
+ {
+ "name": "product_id",
+ "source": "product_id",
+ "type": "text",
+ "nullable": false
+ },
+ {
+ "name": "region",
+ "source": "region",
+ "type": "text",
+ "nullable": false
+ },
+ {
+ "name": "quantity",
+ "source": "quantity",
+ "type": "integer",
+ "nullable": false
+ },
+ {
+ "name": "unit_price_cents",
+ "source": "unit_price_usd",
+ "type": "decimal",
+ "nullable": false,
+ "scale": 2,
+ "unit": "USD cents"
+ },
+ {
+ "name": "discount_cents",
+ "source": "discount_usd",
+ "type": "decimal",
+ "nullable": false,
+ "scale": 2,
+ "unit": "USD cents"
+ },
+ {
+ "name": "refund_cents",
+ "source": "refund_usd",
+ "type": "decimal",
+ "nullable": false,
+ "scale": 2,
+ "unit": "USD cents"
+ },
+ {
+ "name": "status",
+ "source": "status",
+ "type": "text",
+ "nullable": false
+ },
+ {
+ "name": "note",
+ "source": "note",
+ "type": "text",
+ "nullable": true
+ }
+ ]
+ },
+ {
+ "id": "products",
+ "file": "sources/products.csv",
+ "label": "Product catalog · synthetic",
+ "key": [
+ "product_id"
+ ],
+ "columns": [
+ {
+ "name": "product_id",
+ "source": "product_id",
+ "type": "text",
+ "nullable": false
+ },
+ {
+ "name": "product",
+ "source": "product",
+ "type": "text",
+ "nullable": false
+ },
+ {
+ "name": "category",
+ "source": "category",
+ "type": "text",
+ "nullable": false
+ }
+ ]
+ }
+ ],
+ "relationships": [
+ {
+ "from": {
+ "table": "transactions",
+ "column": "product_id"
+ },
+ "to": {
+ "table": "products",
+ "column": "product_id"
+ },
+ "allowMissing": false
+ }
+ ],
+ "parameters": [
+ {
+ "id": "baseline",
+ "label": "Baseline month (first day)",
+ "type": "date",
+ "default": "2026-01-01"
+ },
+ {
+ "id": "comparison",
+ "label": "Comparison month (first day)",
+ "type": "date",
+ "default": "2026-02-01"
+ },
+ {
+ "id": "region",
+ "label": "Region",
+ "type": "text",
+ "default": "",
+ "choices": [
+ "",
+ "East",
+ "West"
+ ]
+ },
+ {
+ "id": "category",
+ "label": "Drilldown category",
+ "type": "text",
+ "default": "",
+ "hidden": true
+ }
+ ],
+ "queries": [
+ {
+ "id": "headline",
+ "title": "Net sales comparison",
+ "file": "queries/headline.sql",
+ "kind": "metric",
+ "formats": {
+ "baseline_sales": {
+ "style": "currency",
+ "currency": "USD",
+ "divisor": 100,
+ "digits": 2
+ },
+ "comparison_sales": {
+ "style": "currency",
+ "currency": "USD",
+ "divisor": 100,
+ "digits": 2
+ },
+ "change": {
+ "style": "currency",
+ "currency": "USD",
+ "divisor": 100,
+ "digits": 2
+ },
+ "growth": {
+ "style": "percent",
+ "digits": 1
+ },
+ "completed_lines": {
+ "style": "number",
+ "digits": 0
+ }
+ },
+ "explanation": "Completed transaction lines in the selected calendar months and region. Money is calculated in cents, then formatted as USD. Growth = change / absolute baseline; a zero baseline stays missing."
+ },
+ {
+ "id": "contribution",
+ "title": "Where the change came from",
+ "file": "queries/contribution.sql",
+ "kind": "bar",
+ "x": "category",
+ "y": "change",
+ "formats": {
+ "baseline_sales": {
+ "style": "currency",
+ "currency": "USD",
+ "divisor": 100,
+ "digits": 2
+ },
+ "comparison_sales": {
+ "style": "currency",
+ "currency": "USD",
+ "divisor": 100,
+ "digits": 2
+ },
+ "change": {
+ "style": "currency",
+ "currency": "USD",
+ "divisor": 100,
+ "digits": 2
+ }
+ },
+ "explanation": "Change in recorded net sales by category. Select a category to inspect the transactions in both months. This is a decomposition, not a causal explanation.",
+ "trace": {
+ "query": "transactions_detail",
+ "bindings": {
+ "category": "category"
+ }
+ }
+ },
+ {
+ "id": "monthly",
+ "title": "Recorded monthly sales",
+ "file": "queries/monthly.sql",
+ "kind": "bar",
+ "x": "month",
+ "y": "net_sales",
+ "formats": {
+ "net_sales": {
+ "style": "currency",
+ "currency": "USD",
+ "divisor": 100,
+ "digits": 2
+ }
+ },
+ "explanation": "Only months with recorded completed lines are shown. Unrecorded months are not filled with zero."
+ },
+ {
+ "id": "transactions_detail",
+ "title": "Transaction evidence",
+ "file": "queries/detail.sql",
+ "kind": "detail",
+ "formats": {
+ "net_sales": {
+ "style": "currency",
+ "currency": "USD",
+ "divisor": 100,
+ "digits": 2
+ }
+ },
+ "sourceLinks": {
+ "transactions_record": "transactions",
+ "products_record": "products"
+ },
+ "explanation": "The actual joined transaction lines for both comparison months, the region filter and the selected category. Source links open the original CSV record, including unconverted strings."
+ }
+ ],
+ "checks": [
+ {
+ "id": "month_rules",
+ "file": "checks/months.sql",
+ "description": "Comparison controls are distinct first-of-month dates."
+ },
+ {
+ "id": "valid_amounts",
+ "file": "checks/amounts.sql",
+ "description": "Units, prices, discounts, refunds and statuses meet the saved business rules."
+ },
+ {
+ "id": "reconcile",
+ "file": "checks/reconcile.sql",
+ "description": "Category contributions reconcile to the transaction-level net sales change."
+ }
+ ]
+}
diff --git a/store/agents/data-studio/template/checks/amounts.sql b/store/agents/data-studio/template/checks/amounts.sql
new file mode 100644
index 000000000..65ba928bf
--- /dev/null
+++ b/store/agents/data-studio/template/checks/amounts.sql
@@ -0,0 +1,4 @@
+SELECT count(*) AS violations FROM transactions
+WHERE quantity<0 OR unit_price_cents<0 OR discount_cents<0 OR refund_cents<0
+ OR discount_cents+refund_cents>quantity*unit_price_cents
+ OR status NOT IN ('completed','cancelled');
diff --git a/store/agents/data-studio/template/checks/months.sql b/store/agents/data-studio/template/checks/months.sql
new file mode 100644
index 000000000..f230804ca
--- /dev/null
+++ b/store/agents/data-studio/template/checks/months.sql
@@ -0,0 +1,2 @@
+SELECT CASE WHEN substr(:baseline,9,2)='01' AND substr(:comparison,9,2)='01'
+ AND :baseline<>:comparison THEN 0 ELSE 1 END AS violations;
diff --git a/store/agents/data-studio/template/checks/reconcile.sql b/store/agents/data-studio/template/checks/reconcile.sql
new file mode 100644
index 000000000..394e4cd65
--- /dev/null
+++ b/store/agents/data-studio/template/checks/reconcile.sql
@@ -0,0 +1,11 @@
+WITH signed_lines AS (
+ SELECT CASE WHEN substr(sold_on,1,7)=substr(:comparison,1,7) THEN 1 ELSE -1 END
+ * (quantity*unit_price_cents-discount_cents-refund_cents) AS delta, product_id
+ FROM transactions
+ WHERE status='completed' AND (:region='' OR region=:region)
+ AND substr(sold_on,1,7) IN (substr(:baseline,1,7),substr(:comparison,1,7))
+), by_category AS (
+ SELECT p.category,sum(s.delta) AS delta FROM signed_lines s JOIN products p ON p.product_id=s.product_id GROUP BY p.category
+)
+SELECT CASE WHEN coalesce((SELECT sum(delta) FROM signed_lines),0)
+ =coalesce((SELECT sum(delta) FROM by_category),0) THEN 0 ELSE 1 END AS violations;
diff --git a/store/agents/data-studio/template/core.js b/store/agents/data-studio/template/core.js
new file mode 100644
index 000000000..38ca3eb33
--- /dev/null
+++ b/store/agents/data-studio/template/core.js
@@ -0,0 +1,850 @@
+// Original OpenHarness code. Shared unchanged by Node, the page and the bounded worker.
+globalThis.DataStudioCore = (() => {
+ "use strict";
+ const LIMITS = Object.freeze({
+ sourceBytes: 6 * 1024 * 1024,
+ rows: 100000,
+ cells: 1000000,
+ columns: 50,
+ tables: 8,
+ queries: 12,
+ resultRows: 10000,
+ resultBytes: 4 * 1024 * 1024,
+ totalResultBytes: 8 * 1024 * 1024,
+ cell: 4096,
+ });
+ const fail = (message) => {
+ throw new Error(message);
+ };
+ const bytes = (text) => new TextEncoder().encode(text).length;
+ const object = (value) =>
+ value && typeof value === "object" && !Array.isArray(value);
+ const own = (o, k) => Object.hasOwn(o, k);
+ const ident = (value) =>
+ typeof value === "string" &&
+ /^[A-Za-z][A-Za-z0-9_]{0,47}$/.test(value) &&
+ !/^(sqlite_|pragma_)/i.test(value);
+ const path = (value) =>
+ typeof value === "string" &&
+ /^[A-Za-z0-9][A-Za-z0-9._/-]{0,159}$/.test(value) &&
+ value.split("/").every((p) => p && !p.startsWith("."));
+ const list = (v, max, label) =>
+ Array.isArray(v) && v.length && v.length <= max
+ ? v
+ : fail(label + " needs 1–" + max + " entries.");
+ function unique(values, label) {
+ if (new Set(values).size !== values.length)
+ fail("Duplicate " + label + ".");
+ }
+ function exactKeys(value, allowed, label) {
+ if (!object(value)) fail(label + " must be an object.");
+ for (const k of Object.keys(value))
+ if (!allowed.includes(k)) fail("Unknown " + label + " field: " + k);
+ }
+ function text(value, label, max = 500) {
+ if (
+ typeof value !== "string" ||
+ !value.trim() ||
+ value.length > max ||
+ value.includes("\0")
+ )
+ fail(label + " must be nonempty text (maximum " + max + " characters).");
+ return value;
+ }
+ function date(value) {
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
+ const d = new Date(value + "T00:00:00Z");
+ return (
+ Number.isFinite(d.valueOf()) && d.toISOString().slice(0, 10) === value
+ );
+ }
+ // RFC-style quoted CSV; a blank physical record is rejected, never silently dropped.
+ function parseCSV(input) {
+ if (
+ typeof input !== "string" ||
+ bytes(input) > LIMITS.sourceBytes ||
+ input.includes("\0")
+ )
+ fail("CSV must be UTF-8 text without NUL, at most 6 MiB.");
+ input = input.replace(/^\uFEFF/, "");
+ const records = [];
+ let record = [],
+ field = "",
+ quoted = false,
+ closed = false,
+ cellCount = 0;
+ const cell = () => {
+ if (++cellCount > LIMITS.cells) fail("CSV exceeds 1,000,000 cells.");
+ if (field.length > LIMITS.cell) fail("CSV cell exceeds 4096 characters.");
+ record.push(field);
+ field = "";
+ closed = false;
+ if (record.length > LIMITS.columns) fail("CSV exceeds 50 columns.");
+ };
+ const row = () => {
+ cell();
+ records.push(record);
+ record = [];
+ if (records.length > LIMITS.rows + 1)
+ fail("CSV exceeds 100,000 records.");
+ };
+ for (let i = 0; i < input.length; i++) {
+ const c = input[i];
+ if (quoted) {
+ if (c === '"') {
+ if (input[i + 1] === '"') {
+ field += '"';
+ i++;
+ } else {
+ quoted = false;
+ closed = true;
+ }
+ } else field += c;
+ } else if (c === ",") cell();
+ else if (c === "\n" || c === "\r") {
+ if (c === "\r" && input[i + 1] === "\n") i++;
+ row();
+ } else if (c === '"') {
+ if (field || closed)
+ fail("Unexpected CSV quote at character " + (i + 1) + ".");
+ quoted = true;
+ } else {
+ if (closed) fail("Text after a closing CSV quote.");
+ field += c;
+ }
+ if (field.length > LIMITS.cell) fail("CSV cell exceeds 4096 characters.");
+ }
+ if (quoted) fail("Unclosed CSV quote.");
+ if (field || record.length || closed) row();
+ if (!records.length) fail("CSV is empty.");
+ const headers = records.shift();
+ if (headers.some((h) => !h || h.trim() !== h))
+ fail("CSV headers must be nonempty, without surrounding whitespace.");
+ unique(headers, "CSV header");
+ records.forEach((r, i) => {
+ if (r.length !== headers.length)
+ fail(
+ "CSV record " +
+ (i + 2) +
+ " has " +
+ r.length +
+ " fields; expected " +
+ headers.length +
+ ".",
+ );
+ if (r.every((v) => v === ""))
+ fail("Blank CSV record " + (i + 2) + "; remove it explicitly.");
+ });
+ return { headers, records };
+ }
+ function convert(raw, c, label) {
+ const value = c.trim ? raw.trim() : raw;
+ if ((c.missing ?? [""]).includes(value)) {
+ if (c.nullable === true) return null;
+ fail(label + " is missing but required.");
+ }
+ if (c.type === "text") return value;
+ if (c.type === "date") {
+ if (!date(value)) fail(label + " must be an ISO date (YYYY-MM-DD).");
+ return value;
+ }
+ if (c.type === "integer") {
+ if (
+ !/^-?(0|[1-9]\d*)$/.test(value) ||
+ !Number.isSafeInteger(Number(value))
+ )
+ fail(label + " must be a safe base-10 integer.");
+ return Number(value);
+ }
+ if (c.type === "decimal") {
+ const m = /^(-?)(0|[1-9]\d*)(?:\.(\d+))?$/.exec(value);
+ if (!m || (m[3]?.length ?? 0) > c.scale)
+ fail(
+ label +
+ " must be decimal text with at most " +
+ c.scale +
+ " fractional digits; no rounding is implicit.",
+ );
+ const n = BigInt((m[1] || "") + m[2] + (m[3] ?? "").padEnd(c.scale, "0"));
+ if (
+ n > BigInt(Number.MAX_SAFE_INTEGER) ||
+ n < BigInt(Number.MIN_SAFE_INTEGER)
+ )
+ fail(label + " exceeds exact integer storage.");
+ return Number(n);
+ }
+ if (c.type === "real") {
+ if (
+ !/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(value) ||
+ !Number.isFinite(Number(value)) ||
+ Math.abs(Number(value)) > Number.MAX_SAFE_INTEGER
+ )
+ fail(label + " must be a finite base-10 number.");
+ return Number(value);
+ }
+ fail("Unsupported column type: " + c.type);
+ }
+ function validateConfig(c) {
+ exactKeys(
+ c,
+ [
+ "spec",
+ "title",
+ "question",
+ "example",
+ "method",
+ "limitations",
+ "tables",
+ "relationships",
+ "parameters",
+ "queries",
+ "checks",
+ ],
+ "analysis",
+ );
+ if (c.spec !== 1 || typeof c.example !== "boolean")
+ fail(
+ "analysis.spec must be 1 and example must explicitly be true or false.",
+ );
+ text(c.title, "Title", 120);
+ text(c.question, "Question");
+ text(c.method, "Method", 2000);
+ if (!Array.isArray(c.limitations) || c.limitations.length > 12)
+ fail("Provide a limitations array.");
+ c.limitations.forEach((v) => text(v, "Limitation"));
+ list(c.tables, LIMITS.tables, "Tables");
+ unique(
+ c.tables.map((t) => String(t.id).toLowerCase()),
+ "table name",
+ );
+ unique(
+ c.tables.map((t) => t.file),
+ "source path",
+ );
+ for (const t of c.tables) {
+ exactKeys(t, ["id", "file", "label", "columns", "key"], "table");
+ if (!ident(t.id) || !path(t.file) || !t.file.endsWith(".csv"))
+ fail("Table needs a safe id and relative .csv file.");
+ text(t.label, "Table label");
+ list(t.columns, LIMITS.columns, "Columns");
+ unique(
+ t.columns.map((x) => String(x.name).toLowerCase()),
+ "column name",
+ );
+ unique(
+ t.columns.map((x) => x.source),
+ "mapped header",
+ );
+ for (const col of t.columns) {
+ exactKeys(
+ col,
+ [
+ "name",
+ "source",
+ "type",
+ "nullable",
+ "missing",
+ "trim",
+ "scale",
+ "unit",
+ ],
+ "column",
+ );
+ if (
+ !ident(col.name) ||
+ !["text", "integer", "decimal", "real", "date"].includes(col.type) ||
+ typeof col.nullable !== "boolean"
+ )
+ fail("Column needs a safe name, explicit type and nullable boolean.");
+ text(col.source, "Source header", 120);
+ if (
+ col.type === "decimal" &&
+ (!Number.isInteger(col.scale) || col.scale < 0 || col.scale > 6)
+ )
+ fail("Decimal scale must be 0–6.");
+ if (col.type !== "decimal" && col.scale !== undefined)
+ fail("Only decimal columns have a scale.");
+ if (col.trim !== undefined && typeof col.trim !== "boolean")
+ fail("trim must be boolean.");
+ if (
+ col.missing !== undefined &&
+ (!Array.isArray(col.missing) ||
+ col.missing.length > 10 ||
+ col.missing.some((v) => typeof v !== "string"))
+ )
+ fail("missing must be an array of strings.");
+ if (col.unit !== undefined) text(col.unit, "Unit", 80);
+ }
+ if (t.key !== undefined) {
+ list(t.key, 5, "Key columns");
+ unique(t.key, "key column");
+ if (
+ t.key.some(
+ (n) => !t.columns.some((col) => col.name === n && !col.nullable),
+ )
+ )
+ fail("Key columns must exist and be non-nullable.");
+ }
+ }
+ if (!Array.isArray(c.relationships) || c.relationships.length > 12)
+ fail("relationships must be an array of at most 12 joins.");
+ for (const r of c.relationships) {
+ exactKeys(r, ["from", "to", "allowMissing"], "relationship");
+ for (const side of ["from", "to"]) {
+ exactKeys(r[side], ["table", "column"], "relationship endpoint");
+ if (
+ !c.tables.some(
+ (t) =>
+ t.id === r[side].table &&
+ t.columns.some((x) => x.name === r[side].column),
+ )
+ )
+ fail("Unknown relationship endpoint.");
+ }
+ if (typeof r.allowMissing !== "boolean")
+ fail("Join allowMissing must be explicit.");
+ const target = c.tables.find((t) => t.id === r.to.table);
+ if (target.key?.length !== 1 || target.key[0] !== r.to.column)
+ fail("Join target must have a single-column unique key.");
+ const from = c.tables
+ .find((t) => t.id === r.from.table)
+ .columns.find((x) => x.name === r.from.column),
+ to = target.columns.find((x) => x.name === r.to.column);
+ if (from.type !== to.type || from.scale !== to.scale)
+ fail("Join key types/scales must match.");
+ }
+ if (!Array.isArray(c.parameters) || c.parameters.length > 12)
+ fail("parameters must be an array of at most 12 controls.");
+ unique(
+ c.parameters.map((p) => p.id),
+ "parameter",
+ );
+ for (const p of c.parameters) {
+ exactKeys(
+ p,
+ ["id", "label", "type", "default", "choices", "hidden"],
+ "parameter",
+ );
+ if (!ident(p.id) || !["text", "date", "integer", "real"].includes(p.type))
+ fail("Invalid parameter.");
+ text(p.label, "Parameter label");
+ if (p.hidden !== undefined && typeof p.hidden !== "boolean")
+ fail("hidden must be boolean.");
+ if (
+ p.choices !== undefined &&
+ (!Array.isArray(p.choices) ||
+ !p.choices.length ||
+ p.choices.length > 100 ||
+ p.choices.some((v) => typeof v !== "string"))
+ )
+ fail("choices must contain 1–100 text values.");
+ }
+ parameters(c, {});
+ list(c.queries, LIMITS.queries, "Queries");
+ unique(
+ c.queries.map((q) => q.id),
+ "query id",
+ );
+ unique(
+ c.queries.map((q) => q.file),
+ "query file",
+ );
+ for (const q of c.queries) {
+ exactKeys(
+ q,
+ [
+ "id",
+ "title",
+ "file",
+ "kind",
+ "x",
+ "y",
+ "formats",
+ "explanation",
+ "trace",
+ "sourceLinks",
+ ],
+ "query",
+ );
+ if (
+ !ident(q.id) ||
+ !path(q.file) ||
+ !q.file.endsWith(".sql") ||
+ !["table", "metric", "bar", "detail"].includes(q.kind)
+ )
+ fail("Query needs safe id, .sql file and supported kind.");
+ text(q.title, "Query title", 120);
+ text(q.explanation, "Query explanation", 1200);
+ if (q.kind === "bar" && (!ident(q.x) || !ident(q.y)))
+ fail("Bar query needs explicit x and y result columns.");
+ if (q.formats !== undefined) {
+ if (!object(q.formats)) fail("formats must be an object.");
+ for (const [key, f] of Object.entries(q.formats)) {
+ if (!ident(key)) fail("Invalid format column.");
+ exactKeys(
+ f,
+ ["style", "currency", "divisor", "digits", "unit"],
+ "format",
+ );
+ if (!["number", "currency", "percent", "text"].includes(f.style))
+ fail("Unsupported format.");
+ if (
+ f.divisor !== undefined &&
+ (!Number.isFinite(f.divisor) || f.divisor <= 0)
+ )
+ fail("Format divisor must be positive.");
+ if (
+ f.digits !== undefined &&
+ (!Number.isInteger(f.digits) || f.digits < 0 || f.digits > 6)
+ )
+ fail("Format digits must be 0–6.");
+ if (f.style === "currency" && !/^[A-Z]{3}$/.test(f.currency))
+ fail("Currency needs an explicit three-letter code.");
+ if (f.unit !== undefined) text(f.unit, "Format unit", 40);
+ }
+ }
+ if (q.trace) {
+ exactKeys(q.trace, ["query", "bindings"], "trace");
+ if (
+ !c.queries.some(
+ (x) => x.id === q.trace.query && x.kind === "detail",
+ ) ||
+ !object(q.trace.bindings) ||
+ !Object.keys(q.trace.bindings).length
+ )
+ fail("Trace needs a detail query and parameter-to-column bindings.");
+ for (const [p, col] of Object.entries(q.trace.bindings))
+ if (!c.parameters.some((x) => x.id === p && x.hidden) || !ident(col))
+ fail("Trace binding needs a hidden parameter and result column.");
+ }
+ if (q.sourceLinks) {
+ if (!object(q.sourceLinks))
+ fail("sourceLinks must map result columns to source table ids.");
+ for (const [col, t] of Object.entries(q.sourceLinks))
+ if (!ident(col) || !c.tables.some((x) => x.id === t))
+ fail("Invalid source link.");
+ }
+ }
+ if (!Array.isArray(c.checks) || c.checks.length > 20)
+ fail("checks must be an array of at most 20 reconciliation queries.");
+ unique(
+ c.checks.map((x) => x.id),
+ "check id",
+ );
+ for (const x of c.checks) {
+ exactKeys(x, ["id", "file", "description"], "check");
+ if (!ident(x.id) || !path(x.file) || !x.file.endsWith(".sql"))
+ fail("Invalid check id or path.");
+ text(x.description, "Check description");
+ }
+ return c;
+ }
+ function parameters(c, input) {
+ if (!object(input)) fail("Parameters must be an object.");
+ for (const k of Object.keys(input))
+ if (!c.parameters.some((p) => p.id === k))
+ fail("Unknown parameter: " + k);
+ return Object.fromEntries(
+ c.parameters.map((p) => {
+ const value = own(input, p.id) ? input[p.id] : p.default;
+ if (
+ p.type === "text" &&
+ (typeof value !== "string" || value.length > 500)
+ )
+ fail(p.label + " must be text.");
+ if (p.type === "date" && (typeof value !== "string" || !date(value)))
+ fail(p.label + " must be an ISO date.");
+ if (p.type === "integer" && !Number.isSafeInteger(value))
+ fail(p.label + " must be an integer.");
+ if (
+ p.type === "real" &&
+ (!Number.isFinite(value) || Math.abs(value) > Number.MAX_SAFE_INTEGER)
+ )
+ fail(p.label + " must be finite.");
+ if (p.choices && !p.choices.includes(value))
+ fail(p.label + " is outside its allowed choices.");
+ return [p.id, value];
+ }),
+ );
+ }
+ function prepare(bundle) {
+ exactKeys(bundle, ["config", "sources", "sql"], "bundle");
+ const c = validateConfig(bundle.config);
+ if (!object(bundle.sources) || !object(bundle.sql))
+ fail("Bundle needs source and SQL maps.");
+ const paths = c.tables.map((t) => t.file),
+ sqlPaths = [...c.queries, ...c.checks].map((q) => q.file);
+ unique([...paths, ...new Set(sqlPaths)], "project path");
+ if (
+ Object.keys(bundle.sources).some((k) => !paths.includes(k)) ||
+ Object.keys(bundle.sql).some((k) => !sqlPaths.includes(k))
+ )
+ fail("Bundle contains undeclared files.");
+ let total = 0,
+ rowCount = 0,
+ cells = 0;
+ const tables = [],
+ checks = [];
+ for (const t of c.tables) {
+ const csv = bundle.sources[t.file];
+ if (typeof csv !== "string") fail("Missing source " + t.file);
+ total += bytes(csv);
+ const parsed = parseCSV(csv);
+ if (
+ parsed.headers.length !== t.columns.length ||
+ parsed.headers.some((h) => !t.columns.some((col) => col.source === h))
+ )
+ fail(
+ t.file + ": source headers do not match explicit column mappings.",
+ );
+ cells += (parsed.records.length + 1) * parsed.headers.length;
+ if (cells > LIMITS.cells) fail("Project exceeds 1,000,000 source cells.");
+ const indices = t.columns.map((col) =>
+ parsed.headers.indexOf(col.source),
+ );
+ const rows = parsed.records.map((r, i) => [
+ i + 2,
+ ...t.columns.map((col, j) =>
+ convert(
+ r[indices[j]],
+ col,
+ t.file + " record " + (i + 2) + " / " + col.source,
+ ),
+ ),
+ ]);
+ rowCount += rows.length;
+ const keys = new Set();
+ if (t.key)
+ for (const r of rows) {
+ const key = JSON.stringify(
+ t.key.map(
+ (n) => r[t.columns.findIndex((col) => col.name === n) + 1],
+ ),
+ );
+ if (keys.has(key))
+ fail(t.file + ": duplicate key " + key + " at record " + r[0]);
+ keys.add(key);
+ }
+ tables.push({ ...t, rows, raw: parsed });
+ checks.push({
+ id: "source_" + t.id,
+ passed: true,
+ description:
+ t.file +
+ ": " +
+ rows.length +
+ " records, explicit types" +
+ (t.key ? ", unique " + t.key.join(" + ") : ""),
+ nulls: Object.fromEntries(
+ t.columns.map((col, j) => [
+ col.name,
+ rows.filter((r) => r[j + 1] === null).length,
+ ]),
+ ),
+ });
+ }
+ if (total > LIMITS.sourceBytes || rowCount > LIMITS.rows)
+ fail("Project exceeds 6 MiB of CSV or 100,000 total records.");
+ for (const r of c.relationships) {
+ const from = tables.find((t) => t.id === r.from.table),
+ to = tables.find((t) => t.id === r.to.table),
+ a = from.columns.findIndex((x) => x.name === r.from.column) + 1,
+ b = to.columns.findIndex((x) => x.name === r.to.column) + 1,
+ keys = new Set(to.rows.map((row) => row[b]));
+ let missing = 0;
+ for (const row of from.rows) if (!keys.has(row[a])) missing++;
+ if (missing && !r.allowMissing)
+ fail(
+ r.from.table +
+ "." +
+ r.from.column +
+ ": " +
+ missing +
+ " records have no matching " +
+ r.to.table +
+ "." +
+ r.to.column,
+ );
+ checks.push({
+ id: "join_" + checks.length,
+ passed: true,
+ description:
+ r.from.table +
+ " → " +
+ r.to.table +
+ ": many-to-one, " +
+ missing +
+ " unmatched" +
+ (r.allowMissing ? " (explicitly allowed)" : ""),
+ });
+ }
+ for (const q of [...c.queries, ...c.checks])
+ validateSQL(bundle.sql[q.file], c);
+ return { config: c, tables, checks, rowCount, sourceBytes: total };
+ }
+ // Small lexer only enforces the read-only/single-statement boundary; SQLite parses the SQL.
+ function validateSQL(sql, c) {
+ if (
+ typeof sql !== "string" ||
+ !sql.trim() ||
+ sql.length > 20000 ||
+ sql.includes("\0")
+ )
+ fail("SQL must be 1–20,000 characters.");
+ const tokens = [],
+ params = new Set();
+ let terminated = false;
+ for (let i = 0; i < sql.length; ) {
+ const ch = sql[i];
+ if (/\s/.test(ch)) {
+ i++;
+ continue;
+ }
+ if (sql.slice(i, i + 2) === "--") {
+ const end = sql.indexOf("\n", i + 2);
+ i = end < 0 ? sql.length : end;
+ continue;
+ }
+ if (sql.slice(i, i + 2) === "/*") {
+ const end = sql.indexOf("*/", i + 2);
+ if (end < 0) fail("Unclosed SQL comment.");
+ i = end + 2;
+ continue;
+ }
+ if (terminated) fail("Only one SELECT statement is allowed.");
+ if (ch === ";") {
+ terminated = true;
+ i++;
+ continue;
+ }
+ if (ch === "'" || ch === '"') {
+ const quote = ch;
+ let value = "",
+ closed = false;
+ i++;
+ while (i < sql.length) {
+ if (sql[i] === quote) {
+ if (sql[i + 1] === quote) {
+ value += quote;
+ i += 2;
+ } else {
+ i++;
+ closed = true;
+ break;
+ }
+ } else value += sql[i++];
+ }
+ if (!closed) fail("Unclosed SQL quoted value.");
+ if (quote === '"') tokens.push(value.toLowerCase());
+ continue;
+ }
+ if (ch === "`" || ch === "[" || ch === "?" || ch === "@" || ch === "$")
+ fail("Use standard quoted identifiers and named :parameters only.");
+ if (ch === ":") {
+ const match = /^[A-Za-z][A-Za-z0-9_]*/.exec(sql.slice(i + 1));
+ if (!match) fail("Invalid SQL parameter.");
+ if (!c.parameters.some((p) => p.id === match[0]))
+ fail("Undeclared SQL parameter: " + match[0]);
+ params.add(match[0]);
+ i += match[0].length + 1;
+ continue;
+ }
+ if (/[A-Za-z_]/.test(ch)) {
+ const token = /^[A-Za-z_][A-Za-z0-9_]*/
+ .exec(sql.slice(i))[0]
+ .toLowerCase();
+ tokens.push(token);
+ i += token.length;
+ } else i++;
+ }
+ if (!["select", "with"].includes(tokens[0]))
+ fail("Only read-only SELECT / WITH queries are allowed.");
+ const forbidden = new Set([
+ "insert",
+ "update",
+ "delete",
+ "drop",
+ "alter",
+ "create",
+ "replace",
+ "attach",
+ "detach",
+ "pragma",
+ "vacuum",
+ "reindex",
+ "analyze",
+ "begin",
+ "commit",
+ "rollback",
+ "savepoint",
+ "release",
+ "load_extension",
+ "writefile",
+ "readfile",
+ ]);
+ if (
+ tokens.some(
+ (t) =>
+ forbidden.has(t) ||
+ t.startsWith("pragma_") ||
+ t.startsWith("sqlite_db"),
+ )
+ )
+ fail("SQL contains a disabled operation.");
+ return [...params];
+ }
+ function scalar(v) {
+ if (typeof v === "bigint") {
+ if (
+ v > BigInt(Number.MAX_SAFE_INTEGER) ||
+ v < BigInt(Number.MIN_SAFE_INTEGER)
+ )
+ fail("Query integer exceeds JavaScript exact range.");
+ return Number(v);
+ }
+ if (
+ v === null ||
+ (typeof v === "string" && v.length <= LIMITS.cell) ||
+ (typeof v === "number" &&
+ Number.isFinite(v) &&
+ Math.abs(v) <= Number.MAX_SAFE_INTEGER)
+ )
+ return v;
+ fail("Unsupported or oversized SQL result value.");
+ }
+ function result(columns, rows, q) {
+ if (!columns.length || columns.length > LIMITS.columns)
+ fail("Query must return 1–50 named columns.");
+ unique(
+ columns.map((c) => c.toLowerCase()),
+ "query output column",
+ );
+ if (columns.some((c) => typeof c !== "string" || !c || c.length > 120))
+ fail("Invalid query output column.");
+ if (rows.length > LIMITS.resultRows)
+ fail("Query exceeds 10,000 result rows; narrow the query.");
+ rows = rows.map((row) => row.map(scalar));
+ if (bytes(JSON.stringify(rows)) > LIMITS.resultBytes)
+ fail("Query result exceeds 4 MiB.");
+ if (q.kind === "metric" && rows.length !== 1)
+ fail("Metric queries must return exactly one row.");
+ for (const key of [
+ ...Object.keys(q.formats ?? {}),
+ ...(q.kind === "bar" ? [q.x, q.y] : []),
+ ...Object.values(q.trace?.bindings ?? {}),
+ ...Object.keys(q.sourceLinks ?? {}),
+ ])
+ if (!columns.includes(key)) fail(q.id + ": missing output column " + key);
+ if (q.kind === "bar") {
+ if (rows.length > 100)
+ fail("Bar charts support at most 100 returned categories.");
+ const yi = columns.indexOf(q.y);
+ if (rows.some((r) => r[yi] !== null && typeof r[yi] !== "number"))
+ fail("Bar values must be numeric or null.");
+ }
+ return { id: q.id, columns, rows };
+ }
+ function stable(v) {
+ if (Array.isArray(v)) return "[" + v.map(stable).join(",") + "]";
+ if (object(v))
+ return (
+ "{" +
+ Object.keys(v)
+ .sort()
+ .map((k) => JSON.stringify(k) + ":" + stable(v[k]))
+ .join(",") +
+ "}"
+ );
+ return JSON.stringify(v);
+ }
+ function validateView(view, c) {
+ exactKeys(view, ["parameters", "notes", "selectedQuery"], "view");
+ parameters(c, view.parameters);
+ if (typeof view.notes !== "string" || view.notes.length > 4000)
+ fail("Review notes must be at most 4,000 characters.");
+ if (!c.queries.some((q) => q.id === view.selectedQuery))
+ fail("The selected query does not exist.");
+ return view;
+ }
+ function validateProject(p) {
+ exactKeys(
+ p,
+ ["format", "spec", "revision", "bundle", "view"],
+ "saved project",
+ );
+ if (
+ p.format !== "data-studio" ||
+ p.spec !== 1 ||
+ !/^[a-f0-9]{64}$/.test(p.revision)
+ )
+ fail("Not a version 1 Data Studio project.");
+ prepare(p.bundle);
+ validateView(p.view, p.bundle.config);
+ return p;
+ }
+ function verifyLinks(bundle, results) {
+ const prepared = prepare(bundle);
+ for (const result of results) {
+ const q = bundle.config.queries.find((q) => q.id === result.id);
+ for (const [col, id] of Object.entries(q.sourceLinks ?? {})) {
+ const t = prepared.tables.find((t) => t.id === id),
+ j = result.columns.indexOf(col);
+ for (const row of result.rows)
+ if (
+ row[j] !== null &&
+ (!Number.isInteger(row[j]) ||
+ row[j] < 2 ||
+ row[j] > t.rows.length + 1)
+ )
+ fail(q.id + ": source record does not exist: " + row[j]);
+ }
+ }
+ }
+ function format(value, f = {}) {
+ if (value === null) return "Missing";
+ if (typeof value !== "number" || f.style === "text") return String(value);
+ const n = value / (f.divisor ?? 1),
+ opts = {
+ maximumFractionDigits: f.digits ?? 2,
+ minimumFractionDigits: f.digits ?? 0,
+ };
+ if (f.style === "currency")
+ Object.assign(opts, { style: "currency", currency: f.currency });
+ if (f.style === "percent") opts.style = "percent";
+ return (
+ new Intl.NumberFormat("en-US", opts).format(n) +
+ (f.unit ? " " + f.unit : "")
+ );
+ }
+ function csv(columns, rows) {
+ const field = (v) => {
+ let s = v === null ? "" : String(v);
+ if (typeof v === "string" && /^[\s]*[=+\-@\t\r]/.test(s)) s = "'" + s;
+ return /[",\r\n]/.test(s) ? '"' + s.replaceAll('"', '""') + '"' : s;
+ };
+ return (
+ [columns, ...rows].map((r) => r.map(field).join(",")).join("\r\n") +
+ "\r\n"
+ );
+ }
+ return {
+ LIMITS,
+ parseCSV,
+ convert,
+ validateConfig,
+ prepare,
+ parameters,
+ validateSQL,
+ result,
+ stable,
+ format,
+ csv,
+ ident,
+ path,
+ date,
+ scalar,
+ validateView,
+ validateProject,
+ verifyLinks,
+ };
+})();
diff --git a/store/agents/data-studio/template/dashboard.mjs b/store/agents/data-studio/template/dashboard.mjs
index 9c1e15a16..e7cc69a54 100644
--- a/store/agents/data-studio/template/dashboard.mjs
+++ b/store/agents/data-studio/template/dashboard.mjs
@@ -1,204 +1,684 @@
-import { parseCSV, numericColumns, inferFields, summarize, exportCSV } from './data.mjs';
-
-const $ = id => document.getElementById(id);
-const colors = ['#2b6451', '#88a965', '#c29a5c', '#829ea9', '#b57c75', '#817da3', '#4a8e89', '#9a8255'];
-const NS = 'http://www.w3.org/2000/svg';
-let table, fields, enabled, groups, periods, snapshot, mode = 'trend', selected = null;
-const title = value => value.replaceAll('_', ' ').replace(/^\w/, c => c.toUpperCase());
-// Units belong to the data, never guessed from a word such as "revenue".
-const currency = () => fields.metric.match(/_(usd|eur|gbp|jpy|vnd)$/i)?.[1].toUpperCase();
-const format = (value, compact = false) => new Intl.NumberFormat('en-US', {
- ...(currency() ? { style: 'currency', currency: currency() } : {}),
- maximumFractionDigits: compact ? 1 : 2, ...(compact ? { notation: 'compact' } : {})
-}).format(value);
-const color = group => colors[groups.indexOf(group) % colors.length];
-function element(tag, attributes = {}, text, svg = false) {
- const node = svg ? document.createElementNS(NS, tag) : document.createElement(tag);
- for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value);
- if (text !== undefined) node.textContent = text;
- return node;
+const C = globalThis.DataStudioCore,
+ $ = (s) => document.querySelector(s),
+ clone = (v) => structuredClone(v);
+const bytes = (s) => new TextEncoder().encode(s),
+ hash = async (v) =>
+ Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", v)), (b) =>
+ b.toString(16).padStart(2, "0"),
+ ).join("");
+const label = (s) => s.replaceAll("_", " "),
+ el = (tag, text, cls) => {
+ const e = document.createElement(tag);
+ if (text !== undefined) e.textContent = text;
+ if (cls) e.className = cls;
+ return e;
+ };
+let current = null,
+ selected = "",
+ pageIndex = 0,
+ sourceId = null,
+ worker = null,
+ cancelCalculation = null,
+ busy = false,
+ assetsPromise;
+const status = (text, error = false) => {
+ $("#status").textContent = text;
+ $("#status").classList.toggle("error", error);
+};
+const download = (name, data, type = "application/json") => {
+ const url = URL.createObjectURL(new Blob([data], { type })),
+ a = el("a");
+ a.href = url;
+ a.download = name;
+ document.body.append(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 30000);
+};
+async function get(url, binary = false) {
+ const response = await fetch(url, { cache: "no-store" });
+ if (!response.ok)
+ throw new Error(
+ url +
+ ": " +
+ response.status +
+ " — run the build helper if this is a fresh workspace.",
+ );
+ const data = await response.arrayBuffer();
+ if (data.byteLength > 16 * 1024 * 1024)
+ throw new Error("File exceeds 16 MiB.");
+ return binary ? data : new TextDecoder("utf-8", { fatal: true }).decode(data);
+}
+async function assets() {
+ if (!assetsPromise)
+ assetsPromise = (async () => {
+ const [vendor, core, code, wasm, pins] = await Promise.all([
+ get("vendor/sqlite3.js"),
+ get("core.js"),
+ get("worker.js"),
+ get("vendor/sqlite3.wasm", true),
+ get("vendor/checksums.json"),
+ ]);
+ const expected = JSON.parse(pins);
+ if (
+ (await hash(bytes(vendor))) !== expected["sqlite3.js"] ||
+ (await hash(wasm)) !== expected["sqlite3.wasm"]
+ )
+ throw new Error("SQLite runtime checksum mismatch.");
+ return {
+ code:
+ "globalThis.sqlite3ApiConfig={disable:{vfs:{opfs:true,'opfs-sahpool':true,'opfs-wl':true,kvvfs:true}}};\n" +
+ vendor +
+ "\n" +
+ core +
+ "\n" +
+ code,
+ wasm,
+ };
+ })().catch((e) => {
+ assetsPromise = null;
+ throw e;
+ });
+ return assetsPromise;
}
-function options(id, values, chosen) {
- $(id).replaceChildren(...values.map(value => element('option', { value }, value)));
- $(id).value = chosen;
+function setBusy(value) {
+ busy = value;
+ document.body.dataset.busy = String(value);
+ if (!value) $("#cancel-run").hidden = true;
+ for (const id of [
+ "save-project",
+ "export-db",
+ "export-report",
+ "export-csv",
+ "export-json",
+ "run-sql",
+ "download-source",
+ ])
+ $("#" + id).disabled = value || !current;
+ $("#filters")
+ .querySelectorAll("button")
+ .forEach((b) => (b.disabled = value));
}
-function configure() {
- groups = [...new Set(table.rows.map(row => row[fields.group]))].sort((a,b) => a.localeCompare(b));
- periods = [...new Set(table.rows.map(row => row[fields.period]))].sort((a,b) => a.localeCompare(b, undefined, { numeric: true }));
- enabled = new Set(groups); selected = null;
- options('start', periods, periods[0]); options('end', periods, periods.at(-1));
- options('period-field', table.headers, fields.period); options('group-field', table.headers, fields.group);
- options('metric-field', numericColumns(table), fields.metric);
- $('group-label').textContent = title(fields.group);
- $('regions').replaceChildren(...groups.map(group => {
- const button = element('button', { class: 'region', 'aria-pressed': 'true', 'aria-label': group });
- const dot = element('i', { class: 'dot', 'aria-hidden': 'true' }); dot.style.background = color(group);
- button.append(dot, element('span', {}, group), element('span', { class: 'count' }, table.rows.filter(row => row[fields.group] === group).length), element('span', { class: 'check', 'aria-hidden': 'true' }, '✓'));
- button.onclick = () => {
- enabled.has(group) ? enabled.delete(group) : enabled.add(group);
- button.setAttribute('aria-pressed', String(enabled.has(group)));
- button.querySelector('.check').textContent = enabled.has(group) ? '✓' : '';
- selected = null; render();
+async function calculate(bundle, parameters) {
+ const a = await assets();
+ return new Promise((resolve, reject) => {
+ const url = URL.createObjectURL(
+ new Blob([a.code], { type: "text/javascript" }),
+ );
+ worker = new Worker(url);
+ URL.revokeObjectURL(url);
+ const finish = (error, value) => {
+ clearTimeout(timer);
+ worker?.terminate();
+ worker = null;
+ cancelCalculation = null;
+ error ? reject(error) : resolve(value);
};
- return button;
- }));
- render();
+ const timer = setTimeout(
+ () =>
+ finish(
+ new Error(
+ "20-second query budget exceeded; narrow the data or query.",
+ ),
+ ),
+ 20000,
+ );
+ cancelCalculation = () => finish(new Error("Query cancelled."));
+ $("#cancel-run").hidden = false;
+ worker.onerror = (event) =>
+ finish(new Error(event.message || "SQLite worker failed."));
+ worker.onmessage = ({ data }) =>
+ data.error ? finish(new Error(data.error)) : finish(null, data);
+ worker.postMessage({ bundle, parameters, wasm: a.wasm });
+ });
}
-function render() {
- snapshot = summarize(table, fields, enabled, { start: $('start').value, end: $('end').value });
- const { total, rows, ranked, growth } = snapshot;
- const metric = title(fields.metric);
- $('headline').textContent = metric + ', in perspective.';
- $('takeaway').textContent = rows.length && ranked.length
- ? ranked[0].name + ' leads your selection with ' + format(ranked[0].value) + '. Explore what changes across ' + snapshot.periods.length + ' periods.'
- : 'Choose a group to start exploring.';
- $('total-label').textContent = 'Total ' + fields.metric.replaceAll('_',' ');
- $('total').textContent = rows.length ? format(total) : '—';
- $('row-count').textContent = rows.length + ' of ' + table.rows.length + ' rows selected';
- $('growth').textContent = growth === null || !rows.length ? '—' : (growth > 0 ? '+' : '') + (growth * 100).toFixed(1) + '%';
- $('growth-detail').textContent = snapshot.periods.length < 2 ? 'Choose more than one period' : snapshot.periods[0] + ' → ' + snapshot.periods.at(-1);
- $('leader').textContent = rows.length ? ranked[0]?.name || '—' : '—';
- $('leader-detail').textContent = rows.length ? format(ranked[0]?.value || 0) + ' in this selection' : 'No groups selected';
- $('chart-title').textContent = metric + ' over time';
- $('chart-subtitle').textContent = (currency() ? currency() + ' · ' : '') + title(fields.period) + ' / ' + title(fields.group);
- $('export').disabled = !rows.length;
- $('tooltip').hidden = true;
- drawChart(); drawRanking(); drawTable();
- $('legend').replaceChildren(...snapshot.series.map(series => {
- const item = element('span'), dot = element('i', { class: 'dot', 'aria-hidden': 'true' });
- dot.style.background = color(series.name); item.append(dot, document.createTextNode(series.name)); return item;
- }));
+$("#cancel-run").onclick = () => cancelCalculation?.();
+async function commit(bundle, view, { baseline = null } = {}) {
+ if (busy) return false;
+ setBusy(true);
+ status("Checking source types, joins and saved queries…");
+ try {
+ C.validateConfig(bundle.config);
+ C.validateView(view, bundle.config);
+ const result = await calculate(bundle, view.parameters),
+ revision = await hash(bytes(C.stable(bundle)));
+ C.verifyLinks(bundle, result.report.results);
+ if (
+ baseline &&
+ (baseline.revision !== revision ||
+ C.stable(baseline.parameters) !== C.stable(result.report.parameters) ||
+ C.stable(baseline.results) !== C.stable(result.report.results))
+ )
+ throw new Error(
+ "Browser results disagree with the saved native build. Rebuild and investigate before using them.",
+ );
+ result.report.revision = revision;
+ current = {
+ bundle: clone(bundle),
+ view: { ...clone(view), parameters: result.report.parameters },
+ ...result,
+ };
+ selected = view.selectedQuery;
+ pageIndex = 0;
+ render();
+ status(
+ (bundle.config.example ? "Synthetic example · " : "") +
+ result.report.records +
+ " source records · " +
+ result.report.checks.length +
+ " checks passed" +
+ (baseline
+ ? " · browser and saved SQLite results agree."
+ : " · analysis recalculated. Save project to keep changes."),
+ );
+ document.body.dataset.ready = "true";
+ return true;
+ } catch (error) {
+ status(
+ error.message +
+ (current
+ ? " Last good analysis is still shown; the attempted change was not applied."
+ : ""),
+ true,
+ );
+ return false;
+ } finally {
+ setBusy(false);
+ }
+}
+function viewFromControls() {
+ const view = clone(current.view);
+ for (const p of current.bundle.config.parameters.filter((p) => !p.hidden)) {
+ const value = $("#param-" + p.id).value;
+ view.parameters[p.id] = ["integer", "real"].includes(p.type)
+ ? Number(value)
+ : value;
+ }
+ view.notes = $("#notes").value;
+ view.selectedQuery = selected;
+ return view;
}
-function drawChart() {
- const plot = $('plot'); plot.replaceChildren();
- if (!snapshot.rows.length) {
- const empty = element('div', { class: 'empty' });
- empty.append(element('strong', {}, 'A fresh perspective starts with a selection.'), document.createTextNode('Choose a group, or reset your filters.'));
- plot.append(empty); return;
+function render() {
+ const c = current.bundle.config,
+ r = current.report;
+ $("#title").textContent = c.title;
+ document.title = c.title + " · Data Studio";
+ $("#question").textContent = c.question;
+ $("#example").textContent = c.example
+ ? "SYNTHETIC EXAMPLE DATA"
+ : "USER-SUPPLIED DATA";
+ $("#method").textContent = c.method;
+ $("#limitations").replaceChildren(...c.limitations.map((v) => el("li", v)));
+ $("#notes").value = current.view.notes;
+ $("#revision").textContent = "REVISION " + r.revision.slice(0, 16);
+ $("#revision").title = r.revision;
+ $("#engine").textContent = r.engine;
+ $("#check-count").textContent = r.checks.length + " passed";
+ $("#check-summary").textContent =
+ c.tables.length + " files · " + r.records + " records";
+ const sources = $("#sources");
+ sources.replaceChildren();
+ for (const t of c.tables) {
+ const b = el("button", t.file.split("/").pop(), "source-button");
+ b.dataset.source = t.id;
+ b.append(
+ el(
+ "small",
+ t.columns.length +
+ " typed columns" +
+ (t.key ? " · key: " + t.key.join(" + ") : ""),
+ ),
+ );
+ b.onclick = () => showSource(t.id);
+ sources.append(b);
}
- const W = 900, H = 310, L = 70, R = 30, T = 30, B = 42, pw = W - L - R, ph = H - T - B;
- const values = snapshot.series.flatMap(series => series.values.map(point => point.value));
- let min = Math.min(0, ...values), max = Math.max(0, ...values);
- if (min === max) max = min + 1;
- const extent = max - min; if (min < 0) min -= extent * .08; if (max > 0) max += extent * .12;
- const y = value => T + ph * (max - value) / (max - min);
- const step = pw / Math.max(1, snapshot.periods.length);
- const x = index => L + step * (index + .5);
- const svg = element('svg', { viewBox: '0 0 '+W+' '+H, role: 'img', 'aria-label': fields.metric + ' by ' + fields.period + ' and ' + fields.group }, undefined, true);
- for (let i = 0; i <= 4; i++) {
- const value = min + (max - min) * i / 4, yy = y(value);
- svg.append(element('line', { x1: L, x2: W-R, y1: yy, y2: yy, stroke: '#e8ede5', 'stroke-dasharray': '3 5' }, undefined, true));
- svg.append(element('text', { x: L-12, y: yy+4, 'text-anchor': 'end' }, format(value,true), true));
+ const nav = $("#queries");
+ nav.replaceChildren();
+ for (const q of c.queries.filter((q) => q.kind !== "metric")) {
+ const b = el("button", q.title, "query-button");
+ b.dataset.query = q.id;
+ b.setAttribute("aria-pressed", String(selected === q.id));
+ b.onclick = () => {
+ if (busy) return;
+ selected = q.id;
+ current.view.selectedQuery = selected;
+ pageIndex = 0;
+ renderQuery();
+ };
+ nav.append(b);
}
- svg.append(element('line', { x1:L, x2:W-R, y1:y(0), y2:y(0), stroke:'#dce4d8' }, undefined, true));
- const stride = Math.max(1, Math.ceil(snapshot.periods.length / 8));
- snapshot.periods.forEach((period,i) => {
- if (i % stride === 0 || i === snapshot.periods.length-1) svg.append(element('text', {x:x(i), y:H-14, 'text-anchor':'middle'}, period.length > 14 ? period.slice(0,12)+'…' : period, true));
- });
- snapshot.series.forEach((series, si) => {
- if (mode === 'trend') {
- const points = series.values.map((point,i) => x(i)+','+y(point.value)).join(' ');
- svg.append(element('polyline', { points, fill:'none', stroke:color(series.name), 'stroke-width':2.5, 'stroke-linejoin':'round', 'stroke-linecap':'round' }, undefined, true));
+ const filters = $("#filters");
+ filters.replaceChildren();
+ for (const p of c.parameters.filter((p) => !p.hidden)) {
+ const l = el("label", p.label),
+ input = el(p.choices ? "select" : "input");
+ input.id = "param-" + p.id;
+ if (p.choices)
+ for (const choice of p.choices) {
+ const o = el("option", choice || "All");
+ o.value = choice;
+ input.append(o);
+ }
+ else {
+ input.type =
+ p.type === "date"
+ ? "date"
+ : ["integer", "real"].includes(p.type)
+ ? "number"
+ : "text";
+ if (p.type === "real") input.step = "any";
}
- series.values.forEach((point, i) => {
- const label = series.name+' · '+point.period+' · '+format(point.value);
- let mark;
- if (mode === 'trend') mark = element('circle', {cx:x(i), cy:y(point.value), r:4, fill:'white', stroke:color(series.name), 'stroke-width':2}, undefined, true);
+ input.value = String(current.view.parameters[p.id]);
+ input.oninput = () =>
+ status(
+ "Controls changed, but the displayed result still uses the last applied controls. Apply controls to recalculate.",
+ );
+ l.append(input);
+ filters.append(l);
+ }
+ const run = el("button", "Apply controls", "primary");
+ run.type = "button";
+ run.id = "apply-controls";
+ run.onclick = () => {
+ if (current && !busy) commit(current.bundle, viewFromControls());
+ };
+ filters.append(run);
+ const reset = el("button", "Reset");
+ reset.type = "button";
+ reset.onclick = () => {
+ if (!busy)
+ commit(current.bundle, {
+ ...clone(current.view),
+ notes: $("#notes").value,
+ parameters: C.parameters(c, {}),
+ });
+ };
+ filters.append(reset);
+ const metrics = $("#metrics");
+ metrics.replaceChildren();
+ for (const q of c.queries.filter((q) => q.kind === "metric")) {
+ const result = r.results.find((x) => x.id === q.id);
+ result.columns.forEach((col, i) => {
+ const card = el("div", undefined, "metric");
+ card.dataset.metric = col;
+ card.append(
+ el("div", label(col), "label"),
+ el("strong", C.format(result.rows[0][i], q.formats?.[col])),
+ el("small", q.title),
+ );
+ metrics.append(card);
+ });
+ }
+ renderQuery();
+ $("#checks").replaceChildren(
+ ...r.checks.map((check) => {
+ const item = el("section");
+ item.append(el("p", "✓ " + check.description));
+ if (check.nulls)
+ item.append(
+ el("pre", JSON.stringify({ missingValues: check.nulls }, null, 2)),
+ );
+ return item;
+ }),
+ );
+}
+function renderQuery() {
+ const q =
+ current.bundle.config.queries.find((q) => q.id === selected) ??
+ current.bundle.config.queries[0],
+ r = current.report.results.find((r) => r.id === q.id);
+ selected = q.id;
+ current.view.selectedQuery = selected;
+ $("#query-title").textContent = q.title;
+ $("#query-explanation").textContent = q.explanation;
+ $("#sql").value = current.bundle.sql[q.file];
+ $("#result-table").dataset.query = q.id;
+ $("#queries")
+ .querySelectorAll("button")
+ .forEach((b) =>
+ b.setAttribute("aria-pressed", String(b.dataset.query === selected)),
+ );
+ const chart = $("#chart"),
+ axis = $("#axis");
+ chart.replaceChildren();
+ axis.replaceChildren();
+ chart.hidden = q.kind !== "bar";
+ axis.hidden = q.kind !== "bar" || !r.rows.length;
+ if (q.kind === "bar" && r.rows.length) {
+ const xi = r.columns.indexOf(q.x),
+ yi = r.columns.indexOf(q.y),
+ values = r.rows.map((row) => row[yi]).filter((v) => v !== null),
+ min = Math.min(0, ...values),
+ max = Math.max(q.formats?.[q.y]?.style === "percent" ? 1 : 0, ...values),
+ range = max - min || 1,
+ zero = ((0 - min) / range) * 100;
+ for (const row of r.rows) {
+ const value = row[yi],
+ b = el(q.trace ? "button" : "div", undefined, "bar-row");
+ b.dataset.category = String(row[xi]);
+ b.setAttribute(
+ "aria-label",
+ String(row[xi]) + ": " + C.format(value, q.formats?.[q.y]),
+ );
+ b.append(el("span", String(row[xi]), "bar-label"));
+ const track = el("span", undefined, "bar-track"),
+ line = el("span", undefined, "zero");
+ line.style.left = zero + "%";
+ track.append(line);
+ if (value === null) track.append(el("span", "Missing", "null-bar"));
else {
- const barWidth = Math.max(1, step * .64 / snapshot.series.length);
- mark = element('rect', {x:x(i)-step*.32+si*barWidth, y:Math.min(y(0),y(point.value)), width:Math.max(.5,barWidth-2), height:Math.max(1,Math.abs(y(point.value)-y(0))), rx:2, fill:color(series.name)}, undefined, true);
+ const bar = el(
+ "span",
+ undefined,
+ "bar" + (value < 0 ? " negative" : ""),
+ );
+ bar.style.left = ((Math.min(0, value) - min) / range) * 100 + "%";
+ bar.style.width = (Math.abs(value) / range) * 100 + "%";
+ track.append(bar);
}
- mark.setAttribute('class','point'); mark.setAttribute('tabindex','0'); mark.setAttribute('role','button'); mark.setAttribute('aria-label',label);
- const show = event => {
- const tip = $('tooltip'); tip.replaceChildren(element('span',{},series.name+' · '+point.period),element('strong',{},format(point.value)));
- tip.hidden = false;
- const rect = mark.getBoundingClientRect();
- const px = Number.isFinite(event.clientX) ? event.clientX : rect.x + rect.width/2;
- const py = Number.isFinite(event.clientY) ? event.clientY : rect.y;
- tip.style.left = Math.max(8,Math.min(innerWidth-tip.offsetWidth-8, px+14))+'px';
- tip.style.top = Math.max(8,Math.min(innerHeight-tip.offsetHeight-8,py-55))+'px';
- };
- mark.onpointerenter = show; mark.onfocus = show;
- mark.onpointerleave = () => $('tooltip').hidden = true;
- mark.onblur = () => $('tooltip').hidden = true;
- mark.onclick = event => { selected = { group: series.name, period: point.period }; drawTable(); show(event); };
- mark.onkeydown = event => { if (event.key==='Enter' || event.key===' ') { event.preventDefault(); mark.onclick(event); } if(event.key==='Escape') $('tooltip').hidden=true; };
- svg.append(mark);
+ b.append(
+ track,
+ el("span", C.format(value, q.formats?.[q.y]), "bar-value"),
+ );
+ if (q.trace) b.onclick = () => trace(q, row, r.columns);
+ chart.append(b);
+ }
+ axis.append(
+ el("span", C.format(min, q.formats?.[q.y])),
+ el("span", C.format(max, q.formats?.[q.y])),
+ );
+ }
+ const table = $("#result-table"),
+ head = el("thead"),
+ tr = el("tr");
+ r.columns.forEach((col) => tr.append(el("th", label(col))));
+ head.append(tr);
+ const body = el("tbody"),
+ start = pageIndex * 50;
+ for (const row of r.rows.slice(start, start + 50)) {
+ const tr = el("tr");
+ row.forEach((v, i) => {
+ const col = r.columns[i],
+ td = el(
+ "td",
+ undefined,
+ v === null ? "missing" : typeof v === "number" ? "numeric" : "",
+ );
+ if (q.sourceLinks?.[col] && v !== null) {
+ const b = el("button", "record " + v + " ↗", "source-link");
+ b.dataset.record = String(v);
+ b.dataset.table = q.sourceLinks[col];
+ b.onclick = () => showSource(q.sourceLinks[col], v);
+ td.append(b);
+ } else td.textContent = C.format(v, q.formats?.[col]);
+ tr.append(td);
});
- });
- plot.append(svg);
-}
-function drawRanking() {
- const maximum = Math.max(1,...snapshot.ranked.map(row=>Math.abs(row.value)));
- $('ranking').replaceChildren(...snapshot.ranked.map(row => {
- const container = element('div',{class:'ranking-row'}), label = element('div',{class:'ranking-label'}), track=element('div',{class:'track'}), bar=element('i');
- label.append(element('span',{},row.name),element('span',{},format(row.value)));
- bar.style.width=(Math.abs(row.value)/maximum*100)+'%'; bar.style.background=color(row.name); track.append(bar); container.append(label,track); return container;
- }));
- if (!snapshot.rows.length) $('ranking').textContent='No groups selected.';
-}
-function drawTable() {
- const columns = [...new Set([fields.period,fields.group,fields.metric])];
- const head = element('tr'); head.append(...columns.map(key=>element('th',{scope:'col'},title(key))));
- $('table').querySelector('thead').replaceChildren(head);
- const rows = selected ? snapshot.rows.filter(row=>row[fields.group]===selected.group && row[fields.period]===selected.period) : snapshot.rows;
- $('table').querySelector('tbody').replaceChildren(...rows.slice(0,100).map(row=>{
- const tr = element('tr',selected?{class:'selected'}:{});
- tr.append(...columns.map(key=>element('td',{},key===fields.metric?format(Number(row[key])):row[key]))); return tr;
- }));
- $('table-note').textContent = selected ? 'Inspecting '+selected.group+' · '+selected.period+' — change a filter to clear' : (rows.length>100?'First 100 of '+rows.length+' rows · export for all rows':rows.length+' source rows · values are aggregated in the chart');
+ if (q.trace) {
+ const td = el("td"),
+ b = el("button", "Trace rows ↗", "source-link");
+ b.onclick = () => trace(q, row, r.columns);
+ td.append(b);
+ tr.append(td);
+ }
+ body.append(tr);
+ }
+ if (q.trace) tr.append(el("th", "Evidence"));
+ table.replaceChildren(head, body);
+ $("#empty").hidden = Boolean(r.rows.length);
+ $("#row-count").textContent = r.rows.length
+ ? start +
+ 1 +
+ "–" +
+ Math.min(start + 50, r.rows.length) +
+ " of " +
+ r.rows.length +
+ " exact result rows"
+ : "0 matching result rows";
+ $("#previous").disabled = pageIndex === 0;
+ $("#next").disabled = start + 50 >= r.rows.length;
+ $("#row-count").dataset.count = String(r.rows.length);
+ $("#reset-trace").hidden = !current.bundle.config.parameters.some(
+ (p) => p.hidden && current.view.parameters[p.id] !== p.default,
+ );
}
-function failure(error) {
- $('error-message').textContent=error.message;
- $('error').hidden=false; $('dashboard').hidden=true; $('loading').hidden=true; $('export').disabled=true;
+async function trace(q, row, columns) {
+ if (busy) return;
+ const view = viewFromControls();
+ for (const [p, col] of Object.entries(q.trace.bindings))
+ view.parameters[p] = row[columns.indexOf(col)];
+ view.selectedQuery = q.trace.query;
+ await commit(current.bundle, view);
}
-function accept(text,name) {
- try {
- if(text.length>5*1024*1024) throw new Error('Choose a CSV smaller than 5 MB for this interactive view.');
- const parsed = parseCSV(text);
- if(!parsed.rows.length) throw new Error('The header is present, but there are no data rows yet.');
- const inferred = inferFields(parsed);
- table=parsed; fields=inferred;
- $('source').textContent=name; $('error').hidden=true; $('loading').hidden=true; $('dashboard').hidden=false;
- configure();
- } catch(error) { failure(error); }
+function showSource(id, record) {
+ sourceId = id;
+ const t = current.bundle.config.tables.find((t) => t.id === id),
+ parsed = C.parseCSV(current.bundle.sources[t.file]);
+ $("#source-title").textContent = t.label;
+ const schema = $("#schema");
+ schema.replaceChildren();
+ const ul = el("ul");
+ for (const col of t.columns)
+ ul.append(
+ el(
+ "li",
+ col.source +
+ " → " +
+ col.name +
+ " · " +
+ col.type +
+ (col.type === "decimal"
+ ? " × 10^" + col.scale + " integer storage"
+ : "") +
+ (col.unit ? " · " + col.unit : "") +
+ " · " +
+ (col.nullable ? "missing allowed" : "required") +
+ (col.trim ? " · trim whitespace" : ""),
+ ),
+ );
+ const rules = el("details");
+ rules.open = !record;
+ rules.append(
+ el(
+ "summary",
+ "Import rules · " + t.columns.length + " explicitly typed columns",
+ ),
+ ul,
+ );
+ schema.append(rules);
+ const table = $("#raw-record"),
+ head = el("thead"),
+ tr = el("tr");
+ (record
+ ? ["Source field", "Original value"]
+ : ["CSV record", ...parsed.headers]
+ ).forEach((h) => tr.append(el("th", h)));
+ head.append(tr);
+ const body = el("tbody");
+ const rows = record
+ ? [
+ ["CSV record", record],
+ ...parsed.headers.map((h, i) => [h, parsed.records[record - 2][i]]),
+ ]
+ : parsed.records.slice(0, 20).map((r, i) => [i + 2, ...r]);
+ for (const row of rows) {
+ const tr = el("tr");
+ row.forEach((v) => tr.append(el("td", v)));
+ body.append(tr);
+ }
+ table.replaceChildren(head, body);
+ $("#source-caption").textContent = record
+ ? "Original CSV record " +
+ record +
+ ". Header is record 1; a quoted multiline field is still one record."
+ : "First " +
+ rows.length +
+ " of " +
+ parsed.records.length +
+ " original records. Download retains all source text. Raw CSV may contain spreadsheet formulas; do not open untrusted raw data with formula evaluation enabled.";
+ if (!$("#source-dialog").open) $("#source-dialog").showModal();
}
-async function load() {
- $('loading').hidden=false; $('dashboard').hidden=true; $('error').hidden=true;
+$("#filters").onkeydown = (e) => {
+ if (e.key === "Enter" && e.target.tagName !== "BUTTON") {
+ e.preventDefault();
+ if (current && !busy) commit(current.bundle, viewFromControls());
+ }
+};
+$("#run-sql").onclick = async () => {
+ if (!current || busy) return;
+ const bundle = clone(current.bundle),
+ q = bundle.config.queries.find((q) => q.id === selected);
+ bundle.sql[q.file] = $("#sql").value;
+ if (
+ bundle.sql[q.file] !== current.bundle.sql[q.file] &&
+ !q.explanation.startsWith("Edited query.")
+ )
+ q.explanation =
+ "Edited query. Review the SQL before interpreting this result. Original explanation: " +
+ q.explanation;
+ await commit(bundle, viewFromControls());
+};
+$("#sql").oninput = () =>
+ status(
+ "SQL draft changed. The displayed result and exports still use the last successful query. Run revised query to apply it.",
+ );
+$("#reset-trace").onclick = () => {
+ if (!current || busy) return;
+ const view = viewFromControls();
+ for (const p of current.bundle.config.parameters.filter((p) => p.hidden))
+ view.parameters[p.id] = p.default;
+ commit(current.bundle, view);
+};
+$("#previous").onclick = () => {
+ if (pageIndex) {
+ pageIndex--;
+ renderQuery();
+ }
+};
+$("#next").onclick = () => {
+ pageIndex++;
+ renderQuery();
+};
+$("#close-source").onclick = () => $("#source-dialog").close();
+$("#close-checks").onclick = () => $("#checks-dialog").close();
+$("#show-checks").onclick = () => current && $("#checks-dialog").showModal();
+$("#replace-source").onchange = async (event) => {
+ const file = event.target.files[0];
+ event.target.value = "";
+ if (!file || !current || busy) return;
+ if (file.size > C.LIMITS.sourceBytes) {
+ status("Replacement exceeds 6 MiB; last good analysis is unchanged.", true);
+ return;
+ }
+ setBusy(true);
+ status("Reading replacement CSV…");
try {
- const response=await fetch('data.csv');
- if(!response.ok) throw new Error('data.csv returned HTTP '+response.status+'. Add it to this workspace or open a CSV.');
- accept(await response.text(),'data.csv');
- } catch(error) { failure(error); }
-}
-$('open').onclick=()=>$('upload').click();
-$('upload').onchange=async event=>{
- const file=event.target.files[0]; if(!file)return;
- if(file.size>5*1024*1024) failure(new Error('Choose a CSV smaller than 5 MB.'));
- else accept(await file.text(),file.name);
- event.target.value='';
+ const bundle = clone(current.bundle),
+ t = bundle.config.tables.find((t) => t.id === sourceId);
+ bundle.sources[t.file] = new TextDecoder("utf-8", { fatal: true }).decode(
+ await file.arrayBuffer(),
+ );
+ const view = viewFromControls();
+ setBusy(false);
+ const ok = await commit(bundle, view);
+ if (ok) showSource(sourceId);
+ } catch (e) {
+ setBusy(false);
+ status(e.message + " Last good analysis is unchanged.", true);
+ }
};
-$('retry').onclick=load;
-$('reset').onclick=()=>configure();
-for(const id of ['start','end']) $(id).onchange=()=>{
- if(periods.indexOf($('start').value)>periods.indexOf($('end').value)) $(id==='start'?'end':'start').value=$(id).value;
- selected=null; render();
+$("#download-source").onclick = () => {
+ const t = current.bundle.config.tables.find((t) => t.id === sourceId);
+ download(t.file.split("/").pop(), current.bundle.sources[t.file], "text/csv");
};
-for(const [id,key] of [['period-field','period'],['group-field','group'],['metric-field','metric']]) $(id).onchange=()=>{
- const value=$(id).value;
- if((key==='period' && value===fields.group)||(key==='group' && value===fields.period)) {
- const other=key==='period'?'group':'period'; fields[other]=fields[key];
+$("#open-project").onchange = async (event) => {
+ const file = event.target.files[0];
+ event.target.value = "";
+ if (!file || busy) return;
+ setBusy(true);
+ status("Reading saved project…");
+ try {
+ if (file.size > 12 * 1024 * 1024)
+ throw new Error("Project exceeds 12 MiB.");
+ const p = C.validateProject(
+ JSON.parse(
+ new TextDecoder("utf-8", { fatal: true }).decode(
+ await file.arrayBuffer(),
+ ),
+ ),
+ );
+ if ((await hash(bytes(C.stable(p.bundle)))) !== p.revision)
+ throw new Error("Project revision checksum mismatch.");
+ setBusy(false);
+ await commit(p.bundle, p.view);
+ } catch (error) {
+ setBusy(false);
+ status(
+ error.message + (current ? " Last good analysis is unchanged." : ""),
+ true,
+ );
}
- fields[key]=value; configure();
};
-for(const kind of ['trend','bars']) $(kind).onclick=()=>{
- mode=kind;
- for(const id of ['trend','bars']) $(id).setAttribute('aria-pressed',String(id===mode));
- drawChart();
+$("#save-project").onclick = () => {
+ current.view.notes = $("#notes").value;
+ download(
+ "analysis.data-studio.json",
+ JSON.stringify(
+ {
+ format: "data-studio",
+ spec: 1,
+ revision: current.report.revision,
+ bundle: current.bundle,
+ view: current.view,
+ },
+ null,
+ 2,
+ ),
+ );
+ status(
+ "Project saved with source CSVs, types, queries, applied controls and notes. Unapplied controls or SQL drafts are not included.",
+ );
};
-$('export').onclick=()=>{
- const blob=new Blob([exportCSV(table.headers,snapshot.rows)],{type:'text/csv;charset=utf-8'});
- const url=URL.createObjectURL(blob), link=document.createElement('a');
- link.href=url; link.download='data-studio-selection.csv'; link.click(); setTimeout(()=>URL.revokeObjectURL(url),30000);
+$("#export-db").onclick = () =>
+ download("analysis.sqlite", current.database, "application/vnd.sqlite3");
+$("#export-report").onclick = () =>
+ download(
+ "analysis-report.html",
+ globalThis.DataStudioReport(
+ current.bundle,
+ current.report,
+ $("#notes").value,
+ ),
+ "text/html",
+ );
+$("#export-csv").onclick = () => {
+ const r = current.report.results.find((r) => r.id === selected);
+ download(selected + ".csv", C.csv(r.columns, r.rows), "text/csv");
};
-await load();
+$("#export-json").onclick = () => {
+ const r = current.report.results.find((r) => r.id === selected);
+ download(
+ selected + ".json",
+ JSON.stringify(
+ {
+ revision: current.report.revision,
+ parameters: current.report.parameters,
+ query: current.bundle.config.queries.find((q) => q.id === selected),
+ ...r,
+ },
+ null,
+ 2,
+ ),
+ );
+};
+try {
+ const [p, baseline] = await Promise.all([
+ get("output/project.data-studio.json").then(JSON.parse),
+ get("output/analysis-result.json").then(JSON.parse),
+ ]);
+ C.validateProject(p);
+ if ((await hash(bytes(C.stable(p.bundle)))) !== p.revision)
+ throw new Error("Saved project revision mismatch.");
+ await commit(p.bundle, p.view, { baseline });
+} catch (error) {
+ status(error.message, true);
+}
diff --git a/store/agents/data-studio/template/data.csv b/store/agents/data-studio/template/data.csv
deleted file mode 100644
index fa43fb79c..000000000
--- a/store/agents/data-studio/template/data.csv
+++ /dev/null
@@ -1,17 +0,0 @@
-quarter,region,revenue,units
-2025-Q1,North,12400,310
-2025-Q1,South,8100,202
-2025-Q1,East,15200,380
-2025-Q1,West,9800,245
-2025-Q2,North,13200,330
-2025-Q2,South,9400,235
-2025-Q2,East,16100,402
-2025-Q2,West,10500,262
-2025-Q3,North,14100,352
-2025-Q3,South,9800,245
-2025-Q3,East,17300,432
-2025-Q3,West,11200,280
-2025-Q4,North,14900,372
-2025-Q4,South,10300,257
-2025-Q4,East,18600,465
-2025-Q4,West,12100,302
diff --git a/store/agents/data-studio/template/data.mjs b/store/agents/data-studio/template/data.mjs
deleted file mode 100644
index 15ed32cc6..000000000
--- a/store/agents/data-studio/template/data.mjs
+++ /dev/null
@@ -1,79 +0,0 @@
-// Shared by the dashboard and Node tests. No external runtime or chart library.
-export function parseCSV(input) {
- const text = String(input).replace(/^\uFEFF/, '');
- const records = []; let record = [], field = '', quoted = false, closed = false;
- const finishField = () => { record.push(field); field = ''; closed = false; };
- const finishRecord = () => {
- finishField();
- if (record.some(value => value.trim() !== '')) records.push(record);
- record = [];
- };
- for (let i = 0; i < text.length; i++) {
- const char = text[i];
- if (quoted) {
- if (char === '"' && text[i + 1] === '"') { field += '"'; i++; }
- else if (char === '"') { quoted = false; closed = true; }
- else field += char;
- } else if (char === '"' && field === '' && !closed) quoted = true;
- else if (char === ',') finishField();
- else if (char === '\n' || char === '\r') { if (char === '\r' && text[i + 1] === '\n') i++; finishRecord(); }
- else if (closed || char === '"') throw new Error('Unexpected character after a CSV quote.');
- else field += char;
- }
- if (quoted) throw new Error('An opening CSV quote has no closing quote.');
- if (field !== '' || record.length || closed) finishRecord();
- if (!records.length) throw new Error('The CSV is empty. Add a header row and your data.');
- const headers = records.shift().map(value => value.trim());
- if (headers.some(value => !value) || new Set(headers).size !== headers.length) throw new Error('Column names must be nonempty and unique.');
- const rows = records.map((record, index) => {
- if (record.length !== headers.length) throw new Error(`Record ${index + 2} has ${record.length} fields; expected ${headers.length}.`);
- return Object.fromEntries(headers.map((header, i) => [header, record[i]]));
- });
- return { headers, rows };
-}
-
-export function numericColumns({ headers, rows }) {
- return headers.filter(key => rows.length && rows.every(row => row[key].trim() !== '' && Number.isFinite(Number(row[key]))));
-}
-
-export function inferFields(table) {
- const numeric = numericColumns(table);
- if (!numeric.length) throw new Error('Choose data with at least one numeric column (no blank values).');
- const dimensions = table.headers.filter(key => !numeric.includes(key));
- if (dimensions.length < 2) throw new Error('This view needs two text columns (period and group) plus a numeric value.');
- const period = dimensions.find(key => /^(quarter|month|date|period|year)$/i.test(key)) || dimensions[0];
- const group = dimensions.find(key => /^(region|category|group|product|team)$/i.test(key) && key !== period) || dimensions.find(key => key !== period);
- const metric = numeric.find(key => /^(revenue|sales|value|amount)$/i.test(key)) || numeric[0];
- return { period, group, metric };
-}
-
-export function summarize(table, fields, enabled, range = {}) {
- const { period, group, metric } = fields;
- const periods = [...new Set(table.rows.map(row => row[period]))].sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
- const groups = [...new Set(table.rows.map(row => row[group]))].sort((a, b) => a.localeCompare(b));
- const start = Math.max(0, periods.indexOf(range.start)), end = range.end ? periods.indexOf(range.end) : periods.length - 1;
- const window = periods.slice(start, end + 1);
- const included = new Set(window), sums = new Map(), periodSums = new Map();
- const rows = table.rows.filter(row => enabled.has(row[group]) && included.has(row[period]));
- for (const row of rows) {
- const name = row[group], label = row[period], value = Number(row[metric]);
- if (!sums.has(name)) sums.set(name, new Map());
- const bucket = sums.get(name);
- bucket.set(label, (bucket.get(label) || 0) + value);
- periodSums.set(label, (periodSums.get(label) || 0) + value);
- }
- const series = groups.filter(name => enabled.has(name)).map(name => ({ name, values: window.map(label => ({
- period: label,
- value: sums.get(name)?.get(label) || 0
- })) }));
- const totals = window.map(label => periodSums.get(label) || 0);
- const total = totals.reduce((sum, value) => sum + value, 0);
- const growth = totals.length > 1 && totals[0] !== 0 ? (totals.at(-1) - totals[0]) / Math.abs(totals[0]) : null;
- const ranked = series.map(series => ({ name: series.name, value: series.values.reduce((sum, point) => sum + point.value, 0) })).sort((a, b) => b.value - a.value);
- return { periods: window, groups, rows, series, totals, total, growth, ranked };
-}
-
-export function exportCSV(headers, rows) {
- const escape = value => '"' + String(value ?? '').replaceAll('"', '""') + '"';
- return [headers, ...rows.map(row => headers.map(key => row[key]))].map(row => row.map(escape).join(',')).join('\r\n') + '\r\n';
-}
diff --git a/store/agents/data-studio/template/index.html b/store/agents/data-studio/template/index.html
index 259bf7344..00b9e6f62 100644
--- a/store/agents/data-studio/template/index.html
+++ b/store/agents/data-studio/template/index.html
@@ -1,56 +1,197 @@
<!doctype html>
<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width,initial-scale=1">
-<title>Data Studio — a clearer picture</title>
-<style>
-:root{color-scheme:light;--bg:#f4f5ef;--white:#fff;--ink:#263d34;--muted:#7b877e;--line:#e2e7df;--green:#275c49;--lime:#ddebaf;--mono:11px/1.5 ui-monospace,SFMono-Regular,monospace}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:13px/1.5 system-ui,-apple-system,sans-serif}button,select,input{font:inherit}button,select{cursor:pointer;color:inherit}button{touch-action:manipulation}:focus-visible{outline:2px solid #578d65;outline-offset:3px}button{border:1px solid var(--line);background:white;border-radius:7px;padding:8px 12px}button:hover{border-color:#96af9b}.eyebrow{font:var(--mono);letter-spacing:1.4px;text-transform:uppercase;color:var(--muted)}
-header{height:72px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);padding:0 34px;background:#fafbf7}.brand{font-size:17px;font-weight:650;letter-spacing:-.5px;display:flex;gap:10px;align-items:center}.brand-icon{width:24px;height:24px;display:flex;gap:3px;align-items:end}.brand-icon i{background:var(--green);width:5px;border-radius:2px}.brand-icon i:nth-child(1){height:10px}.brand-icon i:nth-child(2){height:22px}.brand-icon i:nth-child(3){height:16px}.header-tools{display:flex;gap:9px;align-items:center}.source{font:var(--mono);color:var(--muted);margin-right:7px;max-width:180px;overflow:hidden;text-overflow:ellipsis}.primary{background:var(--green);color:white;border-color:var(--green)}.primary:hover{background:#194632}
-main{padding:32px 34px;max-width:1520px;margin:auto}.intro{display:flex;justify-content:space-between;gap:20px;align-items:end;margin-bottom:26px}h1{font-size:clamp(28px,3.1vw,43px);letter-spacing:-1.8px;font-weight:500;line-height:1.12;margin:9px 0 11px}.intro p{color:var(--muted);margin:0;font-size:13px}.stamp{font:var(--mono);color:var(--muted);white-space:nowrap;padding-bottom:4px}.stamp i{display:inline-block;width:5px;height:5px;background:#6a8a52;border-radius:50%;margin-right:6px}
-.metrics{display:grid;grid-template-columns:1.25fr 1fr 1fr;gap:14px;margin-bottom:22px}.metric{background:white;border:1px solid var(--line);border-radius:10px;padding:19px 22px;position:relative;min-height:116px}.metric:first-child{background:var(--green);color:white;border-color:var(--green)}.metric .label{font-size:11px;color:var(--muted)}.metric:first-child .label,.metric:first-child small{color:#d4e6d9}.metric strong{display:block;font-size:31px;font-weight:500;letter-spacing:-1px;margin:5px 0}.metric small{font:var(--mono);color:var(--muted)}.metric .marker{position:absolute;right:22px;top:24px;font-size:20px;color:#97b99b}
-.workspace{display:grid;grid-template-columns:218px minmax(0,1fr);gap:22px}.filters{padding:6px 4px 0 0}.filter-title{display:flex;justify-content:space-between;align-items:center;margin-bottom:17px}.filter-title h2{font-size:13px;margin:0;font-weight:600}.filter-title button{border:0;background:transparent;font-size:11px;padding:0;color:var(--muted)}.regions{display:grid;gap:6px}.region{display:flex;align-items:center;gap:8px;padding:9px 11px;background:transparent;border-color:transparent;text-align:left}.region:hover{background:#e9eee3}.region[aria-pressed=true]{background:#e8eedf;border-color:#d8e2ce}.dot{width:7px;height:7px;border-radius:50%;flex-shrink:0}.region .count{margin-left:auto;font:var(--mono);color:var(--muted)}.region .check{width:12px;color:var(--green)}.range{border-top:1px solid var(--line);margin-top:22px;padding-top:19px;display:grid;gap:11px}.field{display:grid;gap:5px}.field label{font-size:10px;color:var(--muted)}select{width:100%;background:#fafbf7;border:1px solid #dce2d7;border-radius:6px;padding:8px 7px;font-size:11px}.mapping{margin-top:22px;padding-top:18px;border-top:1px solid var(--line);font-size:11px}.mapping summary{cursor:pointer;color:var(--muted);margin-bottom:12px}.mapping .field{margin:10px 0}.side-note{margin-top:28px;font-size:11px;color:var(--muted);line-height:1.7}
-.content{min-width:0}.chart-card{background:white;border:1px solid var(--line);border-radius:10px;overflow:hidden}.chart-head{display:flex;justify-content:space-between;gap:12px;padding:22px 23px 9px;align-items:center}h2{font-size:14px;font-weight:600;margin:0}.chart-head p{font:var(--mono);color:var(--muted);margin:3px 0 0}.view-switch{display:flex;gap:3px;background:var(--bg);border-radius:6px;padding:3px}.view-switch button{border:0;background:transparent;padding:5px 9px;font-size:11px}.view-switch button[aria-pressed=true]{background:white;box-shadow:0 1px 3px #0001}.plot{position:relative;padding:3px 17px 4px;min-height:274px}.plot svg{width:100%;display:block;overflow:visible}.plot svg text{font-family:ui-monospace,monospace;fill:#88938c;font-size:10px}.plot .point{cursor:pointer;outline:none}.plot .point:focus{stroke:#172b21;stroke-width:3}.chart-foot{display:flex;justify-content:space-between;align-items:center;padding:13px 23px;border-top:1px solid var(--line);font-size:11px;color:var(--muted);gap:12px}.legend{display:flex;gap:15px;flex-wrap:wrap}.legend span{display:flex;gap:5px;align-items:center}.empty{padding:75px 20px;text-align:center;color:var(--muted)}.empty strong{display:block;color:var(--ink);font-size:16px;font-weight:500;margin-bottom:6px}.bottom{display:grid;grid-template-columns:.85fr 1.15fr;gap:18px;margin-top:19px}.panel{background:white;border:1px solid var(--line);border-radius:10px;padding:20px 22px;min-width:0}.panel h2{margin-bottom:18px}.ranking-row{margin:16px 0}.ranking-label{display:flex;justify-content:space-between;font-size:11px;margin-bottom:6px;gap:10px}.track{height:6px;background:#f1f3ec;border-radius:3px;overflow:hidden}.track i{display:block;height:100%;border-radius:3px}.table-wrap{max-height:216px;overflow:auto}table{width:100%;border-collapse:collapse;font-size:11px;text-align:left;font-variant-numeric:tabular-nums}th{color:var(--muted);font-size:10px;font-weight:400;background:white;position:sticky;top:0}td,th{padding:8px 6px;border-bottom:1px solid #eef1ea;white-space:nowrap}td:last-child,th:last-child{text-align:right}tr.selected td{background:#edf3da}.table-note{font:var(--mono);font-size:10px;color:var(--muted);margin-top:12px}
-.error{padding:22px;border:1px solid #d5a48d;border-radius:10px;background:#fff7ef;margin-bottom:20px;color:#7e3c28}.error strong{display:block;font-size:15px;margin-bottom:4px}[hidden]{display:none!important}.tip{position:fixed;pointer-events:none;padding:10px 13px;background:#243c31;color:white;border-radius:7px;box-shadow:0 6px 20px #172d2425;font-size:11px;z-index:9;max-width:240px}.tip strong{display:block;font-size:15px;margin-top:3px}.loading{padding:60px;text-align:center;color:var(--muted)}
-@media(max-width:950px){main{padding:25px 23px}.workspace{grid-template-columns:175px minmax(0,1fr);gap:18px}.bottom{grid-template-columns:1fr}.metric{padding:17px}.metric strong{font-size:27px}.stamp{display:none}header{padding:0 23px}}
-@media(max-width:650px){header{height:64px;padding:0 18px}.header-tools{gap:6px}.source{display:none}.header-tools button{font-size:10px;padding:7px 9px}.brand{font-size:15px}main{padding:24px 18px}.intro{margin-bottom:19px}h1{font-size:32px}.metrics{grid-template-columns:1fr 1fr;gap:9px}.metric:first-child{grid-column:1/-1;min-height:100px}.metric{min-height:108px;padding:15px}.metric strong{font-size:26px}.metric .marker{display:none}.workspace{display:block}.filters{margin-bottom:20px}.regions{display:flex;flex-wrap:wrap;gap:3px}.region{padding:7px 9px;font-size:11px}.region .count{display:none}.range{display:grid;grid-template-columns:1fr 1fr;margin-top:15px;padding-top:14px}.mapping{margin-top:14px;padding-top:12px}.side-note{display:none}.chart-head{padding:18px 15px 6px;align-items:start}.chart-head h2{font-size:12px}.chart-head p{font-size:9px}.view-switch button{padding:4px 7px}.plot{padding:4px 7px;min-height:0}.chart-foot{padding:12px 15px;display:block}.legend{gap:10px;margin-bottom:8px}.bottom{gap:14px}.panel{padding:18px 15px}}
-</style>
-</head>
-<body>
-<header><div class="brand"><span class="brand-icon" aria-hidden="true"><i></i><i></i><i></i></span>Data Studio</div><div class="header-tools"><span class="source" id="source">data.csv</span><button id="open">Open CSV ↗</button><button class="primary" id="export" disabled>Export selection ↓</button><input id="upload" type="file" accept=".csv,text/csv" hidden aria-label="Choose a CSV file"></div></header>
-<main>
- <div class="intro"><div><span class="eyebrow">From data to discovery</span><h1 id="headline">A clearer picture.</h1><p id="takeaway">Your numbers have a story. Find it here.</p></div><span class="stamp" id="stamp"><i></i>Local data · private by design</span></div>
- <div class="error" id="error" role="alert" hidden><strong>We couldn’t read this dataset.</strong><span id="error-message"></span> <button id="retry">Reload data.csv</button></div>
- <div class="loading" id="loading" role="status">Reading data.csv…</div>
- <div id="dashboard" hidden>
- <section class="metrics" aria-label="Selection summary">
- <div class="metric"><span class="label" id="total-label">Total revenue</span><strong id="total">—</strong><small id="row-count"></small><span class="marker" aria-hidden="true">↗</span></div>
- <div class="metric"><span class="label">First → last period</span><strong id="growth">—</strong><small id="growth-detail"></small></div>
- <div class="metric"><span class="label">Leading group</span><strong id="leader">—</strong><small id="leader-detail"></small></div>
- </section>
- <div class="workspace">
- <aside class="filters" aria-label="Data filters">
- <div class="filter-title"><h2 id="group-label">Regions</h2><button id="reset">Reset filters</button></div>
- <div class="regions" id="regions" role="group" aria-label="Groups"></div>
- <div class="range"><div class="field"><label for="start">From period</label><select id="start"></select></div><div class="field"><label for="end">To period</label><select id="end"></select></div></div>
- <details class="mapping"><summary>Map your columns</summary><div class="field"><label for="period-field">Period column</label><select id="period-field"></select></div><div class="field"><label for="group-field">Group column</label><select id="group-field"></select></div><div class="field"><label for="metric-field">Value column</label><select id="metric-field"></select></div></details>
- <p class="side-note">Every chart and number follows your selection.<br><br>Your CSV stays on this device. Nothing is uploaded.</p>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Data Studio · Reproducible analysis</title>
+ <link rel="icon" href="data:," />
+ <link rel="stylesheet" href="styles.css" />
+ </head>
+ <body>
+ <header class="topbar">
+ <div class="brand">
+ <span class="mark" aria-hidden="true">▥</span> Data Studio
+ <span class="eyebrow muted">/ LOCAL ANALYST</span>
+ </div>
+ <div class="toolbar">
+ <label class="button file-button"
+ >Open project<input id="open-project" type="file" accept=".json"
+ /></label>
+ <button id="export-db" disabled>SQLite database</button
+ ><button id="export-report" disabled>Export report</button
+ ><button id="save-project" class="primary" disabled>
+ Save project ↗
+ </button>
+ </div>
+ </header>
+ <div class="layout">
+ <aside>
+ <section class="side-section">
+ <h3 class="eyebrow muted">SOURCE FILES</h3>
+ <div id="sources"></div>
+ <p class="side-copy">
+ Local files. Explicit types.<br />No silent cleaning or upload.
+ </p>
+ </section>
+ <section class="side-section">
+ <h3 class="eyebrow muted">SAVED QUESTIONS</h3>
+ <nav id="queries" aria-label="Saved analyses"></nav>
+ </section>
+ <section class="side-section health">
+ <h3 class="eyebrow muted">DATA QUALITY</h3>
+ <div id="check-count" class="check-count">—</div>
+ <p class="side-copy" id="check-summary">Waiting for an analysis</p>
+ <button id="show-checks" class="quiet">Inspect checks</button>
+ </section>
</aside>
- <div class="content">
- <section class="chart-card">
- <div class="chart-head"><div><h2 id="chart-title">Revenue over time</h2><p id="chart-subtitle"></p></div><div class="view-switch" role="group" aria-label="Chart type"><button id="trend" aria-pressed="true">Trend</button><button id="bars" aria-pressed="false">Bars</button></div></div>
- <div class="plot" id="plot"></div>
- <div class="chart-foot"><div class="legend" id="legend"></div><span>Tap a point to inspect</span></div>
+ <main>
+ <div class="intro">
+ <div>
+ <p class="eyebrow muted">FROM SOURCE ROWS TO AN ANSWER</p>
+ <h1 id="title">
+ Your data. A question.<br />A reproducible answer.
+ </h1>
+ <p id="question" class="muted">
+ Build the workspace to load its saved analysis.
+ </p>
+ </div>
+ <span id="example" class="pill">LOCAL WORKSPACE</span>
+ </div>
+ <div id="status" class="status" role="status" aria-live="polite">
+ Loading saved project…
+ </div>
+ <button id="cancel-run" hidden>Cancel running query</button>
+ <div
+ id="filters"
+ class="filters"
+ role="form"
+ aria-label="Analysis controls"
+ ></div>
+ <section
+ id="metrics"
+ class="metrics"
+ aria-label="Calculated metrics"
+ ></section>
+ <section class="panel" id="answer">
+ <div class="panel-head">
+ <div>
+ <p class="eyebrow muted">EXPLORE THE ANSWER</p>
+ <h2 id="query-title">Saved analysis</h2>
+ <p id="query-explanation"></p>
+ </div>
+ <div class="small-tools">
+ <button id="reset-trace" hidden>Clear drilldown</button
+ ><button id="export-csv" disabled>CSV ↓</button
+ ><button id="export-json" disabled>Exact JSON ↓</button>
+ </div>
+ </div>
+ <div id="chart" class="chart" aria-label="Query chart"></div>
+ <div id="axis" class="chart-axis"></div>
+ <div class="table-scroll">
+ <table id="result-table"></table>
+ <p id="empty" class="empty" hidden>
+ No matching records. Missing values remain missing.
+ </p>
+ </div>
+ <div class="pagination">
+ <span id="row-count">No result yet</span>
+ <div>
+ <button id="previous">← Previous</button>
+ <button id="next">Next →</button>
+ </div>
+ </div>
+ <p class="edit-help">
+ CSV is spreadsheet-safe; formula-looking text gets an apostrophe.
+ Exact JSON preserves text and nulls. Numeric exports retain the
+ query’s stored units.
+ </p>
+ <details id="calculation">
+ <summary>How this answer is calculated · editable SQL</summary>
+ <textarea
+ id="sql"
+ class="sql"
+ spellcheck="false"
+ aria-label="Saved SQL query"
+ ></textarea>
+ <p class="edit-help">
+ Read-only SQLite. Named controls use :parameter. Run validates
+ every saved query and check; Save project retains successful
+ edits.
+ </p>
+ <button id="run-sql">Run revised query</button>
+ </details>
</section>
- <div class="bottom">
- <section class="panel"><h2>Where it comes from</h2><div id="ranking"></div></section>
- <section class="panel"><h2>The numbers behind the picture</h2><div class="table-wrap"><table id="table"><thead></thead><tbody></tbody></table></div><div class="table-note" id="table-note"></div></section>
+ <div class="bottom-grid">
+ <section class="panel">
+ <p class="eyebrow muted">METHOD & BOUNDARIES</p>
+ <h2>Know what these numbers mean.</h2>
+ <p id="method"></p>
+ <ul id="limitations"></ul>
+ <a id="portable" class="button" href="output/project.zip" download
+ >Original built project ZIP ↓</a
+ >
+ <p class="edit-help">
+ ZIP is the last workspace build. Save project above captures your
+ current browser changes. Both include source data—review before
+ sharing.
+ </p>
+ </section>
+ <section class="panel">
+ <p class="eyebrow muted">YOUR REVIEW</p>
+ <h2>Keep the reasoning with the result.</h2>
+ <textarea
+ id="notes"
+ rows="5"
+ maxlength="4000"
+ aria-label="Review notes"
+ placeholder="What did you learn? What should someone check next?"
+ ></textarea>
+ <p class="edit-help">
+ Notes persist in Save project and Export report. Browser changes
+ are not written to the workspace automatically.
+ </p>
+ </section>
</div>
- </div>
+ <footer class="footer">
+ <span id="revision">No verified revision</span
+ ><span id="engine"></span><span>PRIVATE BY DESIGN · NO CDN</span>
+ </footer>
+ </main>
</div>
- </div>
-</main>
-<div id="tooltip" class="tip" role="status" hidden></div>
-<script type="module" src="dashboard.mjs"></script>
-</body>
+ <dialog id="source-dialog">
+ <div class="dialog-head">
+ <div>
+ <p class="eyebrow muted">ORIGINAL RECORDS & IMPORT RULES</p>
+ <h2 id="source-title"></h2>
+ </div>
+ <button id="close-source" aria-label="Close source">Close</button>
+ </div>
+ <div id="schema"></div>
+ <div class="small-tools">
+ <label class="button file-button"
+ >Replace this CSV<input
+ id="replace-source"
+ type="file"
+ accept=".csv,text/csv" /></label
+ ><button id="download-source">Original CSV ↓</button>
+ </div>
+ <p class="edit-help">
+ Replacement must match the saved headers and types. For a new schema or
+ question, ask the agent to update analysis.json and SQL. Invalid imports
+ keep the last good analysis.
+ </p>
+ <div class="table-scroll"><table id="raw-record"></table></div>
+ <p id="source-caption" class="edit-help"></p>
+ </dialog>
+ <dialog id="checks-dialog">
+ <div class="dialog-head">
+ <h2>Checks, source rules & missing values</h2>
+ <button id="close-checks">Close</button>
+ </div>
+ <div id="checks"></div>
+ </dialog>
+ <script src="core.js"></script>
+ <script src="report.js"></script>
+ <script type="module" src="dashboard.mjs"></script>
+ </body>
</html>
diff --git a/store/agents/data-studio/template/proof.json b/store/agents/data-studio/template/proof.json
index 995d49ea3..f4f4947f0 100644
--- a/store/agents/data-studio/template/proof.json
+++ b/store/agents/data-studio/template/proof.json
@@ -1,8 +1,60 @@
{
"actions": [
- { "selector": "#bars", "click": true },
- { "selector": "#bars", "attribute": { "name": "aria-pressed", "value": "true" } },
- { "selector": "#trend", "click": true },
- { "selector": "#trend", "attribute": { "name": "aria-pressed", "value": "true" } }
+ {
+ "selector": "body[data-ready=true]",
+ "attribute": {
+ "name": "data-ready",
+ "value": "true"
+ }
+ },
+ {
+ "selector": "[data-query=\"monthly\"]",
+ "click": true
+ },
+ {
+ "selector": "#result-table[data-query=\"monthly\"]",
+ "attribute": {
+ "name": "data-query",
+ "value": "monthly"
+ }
+ },
+ {
+ "selector": "[data-query=\"contribution\"]",
+ "click": true
+ },
+ {
+ "selector": "[data-category=\"Outdoor\"]",
+ "click": true
+ },
+ {
+ "selector": "#result-table[data-query=\"transactions_detail\"]",
+ "attribute": {
+ "name": "data-query",
+ "value": "transactions_detail"
+ }
+ },
+ {
+ "selector": "#row-count[data-count=\"8\"]",
+ "text": "1–8 of 8 exact result rows"
+ },
+ {
+ "selector": "#reset-trace",
+ "click": true
+ },
+ {
+ "selector": "#row-count[data-count=\"24\"]",
+ "text": "1–24 of 24 exact result rows"
+ },
+ {
+ "selector": "[data-query=\"contribution\"]",
+ "click": true
+ },
+ {
+ "selector": "#result-table[data-query=\"contribution\"]",
+ "attribute": {
+ "name": "data-query",
+ "value": "contribution"
+ }
+ }
]
}
diff --git a/store/agents/data-studio/template/queries/contribution.sql b/store/agents/data-studio/template/queries/contribution.sql
new file mode 100644
index 000000000..d101a6937
--- /dev/null
+++ b/store/agents/data-studio/template/queries/contribution.sql
@@ -0,0 +1,11 @@
+WITH category_totals AS (
+ SELECT p.category,
+ sum(CASE WHEN substr(t.sold_on,1,7)=substr(:baseline,1,7) THEN t.quantity*t.unit_price_cents-t.discount_cents-t.refund_cents ELSE 0 END) AS b,
+ sum(CASE WHEN substr(t.sold_on,1,7)=substr(:comparison,1,7) THEN t.quantity*t.unit_price_cents-t.discount_cents-t.refund_cents ELSE 0 END) AS c
+ FROM transactions t JOIN products p ON t.product_id=p.product_id
+ WHERE t.status='completed' AND (:region='' OR t.region=:region)
+ AND substr(t.sold_on,1,7) IN (substr(:baseline,1,7),substr(:comparison,1,7))
+ GROUP BY p.category
+)
+SELECT category, b AS baseline_sales, c AS comparison_sales, c-b AS change
+FROM category_totals ORDER BY change DESC, category;
diff --git a/store/agents/data-studio/template/queries/detail.sql b/store/agents/data-studio/template/queries/detail.sql
new file mode 100644
index 000000000..9dde470e6
--- /dev/null
+++ b/store/agents/data-studio/template/queries/detail.sql
@@ -0,0 +1,8 @@
+SELECT t._record AS transactions_record, p._record AS products_record,
+ t.line_id, t.sold_on, p.product, p.category, t.region, t.quantity,
+ t.quantity*t.unit_price_cents-t.discount_cents-t.refund_cents AS net_sales
+FROM transactions t JOIN products p ON t.product_id=p.product_id
+WHERE t.status='completed' AND (:region='' OR t.region=:region)
+ AND (:category='' OR p.category=:category)
+ AND substr(t.sold_on,1,7) IN (substr(:baseline,1,7),substr(:comparison,1,7))
+ORDER BY t.sold_on,t.line_id;
diff --git a/store/agents/data-studio/template/queries/headline.sql b/store/agents/data-studio/template/queries/headline.sql
new file mode 100644
index 000000000..4ee6133f8
--- /dev/null
+++ b/store/agents/data-studio/template/queries/headline.sql
@@ -0,0 +1,12 @@
+WITH eligible AS (
+ SELECT t.*, quantity * unit_price_cents - discount_cents - refund_cents AS net
+ FROM transactions t JOIN products p ON t.product_id = p.product_id
+ WHERE status = 'completed' AND (:region = '' OR region = :region)
+ AND substr(sold_on, 1, 7) IN (substr(:baseline,1,7), substr(:comparison,1,7))
+), totals AS (
+ SELECT coalesce(sum(CASE WHEN substr(sold_on,1,7) = substr(:baseline,1,7) THEN net ELSE 0 END),0) AS b,
+ coalesce(sum(CASE WHEN substr(sold_on,1,7) = substr(:comparison,1,7) THEN net ELSE 0 END),0) AS c,
+ count(*) AS n FROM eligible
+)
+SELECT b AS baseline_sales, c AS comparison_sales, c-b AS change,
+ (c-b)*1.0/nullif(abs(b),0) AS growth, n AS completed_lines FROM totals;
diff --git a/store/agents/data-studio/template/queries/monthly.sql b/store/agents/data-studio/template/queries/monthly.sql
new file mode 100644
index 000000000..b5c515f5b
--- /dev/null
+++ b/store/agents/data-studio/template/queries/monthly.sql
@@ -0,0 +1,6 @@
+SELECT substr(sold_on,1,7) AS month,
+ sum(quantity*unit_price_cents-discount_cents-refund_cents) AS net_sales,
+ count(*) AS completed_lines
+FROM transactions
+WHERE status='completed' AND (:region='' OR region=:region)
+GROUP BY substr(sold_on,1,7) ORDER BY month;
diff --git a/store/agents/data-studio/template/report.js b/store/agents/data-studio/template/report.js
new file mode 100644
index 000000000..9429fb337
--- /dev/null
+++ b/store/agents/data-studio/template/report.js
@@ -0,0 +1,72 @@
+// Self-contained, inert HTML handoff. Export current results, parameters and method, never scripts.
+globalThis.DataStudioReport = (bundle, report, notes = "") => {
+ const C = globalThis.DataStudioCore,
+ esc = (value) =>
+ String(value ?? "")
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;")
+ .replaceAll('"', "&quot;");
+ const c = bundle.config;
+ return (
+ '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'; base-uri \'none\'; form-action \'none\'"><title>' +
+ esc(c.title) +
+ "</title><style>body{font:15px/1.6 system-ui;color:#18362d;max-width:1120px;margin:40px auto;padding:0 24px}h1{font-size:36px}h2{margin-top:40px}small,p{color:#52645c}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums;font-size:13px}th,td{text-align:left;border-bottom:1px solid #ddd;padding:8px}th{background:#edf4ef}section{overflow:auto}.badge{color:#805600}pre{white-space:pre-wrap;overflow-wrap:anywhere}li{margin:5px 0}@media print{body{margin:0}section{break-inside:avoid}thead{display:table-header-group}}</style><body><p>DATA STUDIO · REPRODUCIBLE ANALYSIS</p><h1>" +
+ esc(c.title) +
+ '</h1><p class="badge">' +
+ (c.example
+ ? "Synthetic example data — not real results"
+ : "User-supplied data") +
+ "</p><p>" +
+ esc(c.question) +
+ "</p><p>" +
+ esc(c.method) +
+ "</p><h2>Applied controls</h2><pre>" +
+ esc(JSON.stringify(report.parameters, null, 2)) +
+ "</pre>" +
+ report.results
+ .map((r) => {
+ const q = c.queries.find((q) => q.id === r.id);
+ return (
+ "<section><h2>" +
+ esc(q.title) +
+ "</h2><p>" +
+ esc(q.explanation) +
+ "</p><table><thead><tr>" +
+ r.columns.map((k) => "<th>" + esc(k) + "</th>").join("") +
+ "</tr></thead><tbody>" +
+ r.rows
+ .map(
+ (row) =>
+ "<tr>" +
+ row
+ .map(
+ (v, i) =>
+ "<td>" +
+ esc(C.format(v, q.formats?.[r.columns[i]])) +
+ "</td>",
+ )
+ .join("") +
+ "</tr>",
+ )
+ .join("") +
+ "</tbody></table>" +
+ (!r.rows.length
+ ? "<p>No matching records. Missing is not zero.</p>"
+ : "") +
+ "</section>"
+ );
+ })
+ .join("") +
+ "<h2>Checks and limitations</h2><ul>" +
+ report.checks.map((x) => "<li>" + esc(x.description) + "</li>").join("") +
+ c.limitations.map((x) => "<li>" + esc(x) + "</li>").join("") +
+ "</ul><h2>Review notes</h2><pre>" +
+ esc(notes || "No review notes saved.") +
+ "</pre><h2>Reproducibility</h2><p>Revision " +
+ esc(report.revision) +
+ "<br>" +
+ esc(report.engine) +
+ "</p><p>CSV exports are spreadsheet-safe: formula-looking text is prefixed with an apostrophe. Null exports as an empty CSV field; use the project JSON or SQLite database for exact types and missing values. Source CSVs and saved SQL are in the project; _record is the original CSV record number, including the header as record 1.</p></body></html>"
+ );
+};
diff --git a/store/agents/data-studio/template/sources/products.csv b/store/agents/data-studio/template/sources/products.csv
new file mode 100644
index 000000000..d5272bb8d
--- /dev/null
+++ b/store/agents/data-studio/template/sources/products.csv
@@ -0,0 +1,7 @@
+product_id,product,category
+001,Desk lamp,Home
+002,Cable organizer,Home
+010,Sketchbook,Creative
+011,Watercolor set,Creative
+020,Travel mug,Outdoor
+021,Day pack,Outdoor
diff --git a/store/agents/data-studio/template/sources/transactions.csv b/store/agents/data-studio/template/sources/transactions.csv
new file mode 100644
index 000000000..0578c7bee
--- /dev/null
+++ b/store/agents/data-studio/template/sources/transactions.csv
@@ -0,0 +1,27 @@
+line_id,sold_on,product_id,region,quantity,unit_price_usd,discount_usd,refund_usd,status,note
+00001,2026-01-05,001,East,12,38.00,0.00,0.00,completed,Synthetic example — not real transactions
+00002,2026-01-08,002,East,24,12.50,5.00,0.00,completed,
+00003,2026-01-11,010,East,18,16.00,0.00,0.00,completed,
+00004,2026-01-14,011,East,8,32.00,0.00,0.00,completed,
+00005,2026-01-17,020,East,14,24.00,0.00,0.00,completed,
+00006,2026-01-20,021,East,6,65.00,0.00,0.00,completed,
+00007,2026-01-05,001,West,15,38.00,0.00,0.00,completed,Synthetic example — not real transactions
+00008,2026-01-08,002,West,27,12.50,5.00,0.00,completed,
+00009,2026-01-11,010,West,21,16.00,0.00,0.00,completed,
+00010,2026-01-14,011,West,11,32.00,0.00,0.00,completed,
+00011,2026-01-17,020,West,17,24.00,0.00,0.00,completed,
+00012,2026-01-20,021,West,9,65.00,0.00,0.00,completed,
+00013,2026-02-05,001,East,9,38.00,0.00,0.00,completed,Synthetic example — not real transactions
+00014,2026-02-08,002,East,18,12.50,5.00,0.00,completed,
+00015,2026-02-11,010,East,25,16.00,0.00,0.00,completed,
+00016,2026-02-14,011,East,16,32.00,0.00,0.00,completed,
+00017,2026-02-17,020,East,8,24.00,0.00,24.00,completed,
+00018,2026-02-20,021,East,4,65.00,0.00,0.00,completed,
+00019,2026-02-05,001,West,12,38.00,0.00,0.00,completed,Synthetic example — not real transactions
+00020,2026-02-08,002,West,21,12.50,5.00,0.00,completed,
+00021,2026-02-11,010,West,28,16.00,0.00,0.00,completed,
+00022,2026-02-14,011,West,19,32.00,0.00,0.00,completed,
+00023,2026-02-17,020,West,11,24.00,0.00,24.00,completed,
+00024,2026-02-20,021,West,7,65.00,0.00,0.00,completed,
+00025,2026-02-22,001,East,2,38.00,0.00,0.00,cancelled,Excluded by the saved query
+00026,2026-03-01,010,West,7,16.00,0.00,0.00,completed,Outside the default comparison
diff --git a/store/agents/data-studio/template/styles.css b/store/agents/data-studio/template/styles.css
new file mode 100644
index 000000000..7e96ab65a
--- /dev/null
+++ b/store/agents/data-studio/template/styles.css
@@ -0,0 +1,666 @@
+:root {
+ font:
+ 14px/1.5 Inter,
+ ui-sans-serif,
+ system-ui,
+ -apple-system,
+ sans-serif;
+ color: #17392e;
+ background: #f3f5f0;
+ --ink: #17392e;
+ --muted: #647568;
+ --line: #dce3d8;
+ --green: #257952;
+ --pale: #e5eee0;
+ --bad: #9a513d;
+ --surface: #fffef9;
+ color-scheme: light;
+}
+* {
+ box-sizing: border-box;
+}
+body {
+ margin: 0;
+}
+button,
+input,
+select,
+textarea {
+ font: inherit;
+ color: inherit;
+}
+button,
+.button {
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ background: var(--surface);
+ padding: 8px 12px;
+ cursor: pointer;
+ text-decoration: none;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+}
+button:hover,
+.button:hover {
+ background: #e9f0e5;
+}
+button:disabled {
+ opacity: 0.48;
+ cursor: wait;
+}
+.primary {
+ background: var(--ink);
+ color: white;
+ border-color: var(--ink);
+}
+.primary:hover {
+ background: #285840;
+}
+.quiet {
+ background: transparent;
+}
+input,
+select,
+textarea {
+ border: 1px solid #c9d3c5;
+ border-radius: 7px;
+ background: #fff;
+ padding: 8px;
+ max-width: 100%;
+}
+textarea {
+ width: 100%;
+ resize: vertical;
+}
+a {
+ color: var(--green);
+}
+:focus-visible {
+ outline: 3px solid #84aa5e;
+ outline-offset: 3px;
+}
+h1,
+h2,
+h3,
+p {
+ margin-top: 0;
+}
+h1 {
+ font-size: clamp(28px, 3.4vw, 46px);
+ letter-spacing: -1.5px;
+ line-height: 1.1;
+ margin-bottom: 16px;
+}
+h2 {
+ font-size: 20px;
+ letter-spacing: -0.4px;
+ margin-bottom: 10px;
+}
+h3 {
+ font-size: 13px;
+ letter-spacing: 0.02em;
+}
+.muted {
+ color: var(--muted);
+}
+.eyebrow {
+ font:
+ 600 10px/1.5 ui-monospace,
+ monospace;
+ letter-spacing: 1.6px;
+ text-transform: uppercase;
+}
+.topbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 20px;
+ padding: 18px 30px;
+ background: var(--surface);
+ border-bottom: 1px solid var(--line);
+}
+.brand {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ font-weight: 650;
+ font-size: 18px;
+ white-space: nowrap;
+}
+.mark {
+ width: 36px;
+ height: 36px;
+ display: grid;
+ place-items: center;
+ border-radius: 11px;
+ background: var(--ink);
+ color: #c9ee9f;
+}
+.toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+.layout {
+ display: grid;
+ grid-template-columns: 248px minmax(0, 1fr);
+ min-height: calc(100vh - 75px);
+}
+aside {
+ padding: 26px 18px;
+ border-right: 1px solid var(--line);
+ background: #eef2e9;
+}
+main {
+ min-width: 0;
+ max-width: 1600px;
+ padding: 34px 38px 50px;
+ width: 100%;
+ margin: auto;
+}
+.intro {
+ display: flex;
+ justify-content: space-between;
+ gap: 26px;
+ align-items: flex-start;
+}
+.intro p {
+ max-width: 800px;
+}
+.pill {
+ display: inline-block;
+ white-space: nowrap;
+ border: 1px solid #d6ddb1;
+ background: #f3f4d9;
+ color: #727239;
+ border-radius: 20px;
+ font:
+ 600 10px/1.5 ui-monospace,
+ monospace;
+ letter-spacing: 0.5px;
+ padding: 6px 10px;
+}
+.side-section {
+ margin-bottom: 28px;
+}
+.source-button,
+.query-button {
+ display: block;
+ width: 100%;
+ text-align: left;
+ margin: 7px 0;
+ background: transparent;
+ border-color: transparent;
+ padding: 9px 10px;
+}
+.source-button small {
+ display: block;
+ margin-top: 3px;
+ font-size: 10px;
+ color: var(--muted);
+}
+.query-button[aria-pressed="true"] {
+ background: var(--ink);
+ color: white;
+}
+.source-button:hover {
+ background: #e0e9d9;
+}
+.check-count {
+ font-size: 26px;
+ font-weight: 600;
+}
+.side-copy {
+ font-size: 12px;
+ color: var(--muted);
+}
+.status {
+ padding: 12px 18px;
+ border-radius: 8px;
+ background: var(--pale);
+ margin: 14px 0;
+ color: #365440;
+ font-size: 12px;
+ overflow-wrap: anywhere;
+}
+.error {
+ background: #f9e9e2;
+ color: #823c2b;
+}
+.filters {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+ align-items: end;
+ margin: 25px 0;
+}
+.filters label {
+ display: grid;
+ gap: 6px;
+ font-size: 11px;
+ color: var(--muted);
+ font-weight: 600;
+ flex: 1;
+ min-width: 135px;
+}
+.filters input,
+.filters select {
+ width: 100%;
+ font-size: 13px;
+ font-weight: 400;
+ color: var(--ink);
+}
+.metrics {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(148px, 1fr));
+ gap: 12px;
+ margin-bottom: 25px;
+}
+.metric {
+ background: var(--surface);
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ padding: 18px 20px;
+}
+.metric .label {
+ font-size: 11px;
+ color: var(--muted);
+ margin-bottom: 9px;
+ text-transform: capitalize;
+}
+.metric strong {
+ font-size: clamp(20px, 2.1vw, 29px);
+ font-weight: 600;
+ letter-spacing: -0.8px;
+ font-variant-numeric: tabular-nums;
+}
+.metric small {
+ display: block;
+ color: var(--muted);
+ font-size: 10px;
+ margin-top: 5px;
+}
+.panel {
+ background: var(--surface);
+ border: 1px solid var(--line);
+ border-radius: 13px;
+ padding: 24px;
+ margin-bottom: 20px;
+ min-width: 0;
+}
+.panel-head {
+ display: flex;
+ justify-content: space-between;
+ align-items: start;
+ gap: 20px;
+}
+.panel-head p {
+ font-size: 12px;
+ max-width: 800px;
+ color: var(--muted);
+ margin: 0 0 16px;
+}
+.small-tools {
+ display: flex;
+ gap: 7px;
+ flex-wrap: wrap;
+}
+.small-tools button {
+ font-size: 11px;
+ white-space: nowrap;
+}
+.chart {
+ display: grid;
+ gap: 16px;
+ margin: 18px 0 28px;
+}
+.bar-row {
+ display: grid;
+ grid-template-columns: 130px minmax(80px, 1fr) 128px;
+ gap: 14px;
+ align-items: center;
+ width: 100%;
+ padding: 4px;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ font-size: 12px;
+}
+.bar-label {
+ text-align: left;
+}
+.bar-track {
+ height: 28px;
+ background: #eff2eb;
+ position: relative;
+ border-radius: 3px;
+ overflow: hidden;
+}
+.zero {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ border-left: 1px solid #9bae9a;
+}
+.bar {
+ position: absolute;
+ top: 4px;
+ height: 20px;
+ border-radius: 2px;
+ background: #54865c;
+}
+.bar.negative {
+ background: #af7560;
+}
+.bar-value {
+ text-align: right;
+ font:
+ 500 12px/1.4 ui-monospace,
+ monospace;
+}
+.chart-axis {
+ display: flex;
+ justify-content: space-between;
+ margin-left: 148px;
+ margin-right: 145px;
+ color: var(--muted);
+ font:
+ 10px ui-monospace,
+ monospace;
+}
+.null-bar {
+ color: var(--muted);
+ font-style: italic;
+ padding: 4px;
+}
+.table-scroll {
+ overflow: auto;
+ max-height: 480px;
+ border: 1px solid var(--line);
+ border-radius: 8px;
+}
+table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 12px;
+ white-space: nowrap;
+ font-variant-numeric: tabular-nums;
+}
+th,
+td {
+ padding: 11px 13px;
+ text-align: left;
+ border-bottom: 1px solid #e4e9df;
+}
+th {
+ background: #edf2e8;
+ color: #52644f;
+ font-size: 10px;
+ letter-spacing: 0.4px;
+ text-transform: uppercase;
+ position: sticky;
+ top: 0;
+ z-index: 1;
+}
+td.numeric {
+ text-align: right;
+}
+td.missing {
+ color: #88846a;
+ font-style: italic;
+}
+tbody tr:hover {
+ background: #f3f6ef;
+}
+.source-link {
+ border: 0;
+ background: #e9f0e4;
+ border-radius: 4px;
+ padding: 2px 6px;
+ font:
+ 11px ui-monospace,
+ monospace;
+}
+.pagination {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 12px;
+ margin-top: 12px;
+ font-size: 11px;
+ color: var(--muted);
+}
+.pagination button {
+ padding: 5px 10px;
+}
+.empty {
+ padding: 30px;
+ color: var(--muted);
+ text-align: center;
+}
+.bottom-grid {
+ display: grid;
+ grid-template-columns: 1.3fr 1fr;
+ gap: 20px;
+}
+.bottom-grid .panel {
+ margin-bottom: 0;
+}
+.bottom-grid p,
+.bottom-grid li {
+ font-size: 12px;
+ color: var(--muted);
+}
+details summary {
+ cursor: pointer;
+ font-size: 12px;
+ font-weight: 600;
+}
+.sql {
+ font:
+ 12px/1.6 ui-monospace,
+ monospace;
+ tab-size: 2;
+ background: #f7f8f3;
+ margin-top: 14px;
+ min-height: 200px;
+}
+.edit-help {
+ font-size: 11px;
+ color: var(--muted);
+ margin: 10px 0;
+}
+.footer {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 15px;
+ justify-content: space-between;
+ margin-top: 24px;
+ font:
+ 10px ui-monospace,
+ monospace;
+ color: var(--muted);
+}
+dialog {
+ border: 1px solid var(--line);
+ border-radius: 15px;
+ max-width: min(950px, calc(100% - 24px));
+ width: 950px;
+ max-height: 85vh;
+ padding: 26px;
+ color: var(--ink);
+ background: var(--surface);
+}
+dialog::backdrop {
+ background: #16312670;
+}
+.dialog-head {
+ display: flex;
+ align-items: start;
+ justify-content: space-between;
+ gap: 15px;
+}
+pre {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ font-size: 11px;
+}
+#schema {
+ font-size: 12px;
+}
+#schema li {
+ padding: 4px 0;
+}
+#raw-record td {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ max-width: 500px;
+}
+input[type="file"] {
+ display: none;
+}
+.file-button {
+ cursor: pointer;
+}
+.mobile-only {
+ display: none;
+}
+[hidden] {
+ display: none !important;
+}
+@media (max-width: 1000px) {
+ .layout {
+ grid-template-columns: 200px minmax(0, 1fr);
+ }
+ main {
+ padding: 25px 22px;
+ }
+ .topbar {
+ padding: 15px 20px;
+ }
+ .intro {
+ display: block;
+ }
+ .intro .pill {
+ margin-bottom: 15px;
+ }
+ .bottom-grid {
+ grid-template-columns: 1fr;
+ }
+ .metrics {
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
+ }
+ .bar-row {
+ grid-template-columns: 100px minmax(60px, 1fr) 90px;
+ }
+ .chart-axis {
+ margin-left: 118px;
+ margin-right: 107px;
+ }
+}
+@media (max-width: 700px) {
+ .topbar {
+ display: block;
+ padding: 15px;
+ }
+ .toolbar {
+ margin-top: 12px;
+ }
+ .toolbar button,
+ .toolbar .button {
+ font-size: 11px;
+ padding: 7px 9px;
+ }
+ .layout {
+ display: block;
+ }
+ aside {
+ border-right: 0;
+ border-bottom: 1px solid var(--line);
+ padding: 14px 15px;
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 15px;
+ }
+ .side-section {
+ margin: 0;
+ }
+ aside .health {
+ display: none;
+ }
+ .query-button,
+ .source-button {
+ font-size: 11px;
+ padding: 5px;
+ }
+ .source-button small {
+ font-size: 9px;
+ }
+ main {
+ padding: 22px 15px;
+ }
+ .intro .pill {
+ margin-bottom: 10px;
+ }
+ h1 {
+ font-size: 31px;
+ letter-spacing: -1px;
+ }
+ .intro p {
+ font-size: 12px;
+ }
+ .metrics {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+ }
+ .metric {
+ padding: 13px;
+ }
+ .metric strong {
+ font-size: 22px;
+ }
+ .panel {
+ padding: 16px;
+ }
+ .panel-head {
+ display: block;
+ }
+ .small-tools {
+ margin-bottom: 15px;
+ }
+ .bar-row {
+ grid-template-columns: 75px minmax(30px, 1fr) 78px;
+ gap: 8px;
+ font-size: 11px;
+ }
+ .bar-value {
+ font-size: 10px;
+ }
+ .chart-axis {
+ margin-left: 87px;
+ margin-right: 90px;
+ }
+ .filters {
+ gap: 8px;
+ }
+ .filters label {
+ min-width: 120px;
+ }
+ .filters button {
+ padding: 8px;
+ }
+ .pagination {
+ flex-wrap: wrap;
+ }
+ .footer {
+ font-size: 9px;
+ }
+ .bottom-grid {
+ gap: 14px;
+ }
+ dialog {
+ padding: 17px;
+ }
+}
diff --git a/store/agents/data-studio/template/tools/archive.mjs b/store/agents/data-studio/template/tools/archive.mjs
new file mode 100644
index 000000000..8f5d3f605
--- /dev/null
+++ b/store/agents/data-studio/template/tools/archive.mjs
@@ -0,0 +1,179 @@
+// Small, bounded, deterministic ZIP writer. No global npm or Python dependency.
+import { deflateRawSync, inflateRawSync } from "node:zlib";
+const table = Uint32Array.from({ length: 256 }, (_, value) => {
+ for (let i = 0; i < 8; i++)
+ value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
+ return value >>> 0;
+});
+function crc32(bytes) {
+ let crc = 0xffffffff;
+ for (const byte of bytes) crc = table[(crc ^ byte) & 255] ^ (crc >>> 8);
+ return (crc ^ 0xffffffff) >>> 0;
+}
+export function zip(files) {
+ if (!files.length || files.length > 256)
+ throw new Error("Archive needs 1–256 files.");
+ const chunks = [],
+ central = [],
+ names = new Set();
+ let offset = 0,
+ total = 0;
+ for (const { name, bytes: input } of files) {
+ if (
+ !/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(name) ||
+ name.split("/").some((p) => !p || p === "." || p === "..") ||
+ names.has(name.toLowerCase())
+ )
+ throw new Error("Unsafe or duplicate archive path: " + name);
+ names.add(name.toLowerCase());
+ const bytes = Buffer.from(input),
+ filename = Buffer.from(name),
+ compressed = deflateRawSync(bytes),
+ crc = crc32(bytes);
+ total += bytes.length;
+ if (total > 128 * 1024 * 1024)
+ throw new Error("Portable project exceeds 128 MiB uncompressed.");
+ const header = Buffer.alloc(30);
+ header.writeUInt32LE(0x04034b50, 0);
+ header.writeUInt16LE(20, 4);
+ header.writeUInt16LE(0x800, 6);
+ header.writeUInt16LE(8, 8);
+ header.writeUInt16LE(33, 12);
+ header.writeUInt32LE(crc, 14);
+ header.writeUInt32LE(compressed.length, 18);
+ header.writeUInt32LE(bytes.length, 22);
+ header.writeUInt16LE(filename.length, 26);
+ const entry = Buffer.alloc(46);
+ entry.writeUInt32LE(0x02014b50, 0);
+ entry.writeUInt16LE(20, 4);
+ entry.writeUInt16LE(20, 6);
+ entry.writeUInt16LE(0x800, 8);
+ entry.writeUInt16LE(8, 10);
+ entry.writeUInt16LE(33, 14);
+ entry.writeUInt32LE(crc, 16);
+ entry.writeUInt32LE(compressed.length, 20);
+ entry.writeUInt32LE(bytes.length, 24);
+ entry.writeUInt16LE(filename.length, 28);
+ entry.writeUInt32LE(offset, 42);
+ chunks.push(header, filename, compressed);
+ central.push(entry, filename);
+ offset += header.length + filename.length + compressed.length;
+ }
+ const directory = Buffer.concat(central),
+ end = Buffer.alloc(22);
+ end.writeUInt32LE(0x06054b50, 0);
+ end.writeUInt16LE(files.length, 8);
+ end.writeUInt16LE(files.length, 10);
+ end.writeUInt32LE(directory.length, 12);
+ end.writeUInt32LE(offset, 16);
+ const output = Buffer.concat([...chunks, directory, end]);
+ if (output.length > 32 * 1024 * 1024)
+ throw new Error("Portable project exceeds the 32 MiB download limit.");
+ return output;
+}
+
+// Read ZIP members in memory, never extract paths. Used for independently reopening portable projects.
+export function unzip(input) {
+ const data = Buffer.from(input);
+ if (data.length > 32 * 1024 * 1024) throw new Error("ZIP exceeds 32 MiB.");
+ let end = -1;
+ for (let p = data.length - 22; p >= Math.max(0, data.length - 65557); p--)
+ if (
+ data.readUInt32LE(p) === 0x06054b50 &&
+ p + 22 + data.readUInt16LE(p + 20) === data.length
+ ) {
+ end = p;
+ break;
+ }
+ if (end < 0) throw new Error("Missing ZIP directory.");
+ const count = data.readUInt16LE(end + 10),
+ size = data.readUInt32LE(end + 12),
+ start = data.readUInt32LE(end + 16);
+ if (
+ data.readUInt16LE(end + 4) ||
+ data.readUInt16LE(end + 6) ||
+ count !== data.readUInt16LE(end + 8) ||
+ !count ||
+ count > 256 ||
+ start + size !== end
+ )
+ throw new Error("Unsupported ZIP directory.");
+ const result = new Map(),
+ seen = new Set(),
+ ranges = [];
+ let cursor = start,
+ total = 0;
+ for (let i = 0; i < count; i++) {
+ if (cursor + 46 > end || data.readUInt32LE(cursor) !== 0x02014b50)
+ throw new Error("Invalid ZIP entry.");
+ const flags = data.readUInt16LE(cursor + 8),
+ method = data.readUInt16LE(cursor + 10),
+ crc = data.readUInt32LE(cursor + 16),
+ compressed = data.readUInt32LE(cursor + 20),
+ length = data.readUInt32LE(cursor + 24),
+ n = data.readUInt16LE(cursor + 28),
+ extra = data.readUInt16LE(cursor + 30),
+ comment = data.readUInt16LE(cursor + 32),
+ offset = data.readUInt32LE(cursor + 42);
+ if (
+ flags & 1 ||
+ ![0, 8].includes(method) ||
+ compressed === 0xffffffff ||
+ length === 0xffffffff ||
+ offset === 0xffffffff ||
+ data.readUInt16LE(cursor + 34)
+ )
+ throw new Error("Encrypted, split or ZIP64 files are unsupported.");
+ if (cursor + 46 + n + extra + comment > end)
+ throw new Error("Truncated ZIP entry.");
+ const name = data.subarray(cursor + 46, cursor + 46 + n).toString("utf8"),
+ key = name.toLowerCase();
+ if (
+ !name ||
+ name.includes("\\") ||
+ name.includes("\0") ||
+ name.startsWith("/") ||
+ name.includes(":") ||
+ name.split("/").some((v) => v === "." || v === ".." || !v) ||
+ seen.has(key)
+ )
+ throw new Error("Unsafe or duplicate ZIP path.");
+ if (((data.readUInt32LE(cursor + 38) >>> 16) & 0xf000) === 0xa000)
+ throw new Error("ZIP symlinks are unsupported.");
+ seen.add(key);
+ total += length;
+ if (total > 128 * 1024 * 1024)
+ throw new Error("Expanded ZIP exceeds 128 MiB.");
+ if (
+ offset + 30 > start ||
+ data.readUInt32LE(offset) !== 0x04034b50 ||
+ data.readUInt16LE(offset + 6) !== flags ||
+ data.readUInt16LE(offset + 8) !== method
+ )
+ throw new Error("ZIP local header mismatch.");
+ const ln = data.readUInt16LE(offset + 26),
+ le = data.readUInt16LE(offset + 28),
+ body = offset + 30 + ln + le,
+ finish = body + compressed;
+ if (
+ finish > start ||
+ !data.subarray(offset + 30, offset + 30 + ln).equals(Buffer.from(name))
+ )
+ throw new Error("ZIP member bounds/name mismatch.");
+ if (ranges.some(([a, b]) => offset < b && finish > a))
+ throw new Error("Overlapping ZIP members.");
+ ranges.push([offset, finish]);
+ const bytes =
+ method === 0
+ ? data.subarray(body, finish)
+ : inflateRawSync(data.subarray(body, finish), {
+ maxOutputLength: Math.max(1, length),
+ });
+ if (bytes.length !== length || crc32(bytes) !== crc)
+ throw new Error("ZIP member checksum mismatch.");
+ result.set(name, bytes);
+ cursor += 46 + n + extra + comment;
+ }
+ if (cursor !== end) throw new Error("Unexpected ZIP directory data.");
+ return result;
+}
diff --git a/store/agents/data-studio/template/tools/build.mjs b/store/agents/data-studio/template/tools/build.mjs
new file mode 100644
index 000000000..469e69070
--- /dev/null
+++ b/store/agents/data-studio/template/tools/build.mjs
@@ -0,0 +1,286 @@
+import {
+ readFile,
+ readdir,
+ lstat,
+ realpath,
+ writeFile,
+ mkdir,
+} from "node:fs/promises";
+import { join, resolve, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+import { spawnSync } from "node:child_process";
+import { DatabaseSync } from "node:sqlite";
+import { zip } from "./archive.mjs";
+import {
+ source,
+ snapshot,
+ unchanged,
+ save,
+ sha,
+ json,
+ publish,
+ transaction,
+ exists,
+} from "./files.mjs";
+import { revision } from "./engine-node.mjs";
+import "../core.js";
+import "../report.js";
+const C = globalThis.DataStudioCore;
+export const runtimeFiles = [
+ "index.html",
+ "dashboard.mjs",
+ "styles.css",
+ "core.js",
+ "worker.js",
+ "report.js",
+ "proof.json",
+ "vendor/sqlite3.js",
+ "vendor/sqlite3.wasm",
+ "vendor/NOTICE.md",
+ "vendor/checksums.json",
+ "vendor/EMSCRIPTEN-LICENSE.txt",
+ "vendor/MUSL-COPYRIGHT.txt",
+ "tools/build.mjs",
+ "tools/calculate.mjs",
+ "tools/engine-node.mjs",
+ "tools/files.mjs",
+ "tools/archive.mjs",
+ "tools/restore.mjs",
+ "tools/serve.mjs",
+ "PROJECT.md",
+ "LICENSE",
+];
+const decode = (bytes) =>
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);
+export async function loadBundle(workspace) {
+ const config = JSON.parse(decode(await source(workspace, "analysis.json")));
+ C.validateConfig(config);
+ const names = [
+ "analysis.json",
+ ...config.tables.map((t) => t.file),
+ ...[...new Set([...config.queries, ...config.checks].map((q) => q.file))],
+ ];
+ if (names.some((n) => !C.path(n))) throw new Error("Unsafe source path.");
+ if (await exists(join(workspace, "view.json"))) names.push("view.json");
+ const files = await snapshot(workspace, names),
+ data = Object.fromEntries(files.map((f) => [f.name, decode(f.bytes)]));
+ // Use the snapshotted config, never a separately read copy that could change mid-build.
+ if (
+ data["analysis.json"] !== JSON.stringify(config) &&
+ C.stable(JSON.parse(data["analysis.json"])) !== C.stable(config)
+ )
+ throw new Error("Analysis changed while discovering its files.");
+ const bundle = {
+ config,
+ sources: Object.fromEntries(
+ config.tables.map((t) => [t.file, data[t.file]]),
+ ),
+ sql: Object.fromEntries(
+ [...config.queries, ...config.checks].map((q) => [q.file, data[q.file]]),
+ ),
+ };
+ const view = data["view.json"]
+ ? JSON.parse(data["view.json"])
+ : {
+ parameters: {},
+ notes: "",
+ selectedQuery:
+ config.queries.find((q) => q.kind !== "metric")?.id ??
+ config.queries[0].id,
+ };
+ C.validateView(view, config);
+ return { bundle, view, files };
+}
+function reopened(database, bundle, report) {
+ const db = new DatabaseSync(database, {
+ readOnly: true,
+ allowExtension: false,
+ enableDoubleQuotedStringLiterals: false,
+ });
+ try {
+ db.exec("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF");
+ if (db.prepare("PRAGMA integrity_check").get().integrity_check !== "ok")
+ throw new Error("Saved SQLite database did not reopen intact.");
+ for (const q of bundle.config.queries) {
+ const stmt = db.prepare(bundle.sql[q.file]);
+ stmt.setReadBigInts(true);
+ const names = C.validateSQL(bundle.sql[q.file], bundle.config),
+ bind = Object.fromEntries(
+ names.map((n) => [":" + n, report.parameters[n]]),
+ ),
+ cols = stmt.columns().map((c) => c.name),
+ rows = [];
+ for (const r of stmt.iterate(bind)) {
+ rows.push(cols.map((c) => C.scalar(r[c])));
+ if (rows.length > C.LIMITS.resultRows)
+ throw new Error("Reopened query exceeds limit.");
+ }
+ if (
+ C.stable(C.result(cols, rows, q)) !==
+ C.stable(report.results.find((r) => r.id === q.id))
+ )
+ throw new Error("Reopened database disagrees with " + q.id);
+ }
+ } finally {
+ db.close();
+ }
+}
+export async function build(input) {
+ const workspace = await realpath(resolve(input));
+ return transaction(workspace, async ({ state, stage, verdict }) => {
+ const { bundle, view, files } = await loadBundle(workspace);
+ C.prepare(bundle);
+ const assets = await snapshot(workspace, runtimeFiles);
+ const vendor = JSON.parse(
+ decode(assets.find((f) => f.name === "vendor/checksums.json").bytes),
+ );
+ for (const name of ["sqlite3.js", "sqlite3.wasm"])
+ if (
+ sha(assets.find((f) => f.name === "vendor/" + name).bytes) !==
+ vendor[name]
+ )
+ throw new Error("SQLite vendor checksum mismatch: " + name);
+ const output = join(stage, "output");
+ await mkdir(output);
+ await writeFile(
+ join(stage, "input.json"),
+ json({ bundle, parameters: view.parameters }),
+ );
+ const child = spawnSync(
+ process.execPath,
+ [
+ "--max-old-space-size=256",
+ fileURLToPath(new URL("./calculate.mjs", import.meta.url)),
+ join(stage, "input.json"),
+ join(output, "analysis-result.json"),
+ join(output, "analysis.sqlite"),
+ ],
+ { encoding: "utf8", timeout: 20000, maxBuffer: 1024 * 1024 },
+ );
+ if (child.error || child.status !== 0)
+ throw new Error(
+ "Analysis failed: " +
+ (child.error?.code === "ETIMEDOUT"
+ ? "20-second query budget exceeded"
+ : child.stderr.trim() || child.error?.message || "worker exited"),
+ );
+ const report = JSON.parse(
+ await readFile(join(output, "analysis-result.json"), "utf8"),
+ );
+ // The independent reopen is also bounded. Never execute user SQL in the parent process.
+ const verify = spawnSync(
+ process.execPath,
+ [
+ "--max-old-space-size=256",
+ fileURLToPath(import.meta.url),
+ "--reopen",
+ join(output, "analysis.sqlite"),
+ join(stage, "input.json"),
+ join(output, "analysis-result.json"),
+ ],
+ { encoding: "utf8", timeout: 20000, maxBuffer: 1024 * 1024 },
+ );
+ if (verify.error || verify.status !== 0)
+ throw new Error(
+ "Independent SQLite reopen failed: " +
+ (verify.stderr.trim() || verify.error?.message),
+ );
+ report.checks.push({
+ id: "reopen",
+ passed: true,
+ description:
+ "Saved SQLite file reopened read-only; every query reproduced exactly.",
+ });
+ C.verifyLinks(bundle, report.results);
+ report.checks.push({
+ id: "source_links",
+ passed: true,
+ description:
+ "Every declared source-record link resolves to a real input record.",
+ });
+ report.artifacts = {
+ database: sha(await readFile(join(output, "analysis.sqlite"))),
+ };
+ report.runtime = Object.fromEntries(
+ assets.map((f) => [f.name, sha(f.bytes)]),
+ );
+ await writeFile(join(output, "analysis-result.json"), json(report));
+ const project = {
+ format: "data-studio",
+ spec: 1,
+ revision: revision(bundle),
+ bundle,
+ view: { ...view, parameters: report.parameters },
+ };
+ await writeFile(join(output, "project.data-studio.json"), json(project));
+ await writeFile(
+ join(output, "report.html"),
+ globalThis.DataStudioReport(bundle, report, view.notes),
+ );
+ for (const r of report.results)
+ await writeFile(join(output, r.id + ".csv"), C.csv(r.columns, r.rows));
+ const manifest = {
+ spec: 1,
+ revision: report.revision,
+ parameters: report.parameters,
+ inputs: Object.fromEntries(files.map((f) => [f.name, sha(f.bytes)])),
+ outputs: {},
+ };
+ const outputFiles = [];
+ for (const name of await readdir(output)) {
+ const bytes = await readFile(join(output, name));
+ manifest.outputs[name] = sha(bytes);
+ outputFiles.push({ name: "output/" + name, bytes });
+ }
+ await writeFile(join(output, "manifest.json"), json(manifest));
+ outputFiles.push({
+ name: "output/manifest.json",
+ bytes: Buffer.from(json(manifest)),
+ });
+ await writeFile(
+ join(output, "project.zip"),
+ zip([...files, ...assets, ...outputFiles]),
+ );
+ await unchanged(workspace, [...files, ...assets]);
+ const history = await publish(workspace, state, stage, ["output"]);
+ await save(join(state, "analysis-result.json"), json(report));
+ await verdict({
+ summary:
+ "Analysis built: " +
+ report.records +
+ " source records, " +
+ report.results.length +
+ " queries, " +
+ report.checks.length +
+ " checks. Browser interaction proof still required.",
+ artifact: "index.html",
+ });
+ return {
+ revision: report.revision,
+ records: report.records,
+ queries: report.results.length,
+ checks: report.checks.length,
+ output: join(workspace, "output"),
+ history,
+ };
+ });
+}
+if (
+ process.argv[1] &&
+ (await realpath(process.argv[1])) === fileURLToPath(import.meta.url)
+) {
+ try {
+ if (process.argv[2] === "--reopen") {
+ const input = JSON.parse(await readFile(process.argv[4], "utf8")),
+ report = JSON.parse(await readFile(process.argv[5], "utf8"));
+ reopened(process.argv[3], input.bundle, report);
+ console.log("Saved database queries reproduced.");
+ } else
+ console.log(
+ JSON.stringify(await build(process.argv[2] || process.cwd()), null, 2),
+ );
+ } catch (error) {
+ console.error(error.message);
+ process.exitCode = 1;
+ }
+}
diff --git a/store/agents/data-studio/template/tools/calculate.mjs b/store/agents/data-studio/template/tools/calculate.mjs
new file mode 100644
index 000000000..df33e03fd
--- /dev/null
+++ b/store/agents/data-studio/template/tools/calculate.mjs
@@ -0,0 +1,14 @@
+// Run in a bounded child process; an expensive query cannot hang the parent build.
+import { readFile, writeFile } from "node:fs/promises";
+import { runAnalysis } from "./engine-node.mjs";
+const [input, output, database] = process.argv.slice(2);
+try {
+ const { bundle, parameters } = JSON.parse(await readFile(input, "utf8"));
+ await writeFile(
+ output,
+ JSON.stringify(runAnalysis(bundle, parameters, database)),
+ );
+} catch (error) {
+ console.error(error.message);
+ process.exitCode = 1;
+}
diff --git a/store/agents/data-studio/template/tools/engine-node.mjs b/store/agents/data-studio/template/tools/engine-node.mjs
new file mode 100644
index 000000000..a43eaf996
--- /dev/null
+++ b/store/agents/data-studio/template/tools/engine-node.mjs
@@ -0,0 +1,116 @@
+import { DatabaseSync } from "node:sqlite";
+import { createHash } from "node:crypto";
+import "../core.js";
+const C = globalThis.DataStudioCore;
+const quoted = (name) => '"' + name.replaceAll('"', '""') + '"';
+export const revision = (bundle) =>
+ createHash("sha256").update(C.stable(bundle)).digest("hex");
+export function runAnalysis(bundle, input = {}, database = ":memory:") {
+ const prepared = C.prepare(bundle),
+ values = C.parameters(prepared.config, input),
+ db = new DatabaseSync(database, {
+ allowExtension: false,
+ enableDoubleQuotedStringLiterals: false,
+ });
+ try {
+ db.exec(
+ "PRAGMA hard_heap_limit=134217728; PRAGMA trusted_schema=OFF; PRAGMA temp_store=MEMORY; PRAGMA journal_mode=DELETE; BEGIN",
+ );
+ for (const t of prepared.tables) {
+ db.exec(
+ "CREATE TABLE " +
+ quoted(t.id) +
+ " (_record INTEGER PRIMARY KEY," +
+ t.columns
+ .map(
+ (c) =>
+ quoted(c.name) +
+ " " +
+ (["text", "date"].includes(c.type)
+ ? "TEXT"
+ : c.type === "real"
+ ? "REAL"
+ : "INTEGER") +
+ (c.nullable ? "" : " NOT NULL"),
+ )
+ .join(",") +
+ (t.key ? ", UNIQUE (" + t.key.map(quoted).join(",") + ")" : "") +
+ ") STRICT",
+ );
+ const insert = db.prepare(
+ "INSERT INTO " +
+ quoted(t.id) +
+ " VALUES (" +
+ Array(t.columns.length + 1)
+ .fill("?")
+ .join(",") +
+ ")",
+ );
+ for (const row of t.rows) insert.run(...row);
+ }
+ db.exec("COMMIT; PRAGMA query_only=ON");
+ const execute = (q) => {
+ const sql = bundle.sql[q.file],
+ names = C.validateSQL(sql, prepared.config),
+ stmt = db.prepare(sql);
+ stmt.setReadBigInts(true);
+ const bind = Object.fromEntries(names.map((n) => [":" + n, values[n]])),
+ columns = stmt.columns().map((c) => c.name),
+ rows = [];
+ let size = 0;
+ for (const row of stmt.iterate(bind)) {
+ const a = columns.map((c) => C.scalar(row[c]));
+ rows.push(a);
+ size += JSON.stringify(a).length;
+ if (rows.length > C.LIMITS.resultRows || size > C.LIMITS.resultBytes)
+ throw new Error(q.id + ": query result limit exceeded.");
+ }
+ return C.result(columns, rows, q);
+ };
+ let resultBytes = 0;
+ const results = prepared.config.queries.map((q) => {
+ const r = execute(q);
+ resultBytes += Buffer.byteLength(JSON.stringify(r));
+ if (resultBytes > C.LIMITS.totalResultBytes)
+ throw new Error("Combined results exceed 8 MiB.");
+ return r;
+ }),
+ checks = [...prepared.checks];
+ for (const q of prepared.config.checks) {
+ const r = execute(q);
+ if (
+ r.columns.length !== 1 ||
+ r.columns[0] !== "violations" ||
+ r.rows.length !== 1 ||
+ r.rows[0][0] !== 0
+ )
+ throw new Error(
+ q.description + ": expected exactly one violations=0 result.",
+ );
+ checks.push({ id: q.id, description: q.description, passed: true });
+ }
+ if (db.prepare("PRAGMA integrity_check").get().integrity_check !== "ok")
+ throw new Error("SQLite integrity check failed.");
+ checks.push({
+ id: "integrity",
+ description: "Native SQLite integrity_check: ok",
+ passed: true,
+ });
+ return {
+ spec: 1,
+ revision: revision(bundle),
+ engine:
+ "Node " +
+ process.versions.node +
+ " / SQLite " +
+ db.prepare("SELECT sqlite_version() version").get().version,
+ parameters: values,
+ results,
+ checks,
+ records: prepared.rowCount,
+ sourceBytes: prepared.sourceBytes,
+ };
+ } finally {
+ db.close();
+ }
+}
diff --git a/store/agents/data-studio/template/tools/files.mjs b/store/agents/data-studio/template/tools/files.mjs
new file mode 100644
index 000000000..dbec0202f
--- /dev/null
+++ b/store/agents/data-studio/template/tools/files.mjs
@@ -0,0 +1,165 @@
+import {
+ readFile,
+ writeFile,
+ mkdir,
+ mkdtemp,
+ lstat,
+ realpath,
+ rename,
+ copyFile,
+ rm,
+} from "node:fs/promises";
+import { createHash } from "node:crypto";
+import { join, dirname, basename, sep } from "node:path";
+export const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
+export const json = (value) => JSON.stringify(value, null, 2) + "\n";
+export async function exists(path) {
+ try {
+ await lstat(path);
+ return true;
+ } catch (error) {
+ if (error.code === "ENOENT") return false;
+ throw error;
+ }
+}
+export async function source(workspace, name) {
+ let path = workspace;
+ for (const component of name.split("/")) {
+ path = join(path, component);
+ if ((await lstat(path)).isSymbolicLink())
+ throw new Error("Source symlinks are not portable: " + name);
+ }
+ const info = await lstat(path);
+ if (!info.isFile() || info.size > 32 * 1024 * 1024)
+ throw new Error(
+ "Source must be a regular file no larger than 32 MiB: " + name,
+ );
+ if (!(await realpath(path)).startsWith((await realpath(workspace)) + sep))
+ throw new Error("Source escapes workspace: " + name);
+ return readFile(path);
+}
+export async function snapshot(workspace, names) {
+ const files = [];
+ let total = 0;
+ for (const name of names) {
+ const bytes = await source(workspace, name);
+ total += bytes.length;
+ files.push({ name, bytes });
+ }
+ if (total > 64 * 1024 * 1024) throw new Error("Sources exceed 64 MiB.");
+ return files;
+}
+export async function unchanged(workspace, files) {
+ for (const file of files)
+ if (sha(await source(workspace, file.name)) !== sha(file.bytes))
+ throw new Error(
+ "Source changed during build; rebuild the saved project: " + file.name,
+ );
+}
+export async function save(path, bytes) {
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, bytes);
+}
+export async function atomic(path, bytes) {
+ const temp = path + "." + process.pid + ".tmp";
+ await writeFile(temp, bytes);
+ await rename(temp, path);
+}
+export async function publish(workspace, state, stage, names) {
+ if (
+ (await exists(join(state, "history"))) &&
+ (await lstat(join(state, "history"))).isSymbolicLink()
+ )
+ throw new Error("History must not be a symlink.");
+ const history = join(state, "history", basename(stage));
+ await mkdir(history, { recursive: true });
+ const saved = [],
+ installed = [];
+ try {
+ if (await exists(join(state, "analysis-result.json")))
+ await copyFile(
+ join(state, "analysis-result.json"),
+ join(history, "analysis-result.json"),
+ );
+ for (const name of names) {
+ if (await exists(join(workspace, name))) {
+ await rename(join(workspace, name), join(history, name));
+ saved.push(name);
+ }
+ await rename(join(stage, name), join(workspace, name));
+ installed.push(name);
+ }
+ return history;
+ } catch (error) {
+ const failures = [];
+ for (const name of installed.reverse())
+ try {
+ await rename(join(workspace, name), join(stage, name));
+ } catch (error) {
+ failures.push(error.message);
+ }
+ for (const name of saved.reverse())
+ try {
+ await rename(join(history, name), join(workspace, name));
+ } catch (error) {
+ failures.push(error.message);
+ }
+ if (failures.length)
+ throw new Error(
+ "Publication failed; recover saved artifacts from " +
+ history +
+ ": " +
+ failures.join("; "),
+ );
+ throw error;
+ }
+}
+export async function transaction(workspace, run) {
+ const state = join(workspace, ".harness");
+ if ((await exists(state)) && (await lstat(state)).isSymbolicLink())
+ throw new Error(".harness must not be a symlink.");
+ await mkdir(state, { recursive: true });
+ const lock = join(state, "data-build.lock");
+ try {
+ await mkdir(lock);
+ } catch (error) {
+ if (error.code === "EEXIST")
+ throw new Error(
+ "Another build owns .harness/data-build.lock. Confirm its process has stopped before removing a stale lock.",
+ );
+ throw error;
+ }
+ let stage;
+ const verdict = (value) =>
+ atomic(
+ join(state, "verdict.json"),
+ json({
+ spec: 1,
+ ready: false,
+ findings: [],
+ artifact: null,
+ ...value,
+ updatedAt: new Date().toISOString(),
+ }),
+ );
+ try {
+ await writeFile(
+ join(lock, "owner.json"),
+ json({ pid: process.pid, startedAt: new Date().toISOString() }),
+ );
+ await verdict({
+ summary: "Building typed data and checking saved analysis rules",
+ });
+ stage = await mkdtemp(join(state, "data-"));
+ return await run({ state, stage, verdict });
+ } catch (error) {
+ await verdict({
+ summary: "Data Studio build failed",
+ findings: [{ severity: "error", kind: "build", message: error.message }],
+ });
+ throw error;
+ } finally {
+ if (stage) await rm(stage, { recursive: true, force: true });
+ await rm(lock, { recursive: true, force: true });
+ }
+}
diff --git a/store/agents/data-studio/template/tools/restore.mjs b/store/agents/data-studio/template/tools/restore.mjs
new file mode 100644
index 000000000..5a4131b5f
--- /dev/null
+++ b/store/agents/data-studio/template/tools/restore.mjs
@@ -0,0 +1,84 @@
+// Restore a downloaded JSON project into a NEW or empty directory. Never overwrite work.
+import {
+ mkdir,
+ readdir,
+ writeFile,
+ readFile,
+ copyFile,
+ lstat,
+ realpath,
+} from "node:fs/promises";
+import { resolve, join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+import { runtimeFiles } from "./build.mjs";
+import { revision } from "./engine-node.mjs";
+import "../core.js";
+const C = globalThis.DataStudioCore;
+export async function restore(projectFile, target) {
+ const info = await lstat(projectFile);
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 12 * 1024 * 1024)
+ throw new Error("Project must be a regular JSON file at most 12 MiB.");
+ const p = C.validateProject(
+ JSON.parse(
+ new TextDecoder("utf-8", { fatal: true }).decode(
+ await readFile(projectFile),
+ ),
+ ),
+ );
+ if (revision(p.bundle) !== p.revision)
+ throw new Error(
+ "Project revision checksum does not match its sources and queries.",
+ );
+ const output = resolve(target),
+ root = fileURLToPath(new URL("../", import.meta.url));
+ try {
+ const info = await lstat(output);
+ if (
+ !info.isDirectory() ||
+ info.isSymbolicLink() ||
+ (await readdir(output)).length
+ )
+ throw new Error("Restore target must be a new or empty directory.");
+ } catch (e) {
+ if (e.code !== "ENOENT") throw e;
+ }
+ await mkdir(output, { recursive: true });
+ const files = {
+ "analysis.json": JSON.stringify(p.bundle.config, null, 2) + "\n",
+ "view.json": JSON.stringify(p.view, null, 2) + "\n",
+ ...p.bundle.sources,
+ ...p.bundle.sql,
+ };
+ if (Object.keys(files).some((n) => !C.path(n) || runtimeFiles.includes(n)))
+ throw new Error("Project path conflicts with runtime files.");
+ for (const [name, text] of Object.entries(files)) {
+ await mkdir(dirname(join(output, name)), { recursive: true });
+ await writeFile(join(output, name), text, { flag: "wx" });
+ }
+ for (const name of runtimeFiles) {
+ await mkdir(dirname(join(output, name)), { recursive: true });
+ await copyFile(join(root, name), join(output, name), 1);
+ }
+ return {
+ workspace: output,
+ revision: p.revision,
+ next: "Run node tools/build.mjs in the restored directory.",
+ };
+}
+if (
+ process.argv[1] &&
+ (await realpath(process.argv[1])) === fileURLToPath(import.meta.url)
+) {
+ try {
+ if (process.argv.length !== 4)
+ throw new Error(
+ "Usage: node tools/restore.mjs saved.data-studio.json NEW_DIRECTORY",
+ );
+ console.log(
+ JSON.stringify(await restore(process.argv[2], process.argv[3]), null, 2),
+ );
+ } catch (e) {
+ console.error(e.message);
+ process.exitCode = 1;
+ }
+}
diff --git a/store/agents/data-studio/template/tools/serve.mjs b/store/agents/data-studio/template/tools/serve.mjs
new file mode 100644
index 000000000..4238dcdd8
--- /dev/null
+++ b/store/agents/data-studio/template/tools/serve.mjs
@@ -0,0 +1,108 @@
+// Read-only loopback preview for an extracted portable project. No upload/SQL endpoint.
+import { createServer } from "node:http";
+import { readFile, realpath, lstat } from "node:fs/promises";
+import { resolve, join, extname, sep } from "node:path";
+import { fileURLToPath } from "node:url";
+import { randomBytes } from "node:crypto";
+const mime = {
+ ".html": "text/html; charset=utf-8",
+ ".mjs": "text/javascript",
+ ".js": "text/javascript",
+ ".css": "text/css",
+ ".json": "application/json",
+ ".wasm": "application/wasm",
+ ".zip": "application/zip",
+ ".csv": "text/csv",
+ ".sqlite": "application/vnd.sqlite3",
+};
+export async function createPreview(workspace) {
+ const root = await realpath(workspace),
+ token = randomBytes(24).toString("hex"),
+ prefix = "/" + token + "/";
+ const allowed = new Set([
+ "index.html",
+ "dashboard.mjs",
+ "styles.css",
+ "core.js",
+ "worker.js",
+ "report.js",
+ "vendor/sqlite3.js",
+ "vendor/sqlite3.wasm",
+ "vendor/checksums.json",
+ "output/project.data-studio.json",
+ "output/analysis-result.json",
+ "output/analysis.sqlite",
+ "output/report.html",
+ "output/project.zip",
+ "output/manifest.json",
+ ]);
+ const server = createServer(async (req, res) => {
+ res.setHeader("cache-control", "no-store");
+ res.setHeader("x-content-type-options", "nosniff");
+ res.setHeader("referrer-policy", "no-referrer");
+ res.setHeader(
+ "content-security-policy",
+ "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; worker-src blob:; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
+ );
+ const end = (status, body) => {
+ res.writeHead(status, { "content-type": "text/plain" });
+ res.end(req.method === "HEAD" ? undefined : body);
+ };
+ if (!/^(localhost|127\.0\.0\.1)(:\d+)?$/.test(req.headers.host ?? ""))
+ return end(403, "Loopback only.");
+ if (!["GET", "HEAD"].includes(req.method)) return end(405, "Read only.");
+ let name;
+ try {
+ const path = decodeURIComponent(
+ new URL(req.url, "http://127.0.0.1").pathname,
+ );
+ if (!path.startsWith(prefix)) return end(404, "Not found.");
+ name = path.slice(prefix.length) || "index.html";
+ } catch {
+ return end(400, "Invalid path.");
+ }
+ if (!allowed.has(name)) return end(404, "Not found.");
+ try {
+ let file = root;
+ for (const part of name.split("/")) {
+ file = join(file, part);
+ if ((await lstat(file)).isSymbolicLink()) return end(404, "Not found.");
+ }
+ if (!(await realpath(file)).startsWith(root + sep))
+ return end(404, "Not found.");
+ const st = await lstat(file);
+ if (!st.isFile() || st.size > 32 * 1024 * 1024)
+ return end(413, "File limit.");
+ const bytes = await readFile(file);
+ res.writeHead(200, {
+ "content-type": mime[extname(name)] ?? "application/octet-stream",
+ });
+ res.end(req.method === "HEAD" ? undefined : bytes);
+ } catch {
+ return end(404, "Not built yet. Run node tools/build.mjs.");
+ }
+ });
+ server.previewPrefix = prefix;
+ return server;
+}
+if (
+ process.argv[1] &&
+ (await realpath(process.argv[1])) === fileURLToPath(import.meta.url)
+) {
+ const port = Number(process.argv[3] || 0);
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
+ throw new Error("Invalid port.");
+ const server = await createPreview(resolve(process.argv[2] || process.cwd()));
+ server.listen(port, "127.0.0.1", () =>
+ console.log(
+ "Data Studio: http://127.0.0.1:" +
+ server.address().port +
+ server.previewPrefix,
+ ),
+ );
+ for (const signal of ["SIGINT", "SIGTERM"])
+ process.once(signal, () => {
+ server.closeAllConnections();
+ server.close();
+ });
+}
diff --git a/store/agents/data-studio/template/vendor/EMSCRIPTEN-LICENSE.txt b/store/agents/data-studio/template/vendor/EMSCRIPTEN-LICENSE.txt
new file mode 100644
index 000000000..a1fe6bfe1
--- /dev/null
+++ b/store/agents/data-studio/template/vendor/EMSCRIPTEN-LICENSE.txt
@@ -0,0 +1,101 @@
+Emscripten is available under 2 licenses, the MIT license and the
+University of Illinois/NCSA Open Source License.
+
+Both are permissive open source licenses, with little if any
+practical difference between them.
+
+The reason for offering both is that (1) the MIT license is
+well-known, while (2) the University of Illinois/NCSA Open Source
+License allows Emscripten's code to be integrated upstream into
+LLVM, which uses that license, should the opportunity arise.
+
+The full text of both licenses follows.
+
+==============================================================================
+
+Copyright (c) 2010-2014 Emscripten authors, see AUTHORS file.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+==============================================================================
+
+Copyright (c) 2010-2014 Emscripten authors, see AUTHORS file.
+All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the
+"Software"), to deal with the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+ Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimers.
+
+ Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimers
+ in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the names of Mozilla,
+ nor the names of its contributors may be used to endorse
+ or promote products derived from this Software without specific prior
+ written permission.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.
+
+==============================================================================
+
+This program uses portions of Node.js source code located in src/library_path.js,
+in accordance with the terms of the MIT license. Node's license follows:
+
+ """
+ Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to
+ deal in the Software without restriction, including without limitation the
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ IN THE SOFTWARE.
+ """
+
+The musl libc project is bundled in this repo, and it has the MIT license, see
+system/lib/libc/musl/COPYRIGHT
+
+The third_party/ subdirectory contains code with other licenses. None of it is
+used by default, but certain options use it (e.g., the optional closure compiler
+flag will run closure compiler from third_party/).
diff --git a/store/agents/data-studio/template/vendor/MUSL-COPYRIGHT.txt b/store/agents/data-studio/template/vendor/MUSL-COPYRIGHT.txt
new file mode 100644
index 000000000..c1628e9ac
--- /dev/null
+++ b/store/agents/data-studio/template/vendor/MUSL-COPYRIGHT.txt
@@ -0,0 +1,193 @@
+musl as a whole is licensed under the following standard MIT license:
+
+----------------------------------------------------------------------
+Copyright © 2005-2020 Rich Felker, et al.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+----------------------------------------------------------------------
+
+Authors/contributors include:
+
+A. Wilcox
+Ada Worcester
+Alex Dowad
+Alex Suykov
+Alexander Monakov
+Andre McCurdy
+Andrew Kelley
+Anthony G. Basile
+Aric Belsito
+Arvid Picciani
+Bartosz Brachaczek
+Benjamin Peterson
+Bobby Bingham
+Boris Brezillon
+Brent Cook
+Chris Spiegel
+Clément Vasseur
+Daniel Micay
+Daniel Sabogal
+Daurnimator
+David Carlier
+David Edelsohn
+Denys Vlasenko
+Dmitry Ivanov
+Dmitry V. Levin
+Drew DeVault
+Emil Renner Berthing
+Fangrui Song
+Felix Fietkau
+Felix Janda
+Gianluca Anzolin
+Hauke Mehrtens
+He X
+Hiltjo Posthuma
+Isaac Dunham
+Jaydeep Patil
+Jens Gustedt
+Jeremy Huntwork
+Jo-Philipp Wich
+Joakim Sindholt
+John Spencer
+Julien Ramseier
+Justin Cormack
+Kaarle Ritvanen
+Khem Raj
+Kylie McClain
+Leah Neukirchen
+Luca Barbato
+Luka Perkov
+M Farkas-Dyck (Strake)
+Mahesh Bodapati
+Markus Wichmann
+Masanori Ogino
+Michael Clark
+Michael Forney
+Mikhail Kremnyov
+Natanael Copa
+Nicholas J. Kain
+orc
+Pascal Cuoq
+Patrick Oppenlander
+Petr Hosek
+Petr Skocik
+Pierre Carrier
+Reini Urban
+Rich Felker
+Richard Pennington
+Ryan Fairfax
+Samuel Holland
+Segev Finer
+Shiz
+sin
+Solar Designer
+Stefan Kristiansson
+Stefan O'Rear
+Szabolcs Nagy
+Timo Teräs
+Trutz Behn
+Valentin Ochs
+Will Dietz
+William Haddon
+William Pitcock
+
+Portions of this software are derived from third-party works licensed
+under terms compatible with the above MIT license:
+
+The TRE regular expression implementation (src/regex/reg* and
+src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed
+under a 2-clause BSD license (license text in the source files). The
+included version has been heavily modified by Rich Felker in 2012, in
+the interests of size, simplicity, and namespace cleanliness.
+
+Much of the math library code (src/math/* and src/complex/*) is
+Copyright © 1993,2004 Sun Microsystems or
+Copyright © 2003-2011 David Schultz or
+Copyright © 2003-2009 Steven G. Kargl or
+Copyright © 2003-2009 Bruce D. Evans or
+Copyright © 2008 Stephen L. Moshier or
+Copyright © 2017-2018 Arm Limited
+and labelled as such in comments in the individual source files. All
+have been licensed under extremely permissive terms.
+
+The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008
+The Android Open Source Project and is licensed under a two-clause BSD
+license. It was taken from Bionic libc, used on Android.
+
+The AArch64 memcpy and memset code (src/string/aarch64/*) are
+Copyright © 1999-2019, Arm Limited.
+
+The implementation of DES for crypt (src/crypt/crypt_des.c) is
+Copyright © 1994 David Burren. It is licensed under a BSD license.
+
+The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was
+originally written by Solar Designer and placed into the public
+domain. The code also comes with a fallback permissive license for use
+in jurisdictions that may not recognize the public domain.
+
+The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011
+Valentin Ochs and is licensed under an MIT-style license.
+
+The x86_64 port was written by Nicholas J. Kain and is licensed under
+the standard MIT terms.
+
+The mips and microblaze ports were originally written by Richard
+Pennington for use in the ellcc project. The original code was adapted
+by Rich Felker for build system and code conventions during upstream
+integration. It is licensed under the standard MIT terms.
+
+The mips64 port was contributed by Imagination Technologies and is
+licensed under the standard MIT terms.
+
+The powerpc port was also originally written by Richard Pennington,
+and later supplemented and integrated by John Spencer. It is licensed
+under the standard MIT terms.
+
+All other files which have no copyright comments are original works
+produced specifically for use as part of this library, written either
+by Rich Felker, the main author of the library, or by one or more
+contibutors listed above. Details on authorship of individual files
+can be found in the git version control history of the project. The
+omission of copyright and license comments in each file is in the
+interest of source tree size.
+
+In addition, permission is hereby granted for all public header files
+(include/* and arch/*/bits/*) and crt files intended to be linked into
+applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit
+the copyright notice and permission notice otherwise required by the
+license, and to use these files without any requirement of
+attribution. These files include substantial contributions from:
+
+Bobby Bingham
+John Spencer
+Nicholas J. Kain
+Rich Felker
+Richard Pennington
+Stefan Kristiansson
+Szabolcs Nagy
+
+all of whom have explicitly granted such permission.
+
+This file previously contained text expressing a belief that most of
+the files covered by the above exception were sufficiently trivial not
+to be subject to copyright, resulting in confusion over whether it
+negated the permissions granted in the license. In the spirit of
+permissive licensing, and of not having licensing issues being an
+obstacle to adoption, that text has been removed.
diff --git a/store/agents/data-studio/template/vendor/NOTICE.md b/store/agents/data-studio/template/vendor/NOTICE.md
new file mode 100644
index 000000000..afab70704
--- /dev/null
+++ b/store/agents/data-studio/template/vendor/NOTICE.md
@@ -0,0 +1,17 @@
+# SQLite browser runtime
+
+Unmodified sqlite3.js and sqlite3.wasm from the official SQLite 3.53.4
+distribution: https://www.sqlite.org/2026/sqlite-wasm-3530400.zip
+Archive SHA3-256 and individual SHA-256 hashes are in checksums.json.
+
+SQLite source and documentation are dedicated to the public domain:
+https://www.sqlite.org/copyright.html
+The JavaScript file retains the upstream license banner. Its generated
+Emscripten glue is offered under MIT and University of Illinois/NCSA terms:
+https://emscripten.org/docs/introducing_emscripten/emscripten_license.html
+The exact Emscripten 5.0.1 license and its bundled musl copyright notice are
+included as EMSCRIPTEN-LICENSE.txt and MUSL-COPYRIGHT.txt, from the upstream
+emscripten-core/emscripten repository at the 5.0.1 tag.
+
+No upstream ownership, endorsement or warranty is implied. This package uses
+in-memory SQLite only; OPFS, localStorage and extension loading are not used.
diff --git a/store/agents/data-studio/template/vendor/checksums.json b/store/agents/data-studio/template/vendor/checksums.json
new file mode 100644
index 000000000..93de5a55f
--- /dev/null
+++ b/store/agents/data-studio/template/vendor/checksums.json
@@ -0,0 +1,7 @@
+{
+ "version": "3.53.4",
+ "url": "https://www.sqlite.org/2026/sqlite-wasm-3530400.zip",
+ "archiveSHA3_256": "e4fa7e1750b42f6954115d8e69ffff7dc08da7e9fee6e28a2a0ea6bf228a49f2",
+ "sqlite3.js": "b6f472d13f7030d3ca60b8c592ffb84507ef4300e1276dd81b96bd3030d9ec6b",
+ "sqlite3.wasm": "3929b5b2a1cd7d7c32171e1f654fce0355191b7c9bc84afc61d9b2b99b96531f"
+}
diff --git a/store/agents/data-studio/template/vendor/sqlite3.js b/store/agents/data-studio/template/vendor/sqlite3.js
new file mode 100644
index 000000000..0e3d715d7
--- /dev/null
+++ b/store/agents/data-studio/template/vendor/sqlite3.js
@@ -0,0 +1,14314 @@
+/* @preserve
+**
+** LICENSE for the sqlite3 WebAssembly/JavaScript APIs.
+**
+** This bundle (typically released as sqlite3.js or sqlite3.mjs)
+** is an amalgamation of JavaScript source code from two projects:
+**
+** 1) https://emscripten.org: the Emscripten "glue code" is covered by
+** the terms of the MIT license and University of Illinois/NCSA
+** Open Source License, as described at:
+**
+** https://emscripten.org/docs/introducing_emscripten/emscripten_license.html
+**
+** 2) https://sqlite.org: all code and documentation labeled as being
+** from this source are released under the same terms as the sqlite3
+** C library:
+**
+** 2022-10-16
+**
+** The author disclaims copyright to this source code. In place of a
+** legal notice, here is a blessing:
+**
+** * May you do good and not evil.
+** * May you find forgiveness for yourself and forgive others.
+** * May you share freely, never taking more than you give.
+*/
+/* @preserve
+** This code was built from sqlite3 version...
+**
+** SQLITE_VERSION "3.53.4"
+** SQLITE_VERSION_NUMBER 3053004
+** SQLITE_SOURCE_ID "2026-07-24 19:02:57 bf7c7f30031888f4e796e429ab3978879485813aaca6f641c7b33e4e09459bcc"
+**
+** Emscripten SDK: 5.0.1
+*/
+
+
+
+
+
+var sqlite3InitModule = (() => {
+
+
+
+ var _scriptName = globalThis.document?.currentScript?.src;
+ return async function(moduleArg = {}) {
+ var moduleRtn;
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+var Module = moduleArg;
+
+
+
+
+
+var ENVIRONMENT_IS_WEB = !!globalThis.window;
+var ENVIRONMENT_IS_WORKER = !!globalThis.WorkerGlobalScope;
+
+
+var ENVIRONMENT_IS_NODE = globalThis.process?.versions?.node && globalThis.process?.type != 'renderer';
+var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
+
+
+
+
+
+
+(function(Module){
+ const sIMS =
+ globalThis.sqlite3InitModuleState
+ || Object.assign(Object.create(null),{
+
+ debugModule: function(){
+ console.warn("globalThis.sqlite3InitModuleState is missing",arguments);
+ }
+ });
+ delete globalThis.sqlite3InitModuleState;
+ sIMS.debugModule('pre-js.js sqlite3InitModuleState =',sIMS);
+
+
+ Module['locateFile'] = function(path, prefix) {
+ if( this.emscriptenLocateFile instanceof Function ){
+
+ return this.emscriptenLocateFile(path, prefix);
+ }
+ 'use strict';
+ let theFile;
+ const up = this.urlParams;
+ if(up.has(path)){
+ theFile = up.get(path);
+ }else if(this.sqlite3Dir){
+ theFile = this.sqlite3Dir + path;
+ }else if(this.scriptDir){
+ theFile = this.scriptDir + path;
+ }else{
+ theFile = prefix + path;
+ }
+ this.debugModule(
+ "locateFile(",arguments[0], ',', arguments[1],")",
+ 'sqlite3InitModuleState.scriptDir =',this.scriptDir,
+ 'up.entries() =',Array.from(up.entries()),
+ "result =", theFile
+ );
+ return theFile;
+ }.bind(sIMS);
+
+
+ Module['instantiateWasm'] = function callee(imports,onSuccess){
+ if( this.emscriptenInstantiateWasm instanceof Function ){
+
+ return this.emscriptenInstantiateWasm(imports, onSuccess);
+ }
+ const sims = this;
+ const uri = Module.locateFile(
+ sims.wasmFilename, (
+ ('undefined'===typeof scriptDirectory)
+ ? "" : scriptDirectory)
+ );
+ sims.debugModule("instantiateWasm() uri =", uri, "sIMS =",this);
+ const wfetch = ()=>fetch(uri, {credentials: 'same-origin'});
+ const finalThen = (arg)=>{
+ arg.imports = imports;
+ sims.instantiateWasm = arg ;
+ onSuccess(arg.instance, arg.module);
+ };
+ const loadWasm = WebAssembly.instantiateStreaming
+ ? async ()=>
+ WebAssembly
+ .instantiateStreaming(wfetch(), imports)
+ .then(finalThen)
+ : async ()=>
+ wfetch()
+ .then(response => response.arrayBuffer())
+ .then(bytes => WebAssembly.instantiate(bytes, imports))
+ .then(finalThen)
+ return loadWasm();
+ }.bind(sIMS);
+})(Module);
+
+
+
+
+var arguments_ = [];
+var thisProgram = './this.program';
+var quit_ = (status, toThrow) => {
+ throw toThrow;
+};
+
+if (ENVIRONMENT_IS_WORKER) {
+ _scriptName = self.location.href;
+}
+
+
+var scriptDirectory = '';
+function locateFile(path) {
+ if (Module['locateFile']) {
+ return Module['locateFile'](path, scriptDirectory);
+ }
+ return scriptDirectory + path;
+}
+
+
+var readAsync, readBinary;
+
+
+
+
+if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
+ try {
+ scriptDirectory = new URL('.', _scriptName).href;
+ } catch {
+
+
+ }
+
+ {
+
+if (ENVIRONMENT_IS_WORKER) {
+ readBinary = (url) => {
+ var xhr = new XMLHttpRequest();
+ xhr.open('GET', url, false);
+ xhr.responseType = 'arraybuffer';
+ xhr.send(null);
+ return new Uint8Array((xhr.response));
+ };
+ }
+
+ readAsync = async (url) => {
+ var response = await fetch(url, { credentials: 'same-origin' });
+ if (response.ok) {
+ return response.arrayBuffer();
+ }
+ throw new Error(response.status + ' : ' + response.url);
+ };
+
+ }
+} else
+{
+}
+
+var out = console.log.bind(console);
+var err = console.error.bind(console);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+var wasmBinary;
+
+
+
+
+
+
+
+
+
+var ABORT = false;
+
+
+
+
+var EXITSTATUS;
+
+
+
+
+
+
+function assert(condition, text) {
+ if (!condition) {
+
+
+
+ abort(text);
+ }
+}
+
+
+var isFileURI = (filename) => filename.startsWith('file://');
+
+
+
+
+
+
+
+
+var readyPromiseResolve, readyPromiseReject;
+
+
+var
+
+ HEAP8,
+
+ HEAPU8,
+
+ HEAP16,
+
+ HEAPU16,
+
+ HEAP32,
+
+ HEAPU32,
+
+ HEAPF32,
+
+ HEAPF64;
+
+
+var
+
+ HEAP64,
+
+ HEAPU64;
+
+var runtimeInitialized = false;
+
+
+
+function updateMemoryViews() {
+ var b = wasmMemory.buffer;
+ HEAP8 = new Int8Array(b);
+ HEAP16 = new Int16Array(b);
+ HEAPU8 = new Uint8Array(b);
+ HEAPU16 = new Uint16Array(b);
+ HEAP32 = new Int32Array(b);
+ HEAPU32 = new Uint32Array(b);
+ HEAPF32 = new Float32Array(b);
+ HEAPF64 = new Float64Array(b);
+ HEAP64 = new BigInt64Array(b);
+ HEAPU64 = new BigUint64Array(b);
+}
+
+
+
+
+
+
+
+function initMemory() {
+
+
+
+ if (Module['wasmMemory']) {
+ wasmMemory = Module['wasmMemory'];
+ } else
+ {
+ var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 8388608;
+
+
+ wasmMemory = new WebAssembly.Memory({
+ 'initial': INITIAL_MEMORY / 65536,
+
+
+
+
+
+ 'maximum': 32768,
+ });
+ }
+
+ updateMemoryViews();
+}
+
+
+
+
+
+
+function preRun() {
+ if (Module['preRun']) {
+ if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
+ while (Module['preRun'].length) {
+ addOnPreRun(Module['preRun'].shift());
+ }
+ }
+
+ callRuntimeCallbacks(onPreRuns);
+
+}
+
+function initRuntime() {
+ runtimeInitialized = true;
+
+
+ if (!Module['noFSInit'] && !FS.initialized) FS.init();
+TTY.init();
+
+
+ wasmExports['__wasm_call_ctors']();
+
+
+ FS.ignorePermissions = false;
+
+}
+
+function postRun() {
+
+
+ if (Module['postRun']) {
+ if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
+ while (Module['postRun'].length) {
+ addOnPostRun(Module['postRun'].shift());
+ }
+ }
+
+
+ callRuntimeCallbacks(onPostRuns);
+
+}
+
+
+function abort(what) {
+ Module['onAbort']?.(what);
+
+ what = 'Aborted(' + what + ')';
+
+
+ err(what);
+
+ ABORT = true;
+
+ what += '. Build with -sASSERTIONS for more info.';
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ var e = new WebAssembly.RuntimeError(what);
+
+ readyPromiseReject?.(e);
+
+
+
+ throw e;
+}
+
+var wasmBinaryFile;
+
+function findWasmBinary() {
+ return locateFile('sqlite3.wasm');
+}
+
+function getBinarySync(file) {
+ if (file == wasmBinaryFile && wasmBinary) {
+ return new Uint8Array(wasmBinary);
+ }
+ if (readBinary) {
+ return readBinary(file);
+ }
+
+
+ throw 'both async and sync fetching of the wasm failed';
+}
+
+async function getWasmBinary(binaryFile) {
+
+ if (!wasmBinary) {
+
+ try {
+ var response = await readAsync(binaryFile);
+ return new Uint8Array(response);
+ } catch {
+
+ }
+ }
+
+
+ return getBinarySync(binaryFile);
+}
+
+async function instantiateArrayBuffer(binaryFile, imports) {
+ try {
+ var binary = await getWasmBinary(binaryFile);
+ var instance = await WebAssembly.instantiate(binary, imports);
+ return instance;
+ } catch (reason) {
+ err(`failed to asynchronously prepare wasm: ${reason}`);
+
+ abort(reason);
+ }
+}
+
+async function instantiateAsync(binary, binaryFile, imports) {
+ if (!binary
+ ) {
+ try {
+ var response = fetch(binaryFile, { credentials: 'same-origin' });
+ var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);
+ return instantiationResult;
+ } catch (reason) {
+
+
+ err(`wasm streaming compile failed: ${reason}`);
+ err('falling back to ArrayBuffer instantiation');
+
+ };
+ }
+ return instantiateArrayBuffer(binaryFile, imports);
+}
+
+function getWasmImports() {
+
+ var imports = {
+ 'env': wasmImports,
+ 'wasi_snapshot_preview1': wasmImports,
+ };
+ return imports;
+}
+
+
+
+async function createWasm() {
+
+
+
+
+ function receiveInstance(instance, module) {
+ wasmExports = instance.exports;
+
+ assignWasmExports(wasmExports);
+
+ return wasmExports;
+ }
+
+
+ function receiveInstantiationResult(result) {
+
+
+
+
+ return receiveInstance(result['instance']);
+ }
+
+ var info = getWasmImports();
+
+
+
+
+
+
+
+ if (Module['instantiateWasm']) {
+ return new Promise((resolve, reject) => {
+ Module['instantiateWasm'](info, (inst, mod) => {
+ resolve(receiveInstance(inst, mod));
+ });
+ });
+ }
+
+ wasmBinaryFile ??= findWasmBinary();
+ var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);
+ var exports = receiveInstantiationResult(result);
+ return exports;
+}
+
+
+
+
+
+
+ class ExitStatus {
+ name = 'ExitStatus';
+ constructor(status) {
+ this.message = `Program terminated with exit(${status})`;
+ this.status = status;
+ }
+ }
+
+ var callRuntimeCallbacks = (callbacks) => {
+ while (callbacks.length > 0) {
+
+ callbacks.shift()(Module);
+ }
+ };
+ var onPostRuns = [];
+ var addOnPostRun = (cb) => onPostRuns.push(cb);
+
+ var onPreRuns = [];
+ var addOnPreRun = (cb) => onPreRuns.push(cb);
+
+
+
+
+ function getValue(ptr, type = 'i8') {
+ if (type.endsWith('*')) type = '*';
+ switch (type) {
+ case 'i1': return HEAP8[ptr];
+ case 'i8': return HEAP8[ptr];
+ case 'i16': return HEAP16[((ptr)>>1)];
+ case 'i32': return HEAP32[((ptr)>>2)];
+ case 'i64': return HEAP64[((ptr)>>3)];
+ case 'float': return HEAPF32[((ptr)>>2)];
+ case 'double': return HEAPF64[((ptr)>>3)];
+ case '*': return HEAPU32[((ptr)>>2)];
+ default: abort(`invalid type for getValue: ${type}`);
+ }
+ }
+
+ var noExitRuntime = true;
+
+
+
+ function setValue(ptr, value, type = 'i8') {
+ if (type.endsWith('*')) type = '*';
+ switch (type) {
+ case 'i1': HEAP8[ptr] = value; break;
+ case 'i8': HEAP8[ptr] = value; break;
+ case 'i16': HEAP16[((ptr)>>1)] = value; break;
+ case 'i32': HEAP32[((ptr)>>2)] = value; break;
+ case 'i64': HEAP64[((ptr)>>3)] = BigInt(value); break;
+ case 'float': HEAPF32[((ptr)>>2)] = value; break;
+ case 'double': HEAPF64[((ptr)>>3)] = value; break;
+ case '*': HEAPU32[((ptr)>>2)] = value; break;
+ default: abort(`invalid type for setValue: ${type}`);
+ }
+ }
+
+ var stackRestore = (val) => __emscripten_stack_restore(val);
+
+ var stackSave = () => _emscripten_stack_get_current();
+
+ var wasmMemory;
+
+ var PATH = {
+ isAbs:(path) => path.charAt(0) === '/',
+ splitPath:(filename) => {
+ var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
+ return splitPathRe.exec(filename).slice(1);
+ },
+ normalizeArray:(parts, allowAboveRoot) => {
+
+ var up = 0;
+ for (var i = parts.length - 1; i >= 0; i--) {
+ var last = parts[i];
+ if (last === '.') {
+ parts.splice(i, 1);
+ } else if (last === '..') {
+ parts.splice(i, 1);
+ up++;
+ } else if (up) {
+ parts.splice(i, 1);
+ up--;
+ }
+ }
+
+ if (allowAboveRoot) {
+ for (; up; up--) {
+ parts.unshift('..');
+ }
+ }
+ return parts;
+ },
+ normalize:(path) => {
+ var isAbsolute = PATH.isAbs(path),
+ trailingSlash = path.slice(-1) === '/';
+
+ path = PATH.normalizeArray(path.split('/').filter((p) => !!p), !isAbsolute).join('/');
+ if (!path && !isAbsolute) {
+ path = '.';
+ }
+ if (path && trailingSlash) {
+ path += '/';
+ }
+ return (isAbsolute ? '/' : '') + path;
+ },
+ dirname:(path) => {
+ var result = PATH.splitPath(path),
+ root = result[0],
+ dir = result[1];
+ if (!root && !dir) {
+
+ return '.';
+ }
+ if (dir) {
+
+ dir = dir.slice(0, -1);
+ }
+ return root + dir;
+ },
+ basename:(path) => path && path.match(/([^\/]+|\/)\/*$/)[1],
+join:(...paths) => PATH.normalize(paths.join('/')),
+join2:(l, r) => PATH.normalize(l + '/' + r),
+};
+
+var initRandomFill = () => {
+
+ return (view) => crypto.getRandomValues(view);
+ };
+var randomFill = (view) => {
+
+ (randomFill = initRandomFill())(view);
+ };
+
+
+
+var PATH_FS = {
+resolve:(...args) => {
+ var resolvedPath = '',
+ resolvedAbsolute = false;
+ for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
+ var path = (i >= 0) ? args[i] : FS.cwd();
+
+ if (typeof path != 'string') {
+ throw new TypeError('Arguments to path.resolve must be strings');
+ } else if (!path) {
+ return '';
+ }
+ resolvedPath = path + '/' + resolvedPath;
+ resolvedAbsolute = PATH.isAbs(path);
+ }
+
+
+ resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter((p) => !!p), !resolvedAbsolute).join('/');
+ return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
+ },
+relative:(from, to) => {
+ from = PATH_FS.resolve(from).slice(1);
+ to = PATH_FS.resolve(to).slice(1);
+ function trim(arr) {
+ var start = 0;
+ for (; start < arr.length; start++) {
+ if (arr[start] !== '') break;
+ }
+ var end = arr.length - 1;
+ for (; end >= 0; end--) {
+ if (arr[end] !== '') break;
+ }
+ if (start > end) return [];
+ return arr.slice(start, end - start + 1);
+ }
+ var fromParts = trim(from.split('/'));
+ var toParts = trim(to.split('/'));
+ var length = Math.min(fromParts.length, toParts.length);
+ var samePartsLength = length;
+ for (var i = 0; i < length; i++) {
+ if (fromParts[i] !== toParts[i]) {
+ samePartsLength = i;
+ break;
+ }
+ }
+ var outputParts = [];
+ for (var i = samePartsLength; i < fromParts.length; i++) {
+ outputParts.push('..');
+ }
+ outputParts = outputParts.concat(toParts.slice(samePartsLength));
+ return outputParts.join('/');
+ },
+};
+
+
+var UTF8Decoder = new TextDecoder();
+
+var findStringEnd = (heapOrArray, idx, maxBytesToRead, ignoreNul) => {
+ var maxIdx = idx + maxBytesToRead;
+ if (ignoreNul) return maxIdx;
+
+
+
+
+ while (heapOrArray[idx] && !(idx >= maxIdx)) ++idx;
+ return idx;
+ };
+
+
+ var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => {
+
+ var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul);
+
+ return UTF8Decoder.decode(heapOrArray.buffer ? heapOrArray.subarray(idx, endPtr) : new Uint8Array(heapOrArray.slice(idx, endPtr)));
+ };
+
+ var FS_stdin_getChar_buffer = [];
+
+ var lengthBytesUTF8 = (str) => {
+ var len = 0;
+ for (var i = 0; i < str.length; ++i) {
+
+
+
+
+ var c = str.charCodeAt(i);
+ if (c <= 0x7F) {
+ len++;
+ } else if (c <= 0x7FF) {
+ len += 2;
+ } else if (c >= 0xD800 && c <= 0xDFFF) {
+ len += 4; ++i;
+ } else {
+ len += 3;
+ }
+ }
+ return len;
+ };
+
+ var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
+
+
+ if (!(maxBytesToWrite > 0))
+ return 0;
+
+ var startIdx = outIdx;
+ var endIdx = outIdx + maxBytesToWrite - 1;
+ for (var i = 0; i < str.length; ++i) {
+
+
+
+ var u = str.codePointAt(i);
+ if (u <= 0x7F) {
+ if (outIdx >= endIdx) break;
+ heap[outIdx++] = u;
+ } else if (u <= 0x7FF) {
+ if (outIdx + 1 >= endIdx) break;
+ heap[outIdx++] = 0xC0 | (u >> 6);
+ heap[outIdx++] = 0x80 | (u & 63);
+ } else if (u <= 0xFFFF) {
+ if (outIdx + 2 >= endIdx) break;
+ heap[outIdx++] = 0xE0 | (u >> 12);
+ heap[outIdx++] = 0x80 | ((u >> 6) & 63);
+ heap[outIdx++] = 0x80 | (u & 63);
+ } else {
+ if (outIdx + 3 >= endIdx) break;
+ heap[outIdx++] = 0xF0 | (u >> 18);
+ heap[outIdx++] = 0x80 | ((u >> 12) & 63);
+ heap[outIdx++] = 0x80 | ((u >> 6) & 63);
+ heap[outIdx++] = 0x80 | (u & 63);
+
+
+ i++;
+ }
+ }
+
+ heap[outIdx] = 0;
+ return outIdx - startIdx;
+ };
+
+ var intArrayFromString = (stringy, dontAddNull, length) => {
+ var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;
+ var u8array = new Array(len);
+ var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
+ if (dontAddNull) u8array.length = numBytesWritten;
+ return u8array;
+ };
+ var FS_stdin_getChar = () => {
+ if (!FS_stdin_getChar_buffer.length) {
+ var result = null;
+ if (globalThis.window?.prompt) {
+
+ result = window.prompt('Input: ');
+ if (result !== null) {
+ result += '\n';
+ }
+ } else
+ {}
+ if (!result) {
+ return null;
+ }
+ FS_stdin_getChar_buffer = intArrayFromString(result, true);
+ }
+ return FS_stdin_getChar_buffer.shift();
+ };
+ var TTY = {
+ ttys:[],
+ init() {
+
+
+
+
+
+
+
+
+ },
+ shutdown() {
+
+
+
+
+
+
+
+
+
+ },
+ register(dev, ops) {
+ TTY.ttys[dev] = { input: [], output: [], ops: ops };
+ FS.registerDevice(dev, TTY.stream_ops);
+ },
+ stream_ops:{
+ open(stream) {
+ var tty = TTY.ttys[stream.node.rdev];
+ if (!tty) {
+ throw new FS.ErrnoError(43);
+ }
+ stream.tty = tty;
+ stream.seekable = false;
+ },
+ close(stream) {
+
+ stream.tty.ops.fsync(stream.tty);
+ },
+ fsync(stream) {
+ stream.tty.ops.fsync(stream.tty);
+ },
+ read(stream, buffer, offset, length, pos ) {
+ if (!stream.tty || !stream.tty.ops.get_char) {
+ throw new FS.ErrnoError(60);
+ }
+ var bytesRead = 0;
+ for (var i = 0; i < length; i++) {
+ var result;
+ try {
+ result = stream.tty.ops.get_char(stream.tty);
+ } catch (e) {
+ throw new FS.ErrnoError(29);
+ }
+ if (result === undefined && bytesRead === 0) {
+ throw new FS.ErrnoError(6);
+ }
+ if (result === null || result === undefined) break;
+ bytesRead++;
+ buffer[offset+i] = result;
+ }
+ if (bytesRead) {
+ stream.node.atime = Date.now();
+ }
+ return bytesRead;
+ },
+ write(stream, buffer, offset, length, pos) {
+ if (!stream.tty || !stream.tty.ops.put_char) {
+ throw new FS.ErrnoError(60);
+ }
+ try {
+ for (var i = 0; i < length; i++) {
+ stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
+ }
+ } catch (e) {
+ throw new FS.ErrnoError(29);
+ }
+ if (length) {
+ stream.node.mtime = stream.node.ctime = Date.now();
+ }
+ return i;
+ },
+ },
+ default_tty_ops:{
+ get_char(tty) {
+ return FS_stdin_getChar();
+ },
+ put_char(tty, val) {
+ if (val === null || val === 10) {
+ out(UTF8ArrayToString(tty.output));
+ tty.output = [];
+ } else {
+ if (val != 0) tty.output.push(val);
+ }
+ },
+ fsync(tty) {
+ if (tty.output?.length > 0) {
+ out(UTF8ArrayToString(tty.output));
+ tty.output = [];
+ }
+ },
+ ioctl_tcgets(tty) {
+
+ return {
+ c_iflag: 25856,
+ c_oflag: 5,
+ c_cflag: 191,
+ c_lflag: 35387,
+ c_cc: [
+ 0x03, 0x1c, 0x7f, 0x15, 0x04, 0x00, 0x01, 0x00, 0x11, 0x13, 0x1a, 0x00,
+ 0x12, 0x0f, 0x17, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ ]
+ };
+ },
+ ioctl_tcsets(tty, optional_actions, data) {
+
+ return 0;
+ },
+ ioctl_tiocgwinsz(tty) {
+ return [24, 80];
+ },
+ },
+ default_tty1_ops:{
+ put_char(tty, val) {
+ if (val === null || val === 10) {
+ err(UTF8ArrayToString(tty.output));
+ tty.output = [];
+ } else {
+ if (val != 0) tty.output.push(val);
+ }
+ },
+ fsync(tty) {
+ if (tty.output?.length > 0) {
+ err(UTF8ArrayToString(tty.output));
+ tty.output = [];
+ }
+ },
+ },
+ };
+
+
+ var zeroMemory = (ptr, size) => HEAPU8.fill(0, ptr, ptr + size);
+
+ var alignMemory = (size, alignment) => {
+ return Math.ceil(size / alignment) * alignment;
+ };
+ var mmapAlloc = (size) => {
+ size = alignMemory(size, 65536);
+ var ptr = _emscripten_builtin_memalign(65536, size);
+ if (ptr) zeroMemory(ptr, size);
+ return ptr;
+ };
+ var MEMFS = {
+ ops_table:null,
+ mount(mount) {
+ return MEMFS.createNode(null, '/', 16895, 0);
+ },
+ createNode(parent, name, mode, dev) {
+ if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
+
+ throw new FS.ErrnoError(63);
+ }
+ MEMFS.ops_table ||= {
+ dir: {
+ node: {
+ getattr: MEMFS.node_ops.getattr,
+ setattr: MEMFS.node_ops.setattr,
+ lookup: MEMFS.node_ops.lookup,
+ mknod: MEMFS.node_ops.mknod,
+ rename: MEMFS.node_ops.rename,
+ unlink: MEMFS.node_ops.unlink,
+ rmdir: MEMFS.node_ops.rmdir,
+ readdir: MEMFS.node_ops.readdir,
+ symlink: MEMFS.node_ops.symlink
+ },
+ stream: {
+ llseek: MEMFS.stream_ops.llseek
+ }
+ },
+ file: {
+ node: {
+ getattr: MEMFS.node_ops.getattr,
+ setattr: MEMFS.node_ops.setattr
+ },
+ stream: {
+ llseek: MEMFS.stream_ops.llseek,
+ read: MEMFS.stream_ops.read,
+ write: MEMFS.stream_ops.write,
+ mmap: MEMFS.stream_ops.mmap,
+ msync: MEMFS.stream_ops.msync
+ }
+ },
+ link: {
+ node: {
+ getattr: MEMFS.node_ops.getattr,
+ setattr: MEMFS.node_ops.setattr,
+ readlink: MEMFS.node_ops.readlink
+ },
+ stream: {}
+ },
+ chrdev: {
+ node: {
+ getattr: MEMFS.node_ops.getattr,
+ setattr: MEMFS.node_ops.setattr
+ },
+ stream: FS.chrdev_stream_ops
+ }
+ };
+ var node = FS.createNode(parent, name, mode, dev);
+ if (FS.isDir(node.mode)) {
+ node.node_ops = MEMFS.ops_table.dir.node;
+ node.stream_ops = MEMFS.ops_table.dir.stream;
+ node.contents = {};
+ } else if (FS.isFile(node.mode)) {
+ node.node_ops = MEMFS.ops_table.file.node;
+ node.stream_ops = MEMFS.ops_table.file.stream;
+ node.usedBytes = 0;
+
+
+
+ node.contents = null;
+ } else if (FS.isLink(node.mode)) {
+ node.node_ops = MEMFS.ops_table.link.node;
+ node.stream_ops = MEMFS.ops_table.link.stream;
+ } else if (FS.isChrdev(node.mode)) {
+ node.node_ops = MEMFS.ops_table.chrdev.node;
+ node.stream_ops = MEMFS.ops_table.chrdev.stream;
+ }
+ node.atime = node.mtime = node.ctime = Date.now();
+
+ if (parent) {
+ parent.contents[name] = node;
+ parent.atime = parent.mtime = parent.ctime = node.atime;
+ }
+ return node;
+ },
+ getFileDataAsTypedArray(node) {
+ if (!node.contents) return new Uint8Array(0);
+ if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes);
+ return new Uint8Array(node.contents);
+ },
+ expandFileStorage(node, newCapacity) {
+ var prevCapacity = node.contents ? node.contents.length : 0;
+ if (prevCapacity >= newCapacity) return;
+
+
+
+ var CAPACITY_DOUBLING_MAX = 1024 * 1024;
+ newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125)) >>> 0);
+ if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256);
+ var oldContents = node.contents;
+ node.contents = new Uint8Array(newCapacity);
+ if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0);
+ },
+ resizeFileStorage(node, newSize) {
+ if (node.usedBytes == newSize) return;
+ if (newSize == 0) {
+ node.contents = null;
+ node.usedBytes = 0;
+ } else {
+ var oldContents = node.contents;
+ node.contents = new Uint8Array(newSize);
+ if (oldContents) {
+ node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));
+ }
+ node.usedBytes = newSize;
+ }
+ },
+ node_ops:{
+ getattr(node) {
+ var attr = {};
+
+ attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
+ attr.ino = node.id;
+ attr.mode = node.mode;
+ attr.nlink = 1;
+ attr.uid = 0;
+ attr.gid = 0;
+ attr.rdev = node.rdev;
+ if (FS.isDir(node.mode)) {
+ attr.size = 4096;
+ } else if (FS.isFile(node.mode)) {
+ attr.size = node.usedBytes;
+ } else if (FS.isLink(node.mode)) {
+ attr.size = node.link.length;
+ } else {
+ attr.size = 0;
+ }
+ attr.atime = new Date(node.atime);
+ attr.mtime = new Date(node.mtime);
+ attr.ctime = new Date(node.ctime);
+
+
+ attr.blksize = 4096;
+ attr.blocks = Math.ceil(attr.size / attr.blksize);
+ return attr;
+ },
+ setattr(node, attr) {
+ for (const key of ["mode", "atime", "mtime", "ctime"]) {
+ if (attr[key] != null) {
+ node[key] = attr[key];
+ }
+ }
+ if (attr.size !== undefined) {
+ MEMFS.resizeFileStorage(node, attr.size);
+ }
+ },
+ lookup(parent, name) {
+
+
+ if (!MEMFS.doesNotExistError) {
+ MEMFS.doesNotExistError = new FS.ErrnoError(44);
+
+ MEMFS.doesNotExistError.stack = '<generic error, no stack>';
+ }
+ throw MEMFS.doesNotExistError;
+ },
+ mknod(parent, name, mode, dev) {
+ return MEMFS.createNode(parent, name, mode, dev);
+ },
+ rename(old_node, new_dir, new_name) {
+ var new_node;
+ try {
+ new_node = FS.lookupNode(new_dir, new_name);
+ } catch (e) {}
+ if (new_node) {
+ if (FS.isDir(old_node.mode)) {
+
+ for (var i in new_node.contents) {
+ throw new FS.ErrnoError(55);
+ }
+ }
+ FS.hashRemoveNode(new_node);
+ }
+
+ delete old_node.parent.contents[old_node.name];
+ new_dir.contents[new_name] = old_node;
+ old_node.name = new_name;
+ new_dir.ctime = new_dir.mtime = old_node.parent.ctime = old_node.parent.mtime = Date.now();
+ },
+ unlink(parent, name) {
+ delete parent.contents[name];
+ parent.ctime = parent.mtime = Date.now();
+ },
+ rmdir(parent, name) {
+ var node = FS.lookupNode(parent, name);
+ for (var i in node.contents) {
+ throw new FS.ErrnoError(55);
+ }
+ delete parent.contents[name];
+ parent.ctime = parent.mtime = Date.now();
+ },
+ readdir(node) {
+ return ['.', '..', ...Object.keys(node.contents)];
+ },
+ symlink(parent, newname, oldpath) {
+ var node = MEMFS.createNode(parent, newname, 0o777 | 40960, 0);
+ node.link = oldpath;
+ return node;
+ },
+ readlink(node) {
+ if (!FS.isLink(node.mode)) {
+ throw new FS.ErrnoError(28);
+ }
+ return node.link;
+ },
+ },
+ stream_ops:{
+ read(stream, buffer, offset, length, position) {
+ var contents = stream.node.contents;
+ if (position >= stream.node.usedBytes) return 0;
+ var size = Math.min(stream.node.usedBytes - position, length);
+ if (size > 8 && contents.subarray) {
+ buffer.set(contents.subarray(position, position + size), offset);
+ } else {
+ for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];
+ }
+ return size;
+ },
+ write(stream, buffer, offset, length, position, canOwn) {
+
+
+
+
+ if (buffer.buffer === HEAP8.buffer) {
+ canOwn = false;
+ }
+
+ if (!length) return 0;
+ var node = stream.node;
+ node.mtime = node.ctime = Date.now();
+
+ if (buffer.subarray && (!node.contents || node.contents.subarray)) {
+ if (canOwn) {
+ node.contents = buffer.subarray(offset, offset + length);
+ node.usedBytes = length;
+ return length;
+ } else if (node.usedBytes === 0 && position === 0) {
+ node.contents = buffer.slice(offset, offset + length);
+ node.usedBytes = length;
+ return length;
+ } else if (position + length <= node.usedBytes) {
+ node.contents.set(buffer.subarray(offset, offset + length), position);
+ return length;
+ }
+ }
+
+
+ MEMFS.expandFileStorage(node, position+length);
+ if (node.contents.subarray && buffer.subarray) {
+
+ node.contents.set(buffer.subarray(offset, offset + length), position);
+ } else {
+ for (var i = 0; i < length; i++) {
+ node.contents[position + i] = buffer[offset + i];
+ }
+ }
+ node.usedBytes = Math.max(node.usedBytes, position + length);
+ return length;
+ },
+ llseek(stream, offset, whence) {
+ var position = offset;
+ if (whence === 1) {
+ position += stream.position;
+ } else if (whence === 2) {
+ if (FS.isFile(stream.node.mode)) {
+ position += stream.node.usedBytes;
+ }
+ }
+ if (position < 0) {
+ throw new FS.ErrnoError(28);
+ }
+ return position;
+ },
+ mmap(stream, length, position, prot, flags) {
+ if (!FS.isFile(stream.node.mode)) {
+ throw new FS.ErrnoError(43);
+ }
+ var ptr;
+ var allocated;
+ var contents = stream.node.contents;
+
+ if (!(flags & 2) && contents && contents.buffer === HEAP8.buffer) {
+
+
+ allocated = false;
+ ptr = contents.byteOffset;
+ } else {
+ allocated = true;
+ ptr = mmapAlloc(length);
+ if (!ptr) {
+ throw new FS.ErrnoError(48);
+ }
+ if (contents) {
+
+ if (position > 0 || position + length < contents.length) {
+ if (contents.subarray) {
+ contents = contents.subarray(position, position + length);
+ } else {
+ contents = Array.prototype.slice.call(contents, position, position + length);
+ }
+ }
+ HEAP8.set(contents, ptr);
+ }
+ }
+ return { ptr, allocated };
+ },
+ msync(stream, buffer, offset, length, mmapFlags) {
+ MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
+
+ return 0;
+ },
+ },
+ };
+
+ var FS_modeStringToFlags = (str) => {
+ var flagModes = {
+ 'r': 0,
+ 'r+': 2,
+ 'w': 512 | 64 | 1,
+ 'w+': 512 | 64 | 2,
+ 'a': 1024 | 64 | 1,
+ 'a+': 1024 | 64 | 2,
+ };
+ var flags = flagModes[str];
+ if (typeof flags == 'undefined') {
+ throw new Error(`Unknown file open mode: ${str}`);
+ }
+ return flags;
+ };
+
+ var FS_getMode = (canRead, canWrite) => {
+ var mode = 0;
+ if (canRead) mode |= 292 | 73;
+ if (canWrite) mode |= 146;
+ return mode;
+ };
+
+
+ var asyncLoad = async (url) => {
+ var arrayBuffer = await readAsync(url);
+ return new Uint8Array(arrayBuffer);
+ };
+
+
+ var FS_createDataFile = (...args) => FS.createDataFile(...args);
+
+ var getUniqueRunDependency = (id) => {
+ return id;
+ };
+
+ var runDependencies = 0;
+
+
+ var dependenciesFulfilled = null;
+ var removeRunDependency = (id) => {
+ runDependencies--;
+
+ Module['monitorRunDependencies']?.(runDependencies);
+
+ if (runDependencies == 0) {
+ if (dependenciesFulfilled) {
+ var callback = dependenciesFulfilled;
+ dependenciesFulfilled = null;
+ callback();
+ }
+ }
+ };
+ var addRunDependency = (id) => {
+ runDependencies++;
+
+ Module['monitorRunDependencies']?.(runDependencies);
+
+ };
+
+
+ var preloadPlugins = [];
+ var FS_handledByPreloadPlugin = async (byteArray, fullname) => {
+
+ if (typeof Browser != 'undefined') Browser.init();
+
+ for (var plugin of preloadPlugins) {
+ if (plugin['canHandle'](fullname)) {
+ return plugin['handle'](byteArray, fullname);
+ }
+ }
+
+
+ return byteArray;
+ };
+ var FS_preloadFile = async (parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish) => {
+
+
+ var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
+ var dep = getUniqueRunDependency(`cp ${fullname}`);
+ addRunDependency(dep);
+
+ try {
+ var byteArray = url;
+ if (typeof url == 'string') {
+ byteArray = await asyncLoad(url);
+ }
+
+ byteArray = await FS_handledByPreloadPlugin(byteArray, fullname);
+ preFinish?.();
+ if (!dontCreateFile) {
+ FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
+ }
+ } finally {
+ removeRunDependency(dep);
+ }
+ };
+ var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {
+ FS_preloadFile(parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish).then(onload).catch(onerror);
+ };
+ var FS = {
+ root:null,
+ mounts:[],
+ devices:{
+ },
+ streams:[],
+ nextInode:1,
+ nameTable:null,
+ currentPath:"/",
+ initialized:false,
+ ignorePermissions:true,
+ filesystems:null,
+ syncFSRequests:0,
+ ErrnoError:class {
+ name = 'ErrnoError';
+
+
+
+
+
+
+ constructor(errno) {
+ this.errno = errno;
+ }
+ },
+ FSStream:class {
+ shared = {};
+ get object() {
+ return this.node;
+ }
+ set object(val) {
+ this.node = val;
+ }
+ get isRead() {
+ return (this.flags & 2097155) !== 1;
+ }
+ get isWrite() {
+ return (this.flags & 2097155) !== 0;
+ }
+ get isAppend() {
+ return (this.flags & 1024);
+ }
+ get flags() {
+ return this.shared.flags;
+ }
+ set flags(val) {
+ this.shared.flags = val;
+ }
+ get position() {
+ return this.shared.position;
+ }
+ set position(val) {
+ this.shared.position = val;
+ }
+ },
+ FSNode:class {
+ node_ops = {};
+ stream_ops = {};
+ readMode = 292 | 73;
+ writeMode = 146;
+ mounted = null;
+ constructor(parent, name, mode, rdev) {
+ if (!parent) {
+ parent = this;
+ }
+ this.parent = parent;
+ this.mount = parent.mount;
+ this.id = FS.nextInode++;
+ this.name = name;
+ this.mode = mode;
+ this.rdev = rdev;
+ this.atime = this.mtime = this.ctime = Date.now();
+ }
+ get read() {
+ return (this.mode & this.readMode) === this.readMode;
+ }
+ set read(val) {
+ val ? this.mode |= this.readMode : this.mode &= ~this.readMode;
+ }
+ get write() {
+ return (this.mode & this.writeMode) === this.writeMode;
+ }
+ set write(val) {
+ val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;
+ }
+ get isFolder() {
+ return FS.isDir(this.mode);
+ }
+ get isDevice() {
+ return FS.isChrdev(this.mode);
+ }
+ },
+ lookupPath(path, opts = {}) {
+ if (!path) {
+ throw new FS.ErrnoError(44);
+ }
+ opts.follow_mount ??= true
+
+ if (!PATH.isAbs(path)) {
+ path = FS.cwd() + '/' + path;
+ }
+
+
+ linkloop: for (var nlinks = 0; nlinks < 40; nlinks++) {
+
+ var parts = path.split('/').filter((p) => !!p);
+
+
+ var current = FS.root;
+ var current_path = '/';
+
+ for (var i = 0; i < parts.length; i++) {
+ var islast = (i === parts.length-1);
+ if (islast && opts.parent) {
+
+ break;
+ }
+
+ if (parts[i] === '.') {
+ continue;
+ }
+
+ if (parts[i] === '..') {
+ current_path = PATH.dirname(current_path);
+ if (FS.isRoot(current)) {
+ path = current_path + '/' + parts.slice(i + 1).join('/');
+
+
+ nlinks--;
+ continue linkloop;
+ } else {
+ current = current.parent;
+ }
+ continue;
+ }
+
+ current_path = PATH.join2(current_path, parts[i]);
+ try {
+ current = FS.lookupNode(current, parts[i]);
+ } catch (e) {
+
+
+
+ if ((e?.errno === 44) && islast && opts.noent_okay) {
+ return { path: current_path };
+ }
+ throw e;
+ }
+
+
+ if (FS.isMountpoint(current) && (!islast || opts.follow_mount)) {
+ current = current.mounted.root;
+ }
+
+
+
+ if (FS.isLink(current.mode) && (!islast || opts.follow)) {
+ if (!current.node_ops.readlink) {
+ throw new FS.ErrnoError(52);
+ }
+ var link = current.node_ops.readlink(current);
+ if (!PATH.isAbs(link)) {
+ link = PATH.dirname(current_path) + '/' + link;
+ }
+ path = link + '/' + parts.slice(i + 1).join('/');
+ continue linkloop;
+ }
+ }
+ return { path: current_path, node: current };
+ }
+ throw new FS.ErrnoError(32);
+ },
+ getPath(node) {
+ var path;
+ while (true) {
+ if (FS.isRoot(node)) {
+ var mount = node.mount.mountpoint;
+ if (!path) return mount;
+ return mount[mount.length-1] !== '/' ? `${mount}/${path}` : mount + path;
+ }
+ path = path ? `${node.name}/${path}` : node.name;
+ node = node.parent;
+ }
+ },
+ hashName(parentid, name) {
+ var hash = 0;
+
+ for (var i = 0; i < name.length; i++) {
+ hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
+ }
+ return ((parentid + hash) >>> 0) % FS.nameTable.length;
+ },
+ hashAddNode(node) {
+ var hash = FS.hashName(node.parent.id, node.name);
+ node.name_next = FS.nameTable[hash];
+ FS.nameTable[hash] = node;
+ },
+ hashRemoveNode(node) {
+ var hash = FS.hashName(node.parent.id, node.name);
+ if (FS.nameTable[hash] === node) {
+ FS.nameTable[hash] = node.name_next;
+ } else {
+ var current = FS.nameTable[hash];
+ while (current) {
+ if (current.name_next === node) {
+ current.name_next = node.name_next;
+ break;
+ }
+ current = current.name_next;
+ }
+ }
+ },
+ lookupNode(parent, name) {
+ var errCode = FS.mayLookup(parent);
+ if (errCode) {
+ throw new FS.ErrnoError(errCode);
+ }
+ var hash = FS.hashName(parent.id, name);
+ for (var node = FS.nameTable[hash]; node; node = node.name_next) {
+ var nodeName = node.name;
+ if (node.parent.id === parent.id && nodeName === name) {
+ return node;
+ }
+ }
+
+ return FS.lookup(parent, name);
+ },
+ createNode(parent, name, mode, rdev) {
+ var node = new FS.FSNode(parent, name, mode, rdev);
+
+ FS.hashAddNode(node);
+
+ return node;
+ },
+ destroyNode(node) {
+ FS.hashRemoveNode(node);
+ },
+ isRoot(node) {
+ return node === node.parent;
+ },
+ isMountpoint(node) {
+ return !!node.mounted;
+ },
+ isFile(mode) {
+ return (mode & 61440) === 32768;
+ },
+ isDir(mode) {
+ return (mode & 61440) === 16384;
+ },
+ isLink(mode) {
+ return (mode & 61440) === 40960;
+ },
+ isChrdev(mode) {
+ return (mode & 61440) === 8192;
+ },
+ isBlkdev(mode) {
+ return (mode & 61440) === 24576;
+ },
+ isFIFO(mode) {
+ return (mode & 61440) === 4096;
+ },
+ isSocket(mode) {
+ return (mode & 49152) === 49152;
+ },
+ flagsToPermissionString(flag) {
+ var perms = ['r', 'w', 'rw'][flag & 3];
+ if ((flag & 512)) {
+ perms += 'w';
+ }
+ return perms;
+ },
+ nodePermissions(node, perms) {
+ if (FS.ignorePermissions) {
+ return 0;
+ }
+
+ if (perms.includes('r') && !(node.mode & 292)) {
+ return 2;
+ }
+ if (perms.includes('w') && !(node.mode & 146)) {
+ return 2;
+ }
+ if (perms.includes('x') && !(node.mode & 73)) {
+ return 2;
+ }
+ return 0;
+ },
+ mayLookup(dir) {
+ if (!FS.isDir(dir.mode)) return 54;
+ var errCode = FS.nodePermissions(dir, 'x');
+ if (errCode) return errCode;
+ if (!dir.node_ops.lookup) return 2;
+ return 0;
+ },
+ mayCreate(dir, name) {
+ if (!FS.isDir(dir.mode)) {
+ return 54;
+ }
+ try {
+ var node = FS.lookupNode(dir, name);
+ return 20;
+ } catch (e) {
+ }
+ return FS.nodePermissions(dir, 'wx');
+ },
+ mayDelete(dir, name, isdir) {
+ var node;
+ try {
+ node = FS.lookupNode(dir, name);
+ } catch (e) {
+ return e.errno;
+ }
+ var errCode = FS.nodePermissions(dir, 'wx');
+ if (errCode) {
+ return errCode;
+ }
+ if (isdir) {
+ if (!FS.isDir(node.mode)) {
+ return 54;
+ }
+ if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
+ return 10;
+ }
+ } else if (FS.isDir(node.mode)) {
+ return 31;
+ }
+ return 0;
+ },
+ mayOpen(node, flags) {
+ if (!node) {
+ return 44;
+ }
+ if (FS.isLink(node.mode)) {
+ return 32;
+ }
+ var mode = FS.flagsToPermissionString(flags);
+ if (FS.isDir(node.mode)) {
+
+
+ if (mode !== 'r' || (flags & (512 | 64))) {
+ return 31;
+ }
+ }
+ return FS.nodePermissions(node, mode);
+ },
+ checkOpExists(op, err) {
+ if (!op) {
+ throw new FS.ErrnoError(err);
+ }
+ return op;
+ },
+ MAX_OPEN_FDS:4096,
+ nextfd() {
+ for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {
+ if (!FS.streams[fd]) {
+ return fd;
+ }
+ }
+ throw new FS.ErrnoError(33);
+ },
+ getStreamChecked(fd) {
+ var stream = FS.getStream(fd);
+ if (!stream) {
+ throw new FS.ErrnoError(8);
+ }
+ return stream;
+ },
+ getStream:(fd) => FS.streams[fd],
+ createStream(stream, fd = -1) {
+
+
+ stream = Object.assign(new FS.FSStream(), stream);
+ if (fd == -1) {
+ fd = FS.nextfd();
+ }
+ stream.fd = fd;
+ FS.streams[fd] = stream;
+ return stream;
+ },
+ closeStream(fd) {
+ FS.streams[fd] = null;
+ },
+ dupStream(origStream, fd = -1) {
+ var stream = FS.createStream(origStream, fd);
+ stream.stream_ops?.dup?.(stream);
+ return stream;
+ },
+ doSetAttr(stream, node, attr) {
+ var setattr = stream?.stream_ops.setattr;
+ var arg = setattr ? stream : node;
+ setattr ??= node.node_ops.setattr;
+ FS.checkOpExists(setattr, 63)
+ setattr(arg, attr);
+ },
+ chrdev_stream_ops:{
+ open(stream) {
+ var device = FS.getDevice(stream.node.rdev);
+
+ stream.stream_ops = device.stream_ops;
+
+ stream.stream_ops.open?.(stream);
+ },
+ llseek() {
+ throw new FS.ErrnoError(70);
+ },
+ },
+ major:(dev) => ((dev) >> 8),
+ minor:(dev) => ((dev) & 0xff),
+ makedev:(ma, mi) => ((ma) << 8 | (mi)),
+ registerDevice(dev, ops) {
+ FS.devices[dev] = { stream_ops: ops };
+ },
+ getDevice:(dev) => FS.devices[dev],
+ getMounts(mount) {
+ var mounts = [];
+ var check = [mount];
+
+ while (check.length) {
+ var m = check.pop();
+
+ mounts.push(m);
+
+ check.push(...m.mounts);
+ }
+
+ return mounts;
+ },
+ syncfs(populate, callback) {
+ if (typeof populate == 'function') {
+ callback = populate;
+ populate = false;
+ }
+
+ FS.syncFSRequests++;
+
+ if (FS.syncFSRequests > 1) {
+ err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);
+ }
+
+ var mounts = FS.getMounts(FS.root.mount);
+ var completed = 0;
+
+ function doCallback(errCode) {
+ FS.syncFSRequests--;
+ return callback(errCode);
+ }
+
+ function done(errCode) {
+ if (errCode) {
+ if (!done.errored) {
+ done.errored = true;
+ return doCallback(errCode);
+ }
+ return;
+ }
+ if (++completed >= mounts.length) {
+ doCallback(null);
+ }
+ };
+
+
+ for (var mount of mounts) {
+ if (mount.type.syncfs) {
+ mount.type.syncfs(mount, populate, done);
+ } else {
+ done(null);
+ }
+ }
+ },
+ mount(type, opts, mountpoint) {
+ var root = mountpoint === '/';
+ var pseudo = !mountpoint;
+ var node;
+
+ if (root && FS.root) {
+ throw new FS.ErrnoError(10);
+ } else if (!root && !pseudo) {
+ var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
+
+ mountpoint = lookup.path;
+ node = lookup.node;
+
+ if (FS.isMountpoint(node)) {
+ throw new FS.ErrnoError(10);
+ }
+
+ if (!FS.isDir(node.mode)) {
+ throw new FS.ErrnoError(54);
+ }
+ }
+
+ var mount = {
+ type,
+ opts,
+ mountpoint,
+ mounts: []
+ };
+
+
+ var mountRoot = type.mount(mount);
+ mountRoot.mount = mount;
+ mount.root = mountRoot;
+
+ if (root) {
+ FS.root = mountRoot;
+ } else if (node) {
+
+ node.mounted = mount;
+
+
+ if (node.mount) {
+ node.mount.mounts.push(mount);
+ }
+ }
+
+ return mountRoot;
+ },
+ unmount(mountpoint) {
+ var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
+
+ if (!FS.isMountpoint(lookup.node)) {
+ throw new FS.ErrnoError(28);
+ }
+
+
+ var node = lookup.node;
+ var mount = node.mounted;
+ var mounts = FS.getMounts(mount);
+
+ for (var [hash, current] of Object.entries(FS.nameTable)) {
+ while (current) {
+ var next = current.name_next;
+
+ if (mounts.includes(current.mount)) {
+ FS.destroyNode(current);
+ }
+
+ current = next;
+ }
+ }
+
+
+ node.mounted = null;
+
+
+ var idx = node.mount.mounts.indexOf(mount);
+ node.mount.mounts.splice(idx, 1);
+ },
+ lookup(parent, name) {
+ return parent.node_ops.lookup(parent, name);
+ },
+ mknod(path, mode, dev) {
+ var lookup = FS.lookupPath(path, { parent: true });
+ var parent = lookup.node;
+ var name = PATH.basename(path);
+ if (!name) {
+ throw new FS.ErrnoError(28);
+ }
+ if (name === '.' || name === '..') {
+ throw new FS.ErrnoError(20);
+ }
+ var errCode = FS.mayCreate(parent, name);
+ if (errCode) {
+ throw new FS.ErrnoError(errCode);
+ }
+ if (!parent.node_ops.mknod) {
+ throw new FS.ErrnoError(63);
+ }
+ return parent.node_ops.mknod(parent, name, mode, dev);
+ },
+ statfs(path) {
+ return FS.statfsNode(FS.lookupPath(path, {follow: true}).node);
+ },
+ statfsStream(stream) {
+
+
+
+ return FS.statfsNode(stream.node);
+ },
+ statfsNode(node) {
+
+
+
+ var rtn = {
+ bsize: 4096,
+ frsize: 4096,
+ blocks: 1e6,
+ bfree: 5e5,
+ bavail: 5e5,
+ files: FS.nextInode,
+ ffree: FS.nextInode - 1,
+ fsid: 42,
+ flags: 2,
+ namelen: 255,
+ };
+
+ if (node.node_ops.statfs) {
+ Object.assign(rtn, node.node_ops.statfs(node.mount.opts.root));
+ }
+ return rtn;
+ },
+ create(path, mode = 0o666) {
+ mode &= 4095;
+ mode |= 32768;
+ return FS.mknod(path, mode, 0);
+ },
+ mkdir(path, mode = 0o777) {
+ mode &= 511 | 512;
+ mode |= 16384;
+ return FS.mknod(path, mode, 0);
+ },
+ mkdirTree(path, mode) {
+ var dirs = path.split('/');
+ var d = '';
+ for (var dir of dirs) {
+ if (!dir) continue;
+ if (d || PATH.isAbs(path)) d += '/';
+ d += dir;
+ try {
+ FS.mkdir(d, mode);
+ } catch(e) {
+ if (e.errno != 20) throw e;
+ }
+ }
+ },
+ mkdev(path, mode, dev) {
+ if (typeof dev == 'undefined') {
+ dev = mode;
+ mode = 0o666;
+ }
+ mode |= 8192;
+ return FS.mknod(path, mode, dev);
+ },
+ symlink(oldpath, newpath) {
+ if (!PATH_FS.resolve(oldpath)) {
+ throw new FS.ErrnoError(44);
+ }
+ var lookup = FS.lookupPath(newpath, { parent: true });
+ var parent = lookup.node;
+ if (!parent) {
+ throw new FS.ErrnoError(44);
+ }
+ var newname = PATH.basename(newpath);
+ var errCode = FS.mayCreate(parent, newname);
+ if (errCode) {
+ throw new FS.ErrnoError(errCode);
+ }
+ if (!parent.node_ops.symlink) {
+ throw new FS.ErrnoError(63);
+ }
+ return parent.node_ops.symlink(parent, newname, oldpath);
+ },
+ rename(old_path, new_path) {
+ var old_dirname = PATH.dirname(old_path);
+ var new_dirname = PATH.dirname(new_path);
+ var old_name = PATH.basename(old_path);
+ var new_name = PATH.basename(new_path);
+
+ var lookup, old_dir, new_dir;
+
+
+ lookup = FS.lookupPath(old_path, { parent: true });
+ old_dir = lookup.node;
+ lookup = FS.lookupPath(new_path, { parent: true });
+ new_dir = lookup.node;
+
+ if (!old_dir || !new_dir) throw new FS.ErrnoError(44);
+
+ if (old_dir.mount !== new_dir.mount) {
+ throw new FS.ErrnoError(75);
+ }
+
+ var old_node = FS.lookupNode(old_dir, old_name);
+
+ var relative = PATH_FS.relative(old_path, new_dirname);
+ if (relative.charAt(0) !== '.') {
+ throw new FS.ErrnoError(28);
+ }
+
+ relative = PATH_FS.relative(new_path, old_dirname);
+ if (relative.charAt(0) !== '.') {
+ throw new FS.ErrnoError(55);
+ }
+
+ var new_node;
+ try {
+ new_node = FS.lookupNode(new_dir, new_name);
+ } catch (e) {
+
+ }
+
+ if (old_node === new_node) {
+ return;
+ }
+
+ var isdir = FS.isDir(old_node.mode);
+ var errCode = FS.mayDelete(old_dir, old_name, isdir);
+ if (errCode) {
+ throw new FS.ErrnoError(errCode);
+ }
+
+
+ errCode = new_node ?
+ FS.mayDelete(new_dir, new_name, isdir) :
+ FS.mayCreate(new_dir, new_name);
+ if (errCode) {
+ throw new FS.ErrnoError(errCode);
+ }
+ if (!old_dir.node_ops.rename) {
+ throw new FS.ErrnoError(63);
+ }
+ if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
+ throw new FS.ErrnoError(10);
+ }
+
+ if (new_dir !== old_dir) {
+ errCode = FS.nodePermissions(old_dir, 'w');
+ if (errCode) {
+ throw new FS.ErrnoError(errCode);
+ }
+ }
+
+ FS.hashRemoveNode(old_node);
+
+ try {
+ old_dir.node_ops.rename(old_node, new_dir, new_name);
+
+
+ old_node.parent = new_dir;
+ } catch (e) {
+ throw e;
+ } finally {
+
+
+ FS.hashAddNode(old_node);
+ }
+ },
+ rmdir(path) {
+ var lookup = FS.lookupPath(path, { parent: true });
+ var parent = lookup.node;
+ var name = PATH.basename(path);
+ var node = FS.lookupNode(parent, name);
+ var errCode = FS.mayDelete(parent, name, true);
+ if (errCode) {
+ throw new FS.ErrnoError(errCode);
+ }
+ if (!parent.node_ops.rmdir) {
+ throw new FS.ErrnoError(63);
+ }
+ if (FS.isMountpoint(node)) {
+ throw new FS.ErrnoError(10);
+ }
+ parent.node_ops.rmdir(parent, name);
+ FS.destroyNode(node);
+ },
+ readdir(path) {
+ var lookup = FS.lookupPath(path, { follow: true });
+ var node = lookup.node;
+ var readdir = FS.checkOpExists(node.node_ops.readdir, 54);
+ return readdir(node);
+ },
+ unlink(path) {
+ var lookup = FS.lookupPath(path, { parent: true });
+ var parent = lookup.node;
+ if (!parent) {
+ throw new FS.ErrnoError(44);
+ }
+ var name = PATH.basename(path);
+ var node = FS.lookupNode(parent, name);
+ var errCode = FS.mayDelete(parent, name, false);
+ if (errCode) {
+
+
+
+ throw new FS.ErrnoError(errCode);
+ }
+ if (!parent.node_ops.unlink) {
+ throw new FS.ErrnoError(63);
+ }
+ if (FS.isMountpoint(node)) {
+ throw new FS.ErrnoError(10);
+ }
+ parent.node_ops.unlink(parent, name);
+ FS.destroyNode(node);
+ },
+ readlink(path) {
+ var lookup = FS.lookupPath(path);
+ var link = lookup.node;
+ if (!link) {
+ throw new FS.ErrnoError(44);
+ }
+ if (!link.node_ops.readlink) {
+ throw new FS.ErrnoError(28);
+ }
+ return link.node_ops.readlink(link);
+ },
+ stat(path, dontFollow) {
+ var lookup = FS.lookupPath(path, { follow: !dontFollow });
+ var node = lookup.node;
+ var getattr = FS.checkOpExists(node.node_ops.getattr, 63);
+ return getattr(node);
+ },
+ fstat(fd) {
+ var stream = FS.getStreamChecked(fd);
+ var node = stream.node;
+ var getattr = stream.stream_ops.getattr;
+ var arg = getattr ? stream : node;
+ getattr ??= node.node_ops.getattr;
+ FS.checkOpExists(getattr, 63)
+ return getattr(arg);
+ },
+ lstat(path) {
+ return FS.stat(path, true);
+ },
+ doChmod(stream, node, mode, dontFollow) {
+ FS.doSetAttr(stream, node, {
+ mode: (mode & 4095) | (node.mode & ~4095),
+ ctime: Date.now(),
+ dontFollow
+ });
+ },
+ chmod(path, mode, dontFollow) {
+ var node;
+ if (typeof path == 'string') {
+ var lookup = FS.lookupPath(path, { follow: !dontFollow });
+ node = lookup.node;
+ } else {
+ node = path;
+ }
+ FS.doChmod(null, node, mode, dontFollow);
+ },
+ lchmod(path, mode) {
+ FS.chmod(path, mode, true);
+ },
+ fchmod(fd, mode) {
+ var stream = FS.getStreamChecked(fd);
+ FS.doChmod(stream, stream.node, mode, false);
+ },
+ doChown(stream, node, dontFollow) {
+ FS.doSetAttr(stream, node, {
+ timestamp: Date.now(),
+ dontFollow
+
+ });
+ },
+ chown(path, uid, gid, dontFollow) {
+ var node;
+ if (typeof path == 'string') {
+ var lookup = FS.lookupPath(path, { follow: !dontFollow });
+ node = lookup.node;
+ } else {
+ node = path;
+ }
+ FS.doChown(null, node, dontFollow);
+ },
+ lchown(path, uid, gid) {
+ FS.chown(path, uid, gid, true);
+ },
+ fchown(fd, uid, gid) {
+ var stream = FS.getStreamChecked(fd);
+ FS.doChown(stream, stream.node, false);
+ },
+ doTruncate(stream, node, len) {
+ if (FS.isDir(node.mode)) {
+ throw new FS.ErrnoError(31);
+ }
+ if (!FS.isFile(node.mode)) {
+ throw new FS.ErrnoError(28);
+ }
+ var errCode = FS.nodePermissions(node, 'w');
+ if (errCode) {
+ throw new FS.ErrnoError(errCode);
+ }
+ FS.doSetAttr(stream, node, {
+ size: len,
+ timestamp: Date.now()
+ });
+ },
+ truncate(path, len) {
+ if (len < 0) {
+ throw new FS.ErrnoError(28);
+ }
+ var node;
+ if (typeof path == 'string') {
+ var lookup = FS.lookupPath(path, { follow: true });
+ node = lookup.node;
+ } else {
+ node = path;
+ }
+ FS.doTruncate(null, node, len);
+ },
+ ftruncate(fd, len) {
+ var stream = FS.getStreamChecked(fd);
+ if (len < 0 || (stream.flags & 2097155) === 0) {
+ throw new FS.ErrnoError(28);
+ }
+ FS.doTruncate(stream, stream.node, len);
+ },
+ utime(path, atime, mtime) {
+ var lookup = FS.lookupPath(path, { follow: true });
+ var node = lookup.node;
+ var setattr = FS.checkOpExists(node.node_ops.setattr, 63);
+ setattr(node, {
+ atime: atime,
+ mtime: mtime
+ });
+ },
+ open(path, flags, mode = 0o666) {
+ if (path === "") {
+ throw new FS.ErrnoError(44);
+ }
+ flags = typeof flags == 'string' ? FS_modeStringToFlags(flags) : flags;
+ if ((flags & 64)) {
+ mode = (mode & 4095) | 32768;
+ } else {
+ mode = 0;
+ }
+ var node;
+ var isDirPath;
+ if (typeof path == 'object') {
+ node = path;
+ } else {
+ isDirPath = path.endsWith("/");
+
+
+
+ var lookup = FS.lookupPath(path, {
+ follow: !(flags & 131072),
+ noent_okay: true
+ });
+ node = lookup.node;
+ path = lookup.path;
+ }
+
+ var created = false;
+ if ((flags & 64)) {
+ if (node) {
+
+ if ((flags & 128)) {
+ throw new FS.ErrnoError(20);
+ }
+ } else if (isDirPath) {
+ throw new FS.ErrnoError(31);
+ } else {
+
+
+
+
+ node = FS.mknod(path, mode | 0o777, 0);
+ created = true;
+ }
+ }
+ if (!node) {
+ throw new FS.ErrnoError(44);
+ }
+
+ if (FS.isChrdev(node.mode)) {
+ flags &= ~512;
+ }
+
+ if ((flags & 65536) && !FS.isDir(node.mode)) {
+ throw new FS.ErrnoError(54);
+ }
+
+
+
+ if (!created) {
+ var errCode = FS.mayOpen(node, flags);
+ if (errCode) {
+ throw new FS.ErrnoError(errCode);
+ }
+ }
+
+ if ((flags & 512) && !created) {
+ FS.truncate(node, 0);
+ }
+
+ flags &= ~(128 | 512 | 131072);
+
+
+ var stream = FS.createStream({
+ node,
+ path: FS.getPath(node),
+ flags,
+ seekable: true,
+ position: 0,
+ stream_ops: node.stream_ops,
+
+ ungotten: [],
+ error: false
+ });
+
+ if (stream.stream_ops.open) {
+ stream.stream_ops.open(stream);
+ }
+ if (created) {
+ FS.chmod(node, mode & 0o777);
+ }
+ return stream;
+ },
+ close(stream) {
+ if (FS.isClosed(stream)) {
+ throw new FS.ErrnoError(8);
+ }
+ if (stream.getdents) stream.getdents = null;
+ try {
+ if (stream.stream_ops.close) {
+ stream.stream_ops.close(stream);
+ }
+ } catch (e) {
+ throw e;
+ } finally {
+ FS.closeStream(stream.fd);
+ }
+ stream.fd = null;
+ },
+ isClosed(stream) {
+ return stream.fd === null;
+ },
+ llseek(stream, offset, whence) {
+ if (FS.isClosed(stream)) {
+ throw new FS.ErrnoError(8);
+ }
+ if (!stream.seekable || !stream.stream_ops.llseek) {
+ throw new FS.ErrnoError(70);
+ }
+ if (whence != 0 && whence != 1 && whence != 2) {
+ throw new FS.ErrnoError(28);
+ }
+ stream.position = stream.stream_ops.llseek(stream, offset, whence);
+ stream.ungotten = [];
+ return stream.position;
+ },
+ read(stream, buffer, offset, length, position) {
+ if (length < 0 || position < 0) {
+ throw new FS.ErrnoError(28);
+ }
+ if (FS.isClosed(stream)) {
+ throw new FS.ErrnoError(8);
+ }
+ if ((stream.flags & 2097155) === 1) {
+ throw new FS.ErrnoError(8);
+ }
+ if (FS.isDir(stream.node.mode)) {
+ throw new FS.ErrnoError(31);
+ }
+ if (!stream.stream_ops.read) {
+ throw new FS.ErrnoError(28);
+ }
+ var seeking = typeof position != 'undefined';
+ if (!seeking) {
+ position = stream.position;
+ } else if (!stream.seekable) {
+ throw new FS.ErrnoError(70);
+ }
+ var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
+ if (!seeking) stream.position += bytesRead;
+ return bytesRead;
+ },
+ write(stream, buffer, offset, length, position, canOwn) {
+ if (length < 0 || position < 0) {
+ throw new FS.ErrnoError(28);
+ }
+ if (FS.isClosed(stream)) {
+ throw new FS.ErrnoError(8);
+ }
+ if ((stream.flags & 2097155) === 0) {
+ throw new FS.ErrnoError(8);
+ }
+ if (FS.isDir(stream.node.mode)) {
+ throw new FS.ErrnoError(31);
+ }
+ if (!stream.stream_ops.write) {
+ throw new FS.ErrnoError(28);
+ }
+ if (stream.seekable && stream.flags & 1024) {
+
+ FS.llseek(stream, 0, 2);
+ }
+ var seeking = typeof position != 'undefined';
+ if (!seeking) {
+ position = stream.position;
+ } else if (!stream.seekable) {
+ throw new FS.ErrnoError(70);
+ }
+ var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
+ if (!seeking) stream.position += bytesWritten;
+ return bytesWritten;
+ },
+ mmap(stream, length, position, prot, flags) {
+
+
+
+
+
+
+ if ((prot & 2) !== 0
+ && (flags & 2) === 0
+ && (stream.flags & 2097155) !== 2) {
+ throw new FS.ErrnoError(2);
+ }
+ if ((stream.flags & 2097155) === 1) {
+ throw new FS.ErrnoError(2);
+ }
+ if (!stream.stream_ops.mmap) {
+ throw new FS.ErrnoError(43);
+ }
+ if (!length) {
+ throw new FS.ErrnoError(28);
+ }
+ return stream.stream_ops.mmap(stream, length, position, prot, flags);
+ },
+ msync(stream, buffer, offset, length, mmapFlags) {
+ if (!stream.stream_ops.msync) {
+ return 0;
+ }
+ return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
+ },
+ ioctl(stream, cmd, arg) {
+ if (!stream.stream_ops.ioctl) {
+ throw new FS.ErrnoError(59);
+ }
+ return stream.stream_ops.ioctl(stream, cmd, arg);
+ },
+ readFile(path, opts = {}) {
+ opts.flags = opts.flags || 0;
+ opts.encoding = opts.encoding || 'binary';
+ if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
+ abort(`Invalid encoding type "${opts.encoding}"`);
+ }
+ var stream = FS.open(path, opts.flags);
+ var stat = FS.stat(path);
+ var length = stat.size;
+ var buf = new Uint8Array(length);
+ FS.read(stream, buf, 0, length, 0);
+ if (opts.encoding === 'utf8') {
+ buf = UTF8ArrayToString(buf);
+ }
+ FS.close(stream);
+ return buf;
+ },
+ writeFile(path, data, opts = {}) {
+ opts.flags = opts.flags || 577;
+ var stream = FS.open(path, opts.flags, opts.mode);
+ if (typeof data == 'string') {
+ data = new Uint8Array(intArrayFromString(data, true));
+ }
+ if (ArrayBuffer.isView(data)) {
+ FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);
+ } else {
+ abort('Unsupported data type');
+ }
+ FS.close(stream);
+ },
+ cwd:() => FS.currentPath,
+ chdir(path) {
+ var lookup = FS.lookupPath(path, { follow: true });
+ if (lookup.node === null) {
+ throw new FS.ErrnoError(44);
+ }
+ if (!FS.isDir(lookup.node.mode)) {
+ throw new FS.ErrnoError(54);
+ }
+ var errCode = FS.nodePermissions(lookup.node, 'x');
+ if (errCode) {
+ throw new FS.ErrnoError(errCode);
+ }
+ FS.currentPath = lookup.path;
+ },
+ createDefaultDirectories() {
+ FS.mkdir('/tmp');
+ FS.mkdir('/home');
+ FS.mkdir('/home/web_user');
+ },
+ createDefaultDevices() {
+
+ FS.mkdir('/dev');
+
+ FS.registerDevice(FS.makedev(1, 3), {
+ read: () => 0,
+ write: (stream, buffer, offset, length, pos) => length,
+ llseek: () => 0,
+ });
+ FS.mkdev('/dev/null', FS.makedev(1, 3));
+
+
+
+ TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
+ TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
+ FS.mkdev('/dev/tty', FS.makedev(5, 0));
+ FS.mkdev('/dev/tty1', FS.makedev(6, 0));
+
+
+ var randomBuffer = new Uint8Array(1024), randomLeft = 0;
+ var randomByte = () => {
+ if (randomLeft === 0) {
+ randomFill(randomBuffer);
+ randomLeft = randomBuffer.byteLength;
+ }
+ return randomBuffer[--randomLeft];
+ };
+ FS.createDevice('/dev', 'random', randomByte);
+ FS.createDevice('/dev', 'urandom', randomByte);
+
+
+ FS.mkdir('/dev/shm');
+ FS.mkdir('/dev/shm/tmp');
+ },
+ createSpecialDirectories() {
+
+
+ FS.mkdir('/proc');
+ var proc_self = FS.mkdir('/proc/self');
+ FS.mkdir('/proc/self/fd');
+ FS.mount({
+ mount() {
+ var node = FS.createNode(proc_self, 'fd', 16895, 73);
+ node.stream_ops = {
+ llseek: MEMFS.stream_ops.llseek,
+ };
+ node.node_ops = {
+ lookup(parent, name) {
+ var fd = +name;
+ var stream = FS.getStreamChecked(fd);
+ var ret = {
+ parent: null,
+ mount: { mountpoint: 'fake' },
+ node_ops: { readlink: () => stream.path },
+ id: fd + 1,
+ };
+ ret.parent = ret;
+ return ret;
+ },
+ readdir() {
+ return Array.from(FS.streams.entries())
+ .filter(([k, v]) => v)
+ .map(([k, v]) => k.toString());
+ }
+ };
+ return node;
+ }
+ }, {}, '/proc/self/fd');
+ },
+ createStandardStreams(input, output, error) {
+
+
+
+
+
+
+
+
+ if (input) {
+ FS.createDevice('/dev', 'stdin', input);
+ } else {
+ FS.symlink('/dev/tty', '/dev/stdin');
+ }
+ if (output) {
+ FS.createDevice('/dev', 'stdout', null, output);
+ } else {
+ FS.symlink('/dev/tty', '/dev/stdout');
+ }
+ if (error) {
+ FS.createDevice('/dev', 'stderr', null, error);
+ } else {
+ FS.symlink('/dev/tty1', '/dev/stderr');
+ }
+
+
+ var stdin = FS.open('/dev/stdin', 0);
+ var stdout = FS.open('/dev/stdout', 1);
+ var stderr = FS.open('/dev/stderr', 1);
+ },
+ staticInit() {
+ FS.nameTable = new Array(4096);
+
+ FS.mount(MEMFS, {}, '/');
+
+ FS.createDefaultDirectories();
+ FS.createDefaultDevices();
+ FS.createSpecialDirectories();
+
+ FS.filesystems = {
+ 'MEMFS': MEMFS,
+ };
+ },
+ init(input, output, error) {
+ FS.initialized = true;
+
+
+ input ??= Module['stdin'];
+ output ??= Module['stdout'];
+ error ??= Module['stderr'];
+
+ FS.createStandardStreams(input, output, error);
+ },
+ quit() {
+ FS.initialized = false;
+
+
+ for (var stream of FS.streams) {
+ if (stream) {
+ FS.close(stream);
+ }
+ }
+ },
+ findObject(path, dontResolveLastLink) {
+ var ret = FS.analyzePath(path, dontResolveLastLink);
+ if (!ret.exists) {
+ return null;
+ }
+ return ret.object;
+ },
+ analyzePath(path, dontResolveLastLink) {
+
+ try {
+ var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
+ path = lookup.path;
+ } catch (e) {
+ }
+ var ret = {
+ isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
+ parentExists: false, parentPath: null, parentObject: null
+ };
+ try {
+ var lookup = FS.lookupPath(path, { parent: true });
+ ret.parentExists = true;
+ ret.parentPath = lookup.path;
+ ret.parentObject = lookup.node;
+ ret.name = PATH.basename(path);
+ lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
+ ret.exists = true;
+ ret.path = lookup.path;
+ ret.object = lookup.node;
+ ret.name = lookup.node.name;
+ ret.isRoot = lookup.path === '/';
+ } catch (e) {
+ ret.error = e.errno;
+ };
+ return ret;
+ },
+ createPath(parent, path, canRead, canWrite) {
+ parent = typeof parent == 'string' ? parent : FS.getPath(parent);
+ var parts = path.split('/').reverse();
+ while (parts.length) {
+ var part = parts.pop();
+ if (!part) continue;
+ var current = PATH.join2(parent, part);
+ try {
+ FS.mkdir(current);
+ } catch (e) {
+ if (e.errno != 20) throw e;
+ }
+ parent = current;
+ }
+ return current;
+ },
+ createFile(parent, name, properties, canRead, canWrite) {
+ var path = PATH.join2(typeof parent == 'string' ? parent : FS.getPath(parent), name);
+ var mode = FS_getMode(canRead, canWrite);
+ return FS.create(path, mode);
+ },
+ createDataFile(parent, name, data, canRead, canWrite, canOwn) {
+ var path = name;
+ if (parent) {
+ parent = typeof parent == 'string' ? parent : FS.getPath(parent);
+ path = name ? PATH.join2(parent, name) : parent;
+ }
+ var mode = FS_getMode(canRead, canWrite);
+ var node = FS.create(path, mode);
+ if (data) {
+ if (typeof data == 'string') {
+ var arr = new Array(data.length);
+ for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
+ data = arr;
+ }
+
+ FS.chmod(node, mode | 146);
+ var stream = FS.open(node, 577);
+ FS.write(stream, data, 0, data.length, 0, canOwn);
+ FS.close(stream);
+ FS.chmod(node, mode);
+ }
+ },
+ createDevice(parent, name, input, output) {
+ var path = PATH.join2(typeof parent == 'string' ? parent : FS.getPath(parent), name);
+ var mode = FS_getMode(!!input, !!output);
+ FS.createDevice.major ??= 64;
+ var dev = FS.makedev(FS.createDevice.major++, 0);
+
+
+ FS.registerDevice(dev, {
+ open(stream) {
+ stream.seekable = false;
+ },
+ close(stream) {
+
+ if (output?.buffer?.length) {
+ output(10);
+ }
+ },
+ read(stream, buffer, offset, length, pos ) {
+ var bytesRead = 0;
+ for (var i = 0; i < length; i++) {
+ var result;
+ try {
+ result = input();
+ } catch (e) {
+ throw new FS.ErrnoError(29);
+ }
+ if (result === undefined && bytesRead === 0) {
+ throw new FS.ErrnoError(6);
+ }
+ if (result === null || result === undefined) break;
+ bytesRead++;
+ buffer[offset+i] = result;
+ }
+ if (bytesRead) {
+ stream.node.atime = Date.now();
+ }
+ return bytesRead;
+ },
+ write(stream, buffer, offset, length, pos) {
+ for (var i = 0; i < length; i++) {
+ try {
+ output(buffer[offset+i]);
+ } catch (e) {
+ throw new FS.ErrnoError(29);
+ }
+ }
+ if (length) {
+ stream.node.mtime = stream.node.ctime = Date.now();
+ }
+ return i;
+ }
+ });
+ return FS.mkdev(path, mode, dev);
+ },
+ forceLoadFile(obj) {
+ if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
+ if (globalThis.XMLHttpRequest) {
+ abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");
+ } else {
+ try {
+ obj.contents = readBinary(obj.url);
+ } catch (e) {
+ throw new FS.ErrnoError(29);
+ }
+ }
+ },
+ createLazyFile(parent, name, url, canRead, canWrite) {
+
+
+ class LazyUint8Array {
+ lengthKnown = false;
+ chunks = [];
+ get(idx) {
+ if (idx > this.length-1 || idx < 0) {
+ return undefined;
+ }
+ var chunkOffset = idx % this.chunkSize;
+ var chunkNum = (idx / this.chunkSize)|0;
+ return this.getter(chunkNum)[chunkOffset];
+ }
+ setDataGetter(getter) {
+ this.getter = getter;
+ }
+ cacheLength() {
+
+ var xhr = new XMLHttpRequest();
+ xhr.open('HEAD', url, false);
+ xhr.send(null);
+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort("Couldn't load " + url + ". Status: " + xhr.status);
+ var datalength = Number(xhr.getResponseHeader("Content-length"));
+ var header;
+ var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
+ var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
+
+ var chunkSize = 1024*1024;
+
+ if (!hasByteServing) chunkSize = datalength;
+
+
+ var doXHR = (from, to) => {
+ if (from > to) abort("invalid range (" + from + ", " + to + ") or no bytes requested!");
+ if (to > datalength-1) abort("only " + datalength + " bytes available! programmer error!");
+
+
+ var xhr = new XMLHttpRequest();
+ xhr.open('GET', url, false);
+ if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
+
+
+ xhr.responseType = 'arraybuffer';
+ if (xhr.overrideMimeType) {
+ xhr.overrideMimeType('text/plain; charset=x-user-defined');
+ }
+
+ xhr.send(null);
+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort("Couldn't load " + url + ". Status: " + xhr.status);
+ if (xhr.response !== undefined) {
+ return new Uint8Array((xhr.response || []));
+ }
+ return intArrayFromString(xhr.responseText || '', true);
+ };
+ var lazyArray = this;
+ lazyArray.setDataGetter((chunkNum) => {
+ var start = chunkNum * chunkSize;
+ var end = (chunkNum+1) * chunkSize - 1;
+ end = Math.min(end, datalength-1);
+ if (typeof lazyArray.chunks[chunkNum] == 'undefined') {
+ lazyArray.chunks[chunkNum] = doXHR(start, end);
+ }
+ if (typeof lazyArray.chunks[chunkNum] == 'undefined') abort('doXHR failed!');
+ return lazyArray.chunks[chunkNum];
+ });
+
+ if (usesGzip || !datalength) {
+
+ chunkSize = datalength = 1;
+ datalength = this.getter(0).length;
+ chunkSize = datalength;
+ out("LazyFiles on gzip forces download of the whole file when length is accessed");
+ }
+
+ this._length = datalength;
+ this._chunkSize = chunkSize;
+ this.lengthKnown = true;
+ }
+ get length() {
+ if (!this.lengthKnown) {
+ this.cacheLength();
+ }
+ return this._length;
+ }
+ get chunkSize() {
+ if (!this.lengthKnown) {
+ this.cacheLength();
+ }
+ return this._chunkSize;
+ }
+ }
+
+ if (globalThis.XMLHttpRequest) {
+ if (!ENVIRONMENT_IS_WORKER) abort('Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc');
+ var lazyArray = new LazyUint8Array();
+ var properties = { isDevice: false, contents: lazyArray };
+ } else {
+ var properties = { isDevice: false, url: url };
+ }
+
+ var node = FS.createFile(parent, name, properties, canRead, canWrite);
+
+
+
+ if (properties.contents) {
+ node.contents = properties.contents;
+ } else if (properties.url) {
+ node.contents = null;
+ node.url = properties.url;
+ }
+
+ Object.defineProperties(node, {
+ usedBytes: {
+ get: function() { return this.contents.length; }
+ }
+ });
+
+ var stream_ops = {};
+ for (const [key, fn] of Object.entries(node.stream_ops)) {
+ stream_ops[key] = (...args) => {
+ FS.forceLoadFile(node);
+ return fn(...args);
+ };
+ }
+ function writeChunks(stream, buffer, offset, length, position) {
+ var contents = stream.node.contents;
+ if (position >= contents.length)
+ return 0;
+ var size = Math.min(contents.length - position, length);
+ if (contents.slice) {
+ for (var i = 0; i < size; i++) {
+ buffer[offset + i] = contents[position + i];
+ }
+ } else {
+ for (var i = 0; i < size; i++) {
+ buffer[offset + i] = contents.get(position + i);
+ }
+ }
+ return size;
+ }
+
+ stream_ops.read = (stream, buffer, offset, length, position) => {
+ FS.forceLoadFile(node);
+ return writeChunks(stream, buffer, offset, length, position)
+ };
+
+ stream_ops.mmap = (stream, length, position, prot, flags) => {
+ FS.forceLoadFile(node);
+ var ptr = mmapAlloc(length);
+ if (!ptr) {
+ throw new FS.ErrnoError(48);
+ }
+ writeChunks(stream, HEAP8, ptr, length, position);
+ return { ptr, allocated: true };
+ };
+ node.stream_ops = stream_ops;
+ return node;
+ },
+ };
+
+
+
+
+ var UTF8ToString = (ptr, maxBytesToRead, ignoreNul) => {
+ if (!ptr) return '';
+ var end = findStringEnd(HEAPU8, ptr, maxBytesToRead, ignoreNul);
+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end));
+ };
+ var SYSCALLS = {
+ calculateAt(dirfd, path, allowEmpty) {
+ if (PATH.isAbs(path)) {
+ return path;
+ }
+
+ var dir;
+ if (dirfd === -100) {
+ dir = FS.cwd();
+ } else {
+ var dirstream = SYSCALLS.getStreamFromFD(dirfd);
+ dir = dirstream.path;
+ }
+ if (path.length == 0) {
+ if (!allowEmpty) {
+ throw new FS.ErrnoError(44);;
+ }
+ return dir;
+ }
+ return dir + '/' + path;
+ },
+ writeStat(buf, stat) {
+ HEAPU32[((buf)>>2)] = stat.dev;
+ HEAPU32[(((buf)+(4))>>2)] = stat.mode;
+ HEAPU32[(((buf)+(8))>>2)] = stat.nlink;
+ HEAPU32[(((buf)+(12))>>2)] = stat.uid;
+ HEAPU32[(((buf)+(16))>>2)] = stat.gid;
+ HEAPU32[(((buf)+(20))>>2)] = stat.rdev;
+ HEAP64[(((buf)+(24))>>3)] = BigInt(stat.size);
+ HEAP32[(((buf)+(32))>>2)] = 4096;
+ HEAP32[(((buf)+(36))>>2)] = stat.blocks;
+ var atime = stat.atime.getTime();
+ var mtime = stat.mtime.getTime();
+ var ctime = stat.ctime.getTime();
+ HEAP64[(((buf)+(40))>>3)] = BigInt(Math.floor(atime / 1000));
+ HEAPU32[(((buf)+(48))>>2)] = (atime % 1000) * 1000 * 1000;
+ HEAP64[(((buf)+(56))>>3)] = BigInt(Math.floor(mtime / 1000));
+ HEAPU32[(((buf)+(64))>>2)] = (mtime % 1000) * 1000 * 1000;
+ HEAP64[(((buf)+(72))>>3)] = BigInt(Math.floor(ctime / 1000));
+ HEAPU32[(((buf)+(80))>>2)] = (ctime % 1000) * 1000 * 1000;
+ HEAP64[(((buf)+(88))>>3)] = BigInt(stat.ino);
+ return 0;
+ },
+ writeStatFs(buf, stats) {
+ HEAPU32[(((buf)+(4))>>2)] = stats.bsize;
+ HEAPU32[(((buf)+(60))>>2)] = stats.bsize;
+ HEAP64[(((buf)+(8))>>3)] = BigInt(stats.blocks);
+ HEAP64[(((buf)+(16))>>3)] = BigInt(stats.bfree);
+ HEAP64[(((buf)+(24))>>3)] = BigInt(stats.bavail);
+ HEAP64[(((buf)+(32))>>3)] = BigInt(stats.files);
+ HEAP64[(((buf)+(40))>>3)] = BigInt(stats.ffree);
+ HEAPU32[(((buf)+(48))>>2)] = stats.fsid;
+ HEAPU32[(((buf)+(64))>>2)] = stats.flags;
+ HEAPU32[(((buf)+(56))>>2)] = stats.namelen;
+ },
+ doMsync(addr, stream, len, flags, offset) {
+ if (!FS.isFile(stream.node.mode)) {
+ throw new FS.ErrnoError(43);
+ }
+ if (flags & 2) {
+
+ return 0;
+ }
+ var buffer = HEAPU8.slice(addr, addr + len);
+ FS.msync(stream, buffer, offset, len, flags);
+ },
+ getStreamFromFD(fd) {
+ var stream = FS.getStreamChecked(fd);
+ return stream;
+ },
+ varargs:undefined,
+ getStr(ptr) {
+ var ret = UTF8ToString(ptr);
+ return ret;
+ },
+ };
+ function ___syscall_chmod(path, mode) {
+ try {
+
+ path = SYSCALLS.getStr(path);
+ FS.chmod(path, mode);
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ function ___syscall_faccessat(dirfd, path, amode, flags) {
+ try {
+
+ path = SYSCALLS.getStr(path);
+ path = SYSCALLS.calculateAt(dirfd, path);
+ if (amode & ~7) {
+
+ return -28;
+ }
+ var lookup = FS.lookupPath(path, { follow: true });
+ var node = lookup.node;
+ if (!node) {
+ return -44;
+ }
+ var perms = '';
+ if (amode & 4) perms += 'r';
+ if (amode & 2) perms += 'w';
+ if (amode & 1) perms += 'x';
+ if (perms && FS.nodePermissions(node, perms)) {
+ return -2;
+ }
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ function ___syscall_fchmod(fd, mode) {
+ try {
+
+ FS.fchmod(fd, mode);
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ function ___syscall_fchown32(fd, owner, group) {
+ try {
+
+ FS.fchown(fd, owner, group);
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ var syscallGetVarargI = () => {
+
+ var ret = HEAP32[((+SYSCALLS.varargs)>>2)];
+ SYSCALLS.varargs += 4;
+ return ret;
+ };
+ var syscallGetVarargP = syscallGetVarargI;
+
+
+ function ___syscall_fcntl64(fd, cmd, varargs) {
+ SYSCALLS.varargs = varargs;
+ try {
+
+ var stream = SYSCALLS.getStreamFromFD(fd);
+ switch (cmd) {
+ case 0: {
+ var arg = syscallGetVarargI();
+ if (arg < 0) {
+ return -28;
+ }
+ while (FS.streams[arg]) {
+ arg++;
+ }
+ var newStream;
+ newStream = FS.dupStream(stream, arg);
+ return newStream.fd;
+ }
+ case 1:
+ case 2:
+ return 0;
+ case 3:
+ return stream.flags;
+ case 4: {
+ var arg = syscallGetVarargI();
+ stream.flags |= arg;
+ return 0;
+ }
+ case 12: {
+ var arg = syscallGetVarargP();
+ var offset = 0;
+
+ HEAP16[(((arg)+(offset))>>1)] = 2;
+ return 0;
+ }
+ case 13:
+ case 14:
+
+
+
+
+ return 0;
+ }
+ return -28;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ function ___syscall_fstat64(fd, buf) {
+ try {
+
+ return SYSCALLS.writeStat(buf, FS.fstat(fd));
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ var INT53_MAX = 9007199254740992;
+
+ var INT53_MIN = -9007199254740992;
+ var bigintToI53Checked = (num) => (num < INT53_MIN || num > INT53_MAX) ? NaN : Number(num);
+ function ___syscall_ftruncate64(fd, length) {
+ length = bigintToI53Checked(length);
+
+
+ try {
+
+ if (isNaN(length)) return -61;
+ FS.ftruncate(fd, length);
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ ;
+ }
+
+
+ var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {
+ return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
+ };
+ function ___syscall_getcwd(buf, size) {
+ try {
+
+ if (size === 0) return -28;
+ var cwd = FS.cwd();
+ var cwdLengthInBytes = lengthBytesUTF8(cwd) + 1;
+ if (size < cwdLengthInBytes) return -68;
+ stringToUTF8(cwd, buf, size);
+ return cwdLengthInBytes;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+
+ function ___syscall_ioctl(fd, op, varargs) {
+ SYSCALLS.varargs = varargs;
+ try {
+
+ var stream = SYSCALLS.getStreamFromFD(fd);
+ switch (op) {
+ case 21509: {
+ if (!stream.tty) return -59;
+ return 0;
+ }
+ case 21505: {
+ if (!stream.tty) return -59;
+ if (stream.tty.ops.ioctl_tcgets) {
+ var termios = stream.tty.ops.ioctl_tcgets(stream);
+ var argp = syscallGetVarargP();
+ HEAP32[((argp)>>2)] = termios.c_iflag || 0;
+ HEAP32[(((argp)+(4))>>2)] = termios.c_oflag || 0;
+ HEAP32[(((argp)+(8))>>2)] = termios.c_cflag || 0;
+ HEAP32[(((argp)+(12))>>2)] = termios.c_lflag || 0;
+ for (var i = 0; i < 32; i++) {
+ HEAP8[(argp + i)+(17)] = termios.c_cc[i] || 0;
+ }
+ return 0;
+ }
+ return 0;
+ }
+ case 21510:
+ case 21511:
+ case 21512: {
+ if (!stream.tty) return -59;
+ return 0;
+ }
+ case 21506:
+ case 21507:
+ case 21508: {
+ if (!stream.tty) return -59;
+ if (stream.tty.ops.ioctl_tcsets) {
+ var argp = syscallGetVarargP();
+ var c_iflag = HEAP32[((argp)>>2)];
+ var c_oflag = HEAP32[(((argp)+(4))>>2)];
+ var c_cflag = HEAP32[(((argp)+(8))>>2)];
+ var c_lflag = HEAP32[(((argp)+(12))>>2)];
+ var c_cc = []
+ for (var i = 0; i < 32; i++) {
+ c_cc.push(HEAP8[(argp + i)+(17)]);
+ }
+ return stream.tty.ops.ioctl_tcsets(stream.tty, op, { c_iflag, c_oflag, c_cflag, c_lflag, c_cc });
+ }
+ return 0;
+ }
+ case 21519: {
+ if (!stream.tty) return -59;
+ var argp = syscallGetVarargP();
+ HEAP32[((argp)>>2)] = 0;
+ return 0;
+ }
+ case 21520: {
+ if (!stream.tty) return -59;
+ return -28;
+ }
+ case 21537:
+ case 21531: {
+ var argp = syscallGetVarargP();
+ return FS.ioctl(stream, op, argp);
+ }
+ case 21523: {
+
+
+ if (!stream.tty) return -59;
+ if (stream.tty.ops.ioctl_tiocgwinsz) {
+ var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);
+ var argp = syscallGetVarargP();
+ HEAP16[((argp)>>1)] = winsize[0];
+ HEAP16[(((argp)+(2))>>1)] = winsize[1];
+ }
+ return 0;
+ }
+ case 21524: {
+
+
+
+ if (!stream.tty) return -59;
+ return 0;
+ }
+ case 21515: {
+ if (!stream.tty) return -59;
+ return 0;
+ }
+ default: return -28;
+ }
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ function ___syscall_lstat64(path, buf) {
+ try {
+
+ path = SYSCALLS.getStr(path);
+ return SYSCALLS.writeStat(buf, FS.lstat(path));
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ function ___syscall_mkdirat(dirfd, path, mode) {
+ try {
+
+ path = SYSCALLS.getStr(path);
+ path = SYSCALLS.calculateAt(dirfd, path);
+ FS.mkdir(path, mode, 0);
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ function ___syscall_newfstatat(dirfd, path, buf, flags) {
+ try {
+
+ path = SYSCALLS.getStr(path);
+ var nofollow = flags & 256;
+ var allowEmpty = flags & 4096;
+ flags = flags & (~6400);
+ path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);
+ return SYSCALLS.writeStat(buf, nofollow ? FS.lstat(path) : FS.stat(path));
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+
+ function ___syscall_openat(dirfd, path, flags, varargs) {
+ SYSCALLS.varargs = varargs;
+ try {
+
+ path = SYSCALLS.getStr(path);
+ path = SYSCALLS.calculateAt(dirfd, path);
+ var mode = varargs ? syscallGetVarargI() : 0;
+ return FS.open(path, flags, mode).fd;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+
+
+ function ___syscall_readlinkat(dirfd, path, buf, bufsize) {
+ try {
+
+ path = SYSCALLS.getStr(path);
+ path = SYSCALLS.calculateAt(dirfd, path);
+ if (bufsize <= 0) return -28;
+ var ret = FS.readlink(path);
+
+ var len = Math.min(bufsize, lengthBytesUTF8(ret));
+ var endChar = HEAP8[buf+len];
+ stringToUTF8(ret, buf, bufsize+1);
+
+
+ HEAP8[buf+len] = endChar;
+ return len;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ function ___syscall_rmdir(path) {
+ try {
+
+ path = SYSCALLS.getStr(path);
+ FS.rmdir(path);
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ function ___syscall_stat64(path, buf) {
+ try {
+
+ path = SYSCALLS.getStr(path);
+ return SYSCALLS.writeStat(buf, FS.stat(path));
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ function ___syscall_unlinkat(dirfd, path, flags) {
+ try {
+
+ path = SYSCALLS.getStr(path);
+ path = SYSCALLS.calculateAt(dirfd, path);
+ if (!flags) {
+ FS.unlink(path);
+ } else if (flags === 512) {
+ FS.rmdir(path);
+ } else {
+ return -28;
+ }
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ var readI53FromI64 = (ptr) => {
+ return HEAPU32[((ptr)>>2)] + HEAP32[(((ptr)+(4))>>2)] * 4294967296;
+ };
+
+ function ___syscall_utimensat(dirfd, path, times, flags) {
+ try {
+
+ path = SYSCALLS.getStr(path);
+ path = SYSCALLS.calculateAt(dirfd, path, true);
+ var now = Date.now(), atime, mtime;
+ if (!times) {
+ atime = now;
+ mtime = now;
+ } else {
+ var seconds = readI53FromI64(times);
+ var nanoseconds = HEAP32[(((times)+(8))>>2)];
+ if (nanoseconds == 1073741823) {
+ atime = now;
+ } else if (nanoseconds == 1073741822) {
+ atime = null;
+ } else {
+ atime = (seconds*1000) + (nanoseconds/(1000*1000));
+ }
+ times += 16;
+ seconds = readI53FromI64(times);
+ nanoseconds = HEAP32[(((times)+(8))>>2)];
+ if (nanoseconds == 1073741823) {
+ mtime = now;
+ } else if (nanoseconds == 1073741822) {
+ mtime = null;
+ } else {
+ mtime = (seconds*1000) + (nanoseconds/(1000*1000));
+ }
+ }
+
+
+ if ((mtime ?? atime) !== null) {
+ FS.utime(path, atime, mtime);
+ }
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ }
+
+ var isLeapYear = (year) => year%4 === 0 && (year%100 !== 0 || year%400 === 0);
+
+ var MONTH_DAYS_LEAP_CUMULATIVE = [0,31,60,91,121,152,182,213,244,274,305,335];
+
+ var MONTH_DAYS_REGULAR_CUMULATIVE = [0,31,59,90,120,151,181,212,243,273,304,334];
+ var ydayFromDate = (date) => {
+ var leap = isLeapYear(date.getFullYear());
+ var monthDaysCumulative = (leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE);
+ var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;
+
+ return yday;
+ };
+
+ function __localtime_js(time, tmPtr) {
+ time = bigintToI53Checked(time);
+
+
+ var date = new Date(time*1000);
+ HEAP32[((tmPtr)>>2)] = date.getSeconds();
+ HEAP32[(((tmPtr)+(4))>>2)] = date.getMinutes();
+ HEAP32[(((tmPtr)+(8))>>2)] = date.getHours();
+ HEAP32[(((tmPtr)+(12))>>2)] = date.getDate();
+ HEAP32[(((tmPtr)+(16))>>2)] = date.getMonth();
+ HEAP32[(((tmPtr)+(20))>>2)] = date.getFullYear()-1900;
+ HEAP32[(((tmPtr)+(24))>>2)] = date.getDay();
+
+ var yday = ydayFromDate(date)|0;
+ HEAP32[(((tmPtr)+(28))>>2)] = yday;
+ HEAP32[(((tmPtr)+(36))>>2)] = -(date.getTimezoneOffset() * 60);
+
+
+ var start = new Date(date.getFullYear(), 0, 1);
+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
+ var winterOffset = start.getTimezoneOffset();
+ var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset))|0;
+ HEAP32[(((tmPtr)+(32))>>2)] = dst;
+ ;
+ }
+
+
+
+
+
+
+ function __mmap_js(len, prot, flags, fd, offset, allocated, addr) {
+ offset = bigintToI53Checked(offset);
+
+
+ try {
+
+ var stream = SYSCALLS.getStreamFromFD(fd);
+ var res = FS.mmap(stream, len, offset, prot, flags);
+ var ptr = res.ptr;
+ HEAP32[((allocated)>>2)] = res.allocated;
+ HEAPU32[((addr)>>2)] = ptr;
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ ;
+ }
+
+
+ function __munmap_js(addr, len, prot, flags, fd, offset) {
+ offset = bigintToI53Checked(offset);
+
+
+ try {
+
+ var stream = SYSCALLS.getStreamFromFD(fd);
+ if (prot & 2) {
+ SYSCALLS.doMsync(addr, stream, len, flags, offset);
+ }
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return -e.errno;
+ }
+ ;
+ }
+
+ var __tzset_js = (timezone, daylight, std_name, dst_name) => {
+
+ var currentYear = new Date().getFullYear();
+ var winter = new Date(currentYear, 0, 1);
+ var summer = new Date(currentYear, 6, 1);
+ var winterOffset = winter.getTimezoneOffset();
+ var summerOffset = summer.getTimezoneOffset();
+
+
+
+
+
+
+
+ var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
+
+
+
+
+
+
+ HEAPU32[((timezone)>>2)] = stdTimezoneOffset * 60;
+
+ HEAP32[((daylight)>>2)] = Number(winterOffset != summerOffset);
+
+ var extractZone = (timezoneOffset) => {
+
+
+ var sign = timezoneOffset >= 0 ? "-" : "+";
+
+ var absOffset = Math.abs(timezoneOffset)
+ var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");
+ var minutes = String(absOffset % 60).padStart(2, "0");
+
+ return `UTC${sign}${hours}${minutes}`;
+ }
+
+ var winterName = extractZone(winterOffset);
+ var summerName = extractZone(summerOffset);
+ if (summerOffset < winterOffset) {
+
+ stringToUTF8(winterName, std_name, 17);
+ stringToUTF8(summerName, dst_name, 17);
+ } else {
+ stringToUTF8(winterName, dst_name, 17);
+ stringToUTF8(summerName, std_name, 17);
+ }
+ };
+
+ var _emscripten_get_now = () => performance.now();
+
+ var _emscripten_date_now = () => Date.now();
+
+ var nowIsMonotonic = 1;
+
+ var checkWasiClock = (clock_id) => clock_id >= 0 && clock_id <= 3;
+
+ function _clock_time_get(clk_id, ignored_precision, ptime) {
+ ignored_precision = bigintToI53Checked(ignored_precision);
+
+
+ if (!checkWasiClock(clk_id)) {
+ return 28;
+ }
+ var now;
+
+ if (clk_id === 0) {
+ now = _emscripten_date_now();
+ } else if (nowIsMonotonic) {
+ now = _emscripten_get_now();
+ } else {
+ return 52;
+ }
+
+ var nsec = Math.round(now * 1000 * 1000);
+ HEAP64[((ptime)>>3)] = BigInt(nsec);
+ return 0;
+ ;
+ }
+
+
+ var getHeapMax = () =>
+
+
+
+
+ 2147483648;
+ var _emscripten_get_heap_max = () => getHeapMax();
+
+
+
+
+ var growMemory = (size) => {
+ var oldHeapSize = wasmMemory.buffer.byteLength;
+ var pages = ((size - oldHeapSize + 65535) / 65536) | 0;
+ try {
+
+ wasmMemory.grow(pages);
+ updateMemoryViews();
+ return 1 ;
+ } catch(e) {
+ }
+
+
+ };
+ var _emscripten_resize_heap = (requestedSize) => {
+ var oldSize = HEAPU8.length;
+
+ requestedSize >>>= 0;
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ var maxHeapSize = getHeapMax();
+ if (requestedSize > maxHeapSize) {
+ return false;
+ }
+
+
+
+
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
+
+ overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296 );
+
+ var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));
+
+ var replacement = growMemory(newSize);
+ if (replacement) {
+
+ return true;
+ }
+ }
+ return false;
+ };
+
+ var ENV = {
+ };
+
+ var getExecutableName = () => thisProgram || './this.program';
+ var getEnvStrings = () => {
+ if (!getEnvStrings.strings) {
+
+
+ var lang = (globalThis.navigator?.language ?? 'C').replace('-', '_') + '.UTF-8';
+ var env = {
+ 'USER': 'web_user',
+ 'LOGNAME': 'web_user',
+ 'PATH': '/',
+ 'PWD': '/',
+ 'HOME': '/home/web_user',
+ 'LANG': lang,
+ '_': getExecutableName()
+ };
+
+ for (var x in ENV) {
+
+
+
+ if (ENV[x] === undefined) delete env[x];
+ else env[x] = ENV[x];
+ }
+ var strings = [];
+ for (var x in env) {
+ strings.push(`${x}=${env[x]}`);
+ }
+ getEnvStrings.strings = strings;
+ }
+ return getEnvStrings.strings;
+ };
+
+ var _environ_get = (__environ, environ_buf) => {
+ var bufSize = 0;
+ var envp = 0;
+ for (var string of getEnvStrings()) {
+ var ptr = environ_buf + bufSize;
+ HEAPU32[(((__environ)+(envp))>>2)] = ptr;
+ bufSize += stringToUTF8(string, ptr, Infinity) + 1;
+ envp += 4;
+ }
+ return 0;
+ };
+
+
+ var _environ_sizes_get = (penviron_count, penviron_buf_size) => {
+ var strings = getEnvStrings();
+ HEAPU32[((penviron_count)>>2)] = strings.length;
+ var bufSize = 0;
+ for (var string of strings) {
+ bufSize += lengthBytesUTF8(string) + 1;
+ }
+ HEAPU32[((penviron_buf_size)>>2)] = bufSize;
+ return 0;
+ };
+
+ function _fd_close(fd) {
+ try {
+
+ var stream = SYSCALLS.getStreamFromFD(fd);
+ FS.close(stream);
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return e.errno;
+ }
+ }
+
+ function _fd_fdstat_get(fd, pbuf) {
+ try {
+
+ var rightsBase = 0;
+ var rightsInheriting = 0;
+ var flags = 0;
+ {
+ var stream = SYSCALLS.getStreamFromFD(fd);
+
+
+ var type = stream.tty ? 2 :
+ FS.isDir(stream.mode) ? 3 :
+ FS.isLink(stream.mode) ? 7 :
+ 4;
+ }
+ HEAP8[pbuf] = type;
+ HEAP16[(((pbuf)+(2))>>1)] = flags;
+ HEAP64[(((pbuf)+(8))>>3)] = BigInt(rightsBase);
+ HEAP64[(((pbuf)+(16))>>3)] = BigInt(rightsInheriting);
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return e.errno;
+ }
+ }
+
+
+ var doReadv = (stream, iov, iovcnt, offset) => {
+ var ret = 0;
+ for (var i = 0; i < iovcnt; i++) {
+ var ptr = HEAPU32[((iov)>>2)];
+ var len = HEAPU32[(((iov)+(4))>>2)];
+ iov += 8;
+ var curr = FS.read(stream, HEAP8, ptr, len, offset);
+ if (curr < 0) return -1;
+ ret += curr;
+ if (curr < len) break;
+ if (typeof offset != 'undefined') {
+ offset += curr;
+ }
+ }
+ return ret;
+ };
+
+ function _fd_read(fd, iov, iovcnt, pnum) {
+ try {
+
+ var stream = SYSCALLS.getStreamFromFD(fd);
+ var num = doReadv(stream, iov, iovcnt);
+ HEAPU32[((pnum)>>2)] = num;
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return e.errno;
+ }
+ }
+
+
+ function _fd_seek(fd, offset, whence, newOffset) {
+ offset = bigintToI53Checked(offset);
+
+
+ try {
+
+ if (isNaN(offset)) return 61;
+ var stream = SYSCALLS.getStreamFromFD(fd);
+ FS.llseek(stream, offset, whence);
+ HEAP64[((newOffset)>>3)] = BigInt(stream.position);
+ if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return e.errno;
+ }
+ ;
+ }
+
+ function _fd_sync(fd) {
+ try {
+
+ var stream = SYSCALLS.getStreamFromFD(fd);
+ var rtn = stream.stream_ops?.fsync?.(stream);
+ return rtn;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return e.errno;
+ }
+ }
+
+
+ var doWritev = (stream, iov, iovcnt, offset) => {
+ var ret = 0;
+ for (var i = 0; i < iovcnt; i++) {
+ var ptr = HEAPU32[((iov)>>2)];
+ var len = HEAPU32[(((iov)+(4))>>2)];
+ iov += 8;
+ var curr = FS.write(stream, HEAP8, ptr, len, offset);
+ if (curr < 0) return -1;
+ ret += curr;
+ if (curr < len) {
+
+ break;
+ }
+ if (typeof offset != 'undefined') {
+ offset += curr;
+ }
+ }
+ return ret;
+ };
+
+ function _fd_write(fd, iov, iovcnt, pnum) {
+ try {
+
+ var stream = SYSCALLS.getStreamFromFD(fd);
+ var num = doWritev(stream, iov, iovcnt);
+ HEAPU32[((pnum)>>2)] = num;
+ return 0;
+ } catch (e) {
+ if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e;
+ return e.errno;
+ }
+ }
+
+
+ FS.createPreloadedFile = FS_createPreloadedFile;
+ FS.preloadFile = FS_preloadFile;
+ FS.staticInit();;
+
+
+
+
+
+
+{
+
+
+ initMemory();
+
+
+ if (Module['noExitRuntime']) noExitRuntime = Module['noExitRuntime'];
+if (Module['preloadPlugins']) preloadPlugins = Module['preloadPlugins'];
+if (Module['print']) out = Module['print'];
+if (Module['printErr']) err = Module['printErr'];
+if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];
+
+
+ if (Module['arguments']) arguments_ = Module['arguments'];
+ if (Module['thisProgram']) thisProgram = Module['thisProgram'];
+
+ if (Module['preInit']) {
+ if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
+ while (Module['preInit'].length > 0) {
+ Module['preInit'].shift()();
+ }
+ }
+}
+
+
+ Module['wasmMemory'] = wasmMemory;
+
+
+
+
+
+
+
+
+var _sqlite3_status64,
+ _sqlite3_status,
+ _sqlite3_db_status64,
+ _sqlite3_msize,
+ _sqlite3_db_status,
+ _sqlite3_vfs_find,
+ _sqlite3_initialize,
+ _sqlite3_malloc,
+ _sqlite3_free,
+ _sqlite3_vfs_register,
+ _sqlite3_vfs_unregister,
+ _sqlite3_malloc64,
+ _sqlite3_realloc,
+ _sqlite3_realloc64,
+ _sqlite3_value_text,
+ _sqlite3_randomness,
+ _sqlite3_stricmp,
+ _sqlite3_strnicmp,
+ _sqlite3_uri_parameter,
+ _sqlite3_uri_boolean,
+ _sqlite3_serialize,
+ _sqlite3_prepare_v2,
+ _sqlite3_step,
+ _sqlite3_column_int64,
+ _sqlite3_reset,
+ _sqlite3_exec,
+ _sqlite3_column_int,
+ _sqlite3_finalize,
+ _sqlite3_file_control,
+ _sqlite3_column_name,
+ _sqlite3_column_text,
+ _sqlite3_column_type,
+ _sqlite3_errmsg,
+ _sqlite3_deserialize,
+ _sqlite3_clear_bindings,
+ _sqlite3_value_blob,
+ _sqlite3_value_bytes,
+ _sqlite3_value_double,
+ _sqlite3_value_int,
+ _sqlite3_value_int64,
+ _sqlite3_value_subtype,
+ _sqlite3_value_pointer,
+ _sqlite3_value_type,
+ _sqlite3_value_nochange,
+ _sqlite3_value_frombind,
+ _sqlite3_value_dup,
+ _sqlite3_value_free,
+ _sqlite3_result_blob,
+ _sqlite3_result_error_toobig,
+ _sqlite3_result_error_nomem,
+ _sqlite3_result_double,
+ _sqlite3_result_error,
+ _sqlite3_result_int,
+ _sqlite3_result_int64,
+ _sqlite3_result_null,
+ _sqlite3_result_pointer,
+ _sqlite3_result_subtype,
+ _sqlite3_result_text,
+ _sqlite3_result_zeroblob,
+ _sqlite3_result_zeroblob64,
+ _sqlite3_result_error_code,
+ _sqlite3_user_data,
+ _sqlite3_context_db_handle,
+ _sqlite3_vtab_nochange,
+ _sqlite3_vtab_in_first,
+ _sqlite3_vtab_in_next,
+ _sqlite3_aggregate_context,
+ _sqlite3_get_auxdata,
+ _sqlite3_set_auxdata,
+ _sqlite3_column_count,
+ _sqlite3_data_count,
+ _sqlite3_column_blob,
+ _sqlite3_column_bytes,
+ _sqlite3_column_double,
+ _sqlite3_column_value,
+ _sqlite3_column_decltype,
+ _sqlite3_column_database_name,
+ _sqlite3_column_table_name,
+ _sqlite3_column_origin_name,
+ _sqlite3_bind_blob,
+ _sqlite3_bind_double,
+ _sqlite3_bind_int,
+ _sqlite3_bind_int64,
+ _sqlite3_bind_null,
+ _sqlite3_bind_pointer,
+ _sqlite3_bind_text,
+ _sqlite3_bind_zeroblob,
+ _sqlite3_bind_parameter_count,
+ _sqlite3_bind_parameter_name,
+ _sqlite3_bind_parameter_index,
+ _sqlite3_db_handle,
+ _sqlite3_stmt_readonly,
+ _sqlite3_stmt_isexplain,
+ _sqlite3_stmt_explain,
+ _sqlite3_stmt_busy,
+ _sqlite3_next_stmt,
+ _sqlite3_stmt_status,
+ _sqlite3_sql,
+ _sqlite3_expanded_sql,
+ _sqlite3_preupdate_old,
+ _sqlite3_preupdate_count,
+ _sqlite3_preupdate_depth,
+ _sqlite3_preupdate_blobwrite,
+ _sqlite3_preupdate_new,
+ _sqlite3_value_numeric_type,
+ _sqlite3_set_authorizer,
+ _sqlite3_strglob,
+ _sqlite3_strlike,
+ _sqlite3_auto_extension,
+ _sqlite3_cancel_auto_extension,
+ _sqlite3_reset_auto_extension,
+ _sqlite3_prepare_v3,
+ _sqlite3_create_module,
+ _sqlite3_create_module_v2,
+ _sqlite3_drop_modules,
+ _sqlite3_declare_vtab,
+ _sqlite3_vtab_on_conflict,
+ _sqlite3_vtab_collation,
+ _sqlite3_vtab_in,
+ _sqlite3_vtab_rhs_value,
+ _sqlite3_vtab_distinct,
+ _sqlite3_keyword_name,
+ _sqlite3_keyword_count,
+ _sqlite3_keyword_check,
+ _sqlite3_complete,
+ _sqlite3_libversion,
+ _sqlite3_libversion_number,
+ _sqlite3_shutdown,
+ _sqlite3_last_insert_rowid,
+ _sqlite3_set_last_insert_rowid,
+ _sqlite3_changes64,
+ _sqlite3_changes,
+ _sqlite3_total_changes64,
+ _sqlite3_total_changes,
+ _sqlite3_txn_state,
+ _sqlite3_close_v2,
+ _sqlite3_busy_handler,
+ _sqlite3_progress_handler,
+ _sqlite3_busy_timeout,
+ _sqlite3_interrupt,
+ _sqlite3_is_interrupted,
+ _sqlite3_create_function,
+ _sqlite3_create_function_v2,
+ _sqlite3_create_window_function,
+ _sqlite3_overload_function,
+ _sqlite3_trace_v2,
+ _sqlite3_commit_hook,
+ _sqlite3_update_hook,
+ _sqlite3_rollback_hook,
+ _sqlite3_preupdate_hook,
+ _sqlite3_set_errmsg,
+ _sqlite3_error_offset,
+ _sqlite3_errcode,
+ _sqlite3_extended_errcode,
+ _sqlite3_errstr,
+ _sqlite3_limit,
+ _sqlite3_open,
+ _sqlite3_open_v2,
+ _sqlite3_create_collation,
+ _sqlite3_create_collation_v2,
+ _sqlite3_collation_needed,
+ _sqlite3_get_autocommit,
+ _sqlite3_table_column_metadata,
+ _sqlite3_extended_result_codes,
+ _sqlite3_uri_key,
+ _sqlite3_uri_int64,
+ _sqlite3_db_name,
+ _sqlite3_db_filename,
+ _sqlite3_db_readonly,
+ _sqlite3_compileoption_used,
+ _sqlite3_compileoption_get,
+ _sqlite3session_diff,
+ _sqlite3session_attach,
+ _sqlite3session_create,
+ _sqlite3session_delete,
+ _sqlite3session_table_filter,
+ _sqlite3session_changeset,
+ _sqlite3session_changeset_strm,
+ _sqlite3session_patchset_strm,
+ _sqlite3session_patchset,
+ _sqlite3session_enable,
+ _sqlite3session_indirect,
+ _sqlite3session_isempty,
+ _sqlite3session_memory_used,
+ _sqlite3session_object_config,
+ _sqlite3session_changeset_size,
+ _sqlite3changeset_start,
+ _sqlite3changeset_start_v2,
+ _sqlite3changeset_start_strm,
+ _sqlite3changeset_start_v2_strm,
+ _sqlite3changeset_next,
+ _sqlite3changeset_op,
+ _sqlite3changeset_pk,
+ _sqlite3changeset_old,
+ _sqlite3changeset_new,
+ _sqlite3changeset_conflict,
+ _sqlite3changeset_fk_conflicts,
+ _sqlite3changeset_finalize,
+ _sqlite3changeset_invert,
+ _sqlite3changeset_invert_strm,
+ _sqlite3changeset_apply_v2,
+ _sqlite3changeset_apply_v3,
+ _sqlite3changeset_apply,
+ _sqlite3changeset_apply_v3_strm,
+ _sqlite3changeset_apply_v2_strm,
+ _sqlite3changeset_apply_strm,
+ _sqlite3changegroup_new,
+ _sqlite3changegroup_add,
+ _sqlite3changegroup_output,
+ _sqlite3changegroup_add_strm,
+ _sqlite3changegroup_output_strm,
+ _sqlite3changegroup_delete,
+ _sqlite3changeset_concat,
+ _sqlite3changeset_concat_strm,
+ _sqlite3session_config,
+ _sqlite3_sourceid,
+ _sqlite3__wasm_pstack_ptr,
+ _sqlite3__wasm_pstack_restore,
+ _sqlite3__wasm_pstack_alloc,
+ _sqlite3__wasm_pstack_remaining,
+ _sqlite3__wasm_pstack_quota,
+ _sqlite3__wasm_test_struct,
+ _sqlite3__wasm_enum_json,
+ _sqlite3__wasm_vfs_unlink,
+ _sqlite3__wasm_db_vfs,
+ _sqlite3__wasm_db_reset,
+ _sqlite3__wasm_db_export_chunked,
+ _sqlite3__wasm_db_serialize,
+ _sqlite3__wasm_vfs_create_file,
+ _sqlite3__wasm_posix_create_file,
+ _sqlite3__wasm_kvvfsMakeKey,
+ _sqlite3__wasm_kvvfs_methods,
+ _sqlite3__wasm_vtab_config,
+ _sqlite3__wasm_db_config_ip,
+ _sqlite3__wasm_db_config_pii,
+ _sqlite3__wasm_db_config_s,
+ _sqlite3__wasm_config_i,
+ _sqlite3__wasm_config_ii,
+ _sqlite3__wasm_config_j,
+ _sqlite3__wasm_qfmt_token,
+ _sqlite3__wasm_kvvfs_decode,
+ _sqlite3__wasm_kvvfs_encode,
+ _sqlite3__wasm_init_wasmfs,
+ _sqlite3__wasm_test_intptr,
+ _sqlite3__wasm_test_voidptr,
+ _sqlite3__wasm_test_int64_max,
+ _sqlite3__wasm_test_int64_min,
+ _sqlite3__wasm_test_int64_times2,
+ _sqlite3__wasm_test_int64_minmax,
+ _sqlite3__wasm_test_int64ptr,
+ _sqlite3__wasm_test_stack_overflow,
+ _sqlite3__wasm_test_str_hello,
+ _sqlite3__wasm_SQLTester_strglob,
+ _malloc,
+ _free,
+ _realloc,
+ _emscripten_builtin_memalign,
+ __emscripten_stack_restore,
+ __emscripten_stack_alloc,
+ _emscripten_stack_get_current,
+ __indirect_function_table;
+
+
+function assignWasmExports(wasmExports) {
+ _sqlite3_status64 = Module['_sqlite3_status64'] = wasmExports['sqlite3_status64'];
+ _sqlite3_status = Module['_sqlite3_status'] = wasmExports['sqlite3_status'];
+ _sqlite3_db_status64 = Module['_sqlite3_db_status64'] = wasmExports['sqlite3_db_status64'];
+ _sqlite3_msize = Module['_sqlite3_msize'] = wasmExports['sqlite3_msize'];
+ _sqlite3_db_status = Module['_sqlite3_db_status'] = wasmExports['sqlite3_db_status'];
+ _sqlite3_vfs_find = Module['_sqlite3_vfs_find'] = wasmExports['sqlite3_vfs_find'];
+ _sqlite3_initialize = Module['_sqlite3_initialize'] = wasmExports['sqlite3_initialize'];
+ _sqlite3_malloc = Module['_sqlite3_malloc'] = wasmExports['sqlite3_malloc'];
+ _sqlite3_free = Module['_sqlite3_free'] = wasmExports['sqlite3_free'];
+ _sqlite3_vfs_register = Module['_sqlite3_vfs_register'] = wasmExports['sqlite3_vfs_register'];
+ _sqlite3_vfs_unregister = Module['_sqlite3_vfs_unregister'] = wasmExports['sqlite3_vfs_unregister'];
+ _sqlite3_malloc64 = Module['_sqlite3_malloc64'] = wasmExports['sqlite3_malloc64'];
+ _sqlite3_realloc = Module['_sqlite3_realloc'] = wasmExports['sqlite3_realloc'];
+ _sqlite3_realloc64 = Module['_sqlite3_realloc64'] = wasmExports['sqlite3_realloc64'];
+ _sqlite3_value_text = Module['_sqlite3_value_text'] = wasmExports['sqlite3_value_text'];
+ _sqlite3_randomness = Module['_sqlite3_randomness'] = wasmExports['sqlite3_randomness'];
+ _sqlite3_stricmp = Module['_sqlite3_stricmp'] = wasmExports['sqlite3_stricmp'];
+ _sqlite3_strnicmp = Module['_sqlite3_strnicmp'] = wasmExports['sqlite3_strnicmp'];
+ _sqlite3_uri_parameter = Module['_sqlite3_uri_parameter'] = wasmExports['sqlite3_uri_parameter'];
+ _sqlite3_uri_boolean = Module['_sqlite3_uri_boolean'] = wasmExports['sqlite3_uri_boolean'];
+ _sqlite3_serialize = Module['_sqlite3_serialize'] = wasmExports['sqlite3_serialize'];
+ _sqlite3_prepare_v2 = Module['_sqlite3_prepare_v2'] = wasmExports['sqlite3_prepare_v2'];
+ _sqlite3_step = Module['_sqlite3_step'] = wasmExports['sqlite3_step'];
+ _sqlite3_column_int64 = Module['_sqlite3_column_int64'] = wasmExports['sqlite3_column_int64'];
+ _sqlite3_reset = Module['_sqlite3_reset'] = wasmExports['sqlite3_reset'];
+ _sqlite3_exec = Module['_sqlite3_exec'] = wasmExports['sqlite3_exec'];
+ _sqlite3_column_int = Module['_sqlite3_column_int'] = wasmExports['sqlite3_column_int'];
+ _sqlite3_finalize = Module['_sqlite3_finalize'] = wasmExports['sqlite3_finalize'];
+ _sqlite3_file_control = Module['_sqlite3_file_control'] = wasmExports['sqlite3_file_control'];
+ _sqlite3_column_name = Module['_sqlite3_column_name'] = wasmExports['sqlite3_column_name'];
+ _sqlite3_column_text = Module['_sqlite3_column_text'] = wasmExports['sqlite3_column_text'];
+ _sqlite3_column_type = Module['_sqlite3_column_type'] = wasmExports['sqlite3_column_type'];
+ _sqlite3_errmsg = Module['_sqlite3_errmsg'] = wasmExports['sqlite3_errmsg'];
+ _sqlite3_deserialize = Module['_sqlite3_deserialize'] = wasmExports['sqlite3_deserialize'];
+ _sqlite3_clear_bindings = Module['_sqlite3_clear_bindings'] = wasmExports['sqlite3_clear_bindings'];
+ _sqlite3_value_blob = Module['_sqlite3_value_blob'] = wasmExports['sqlite3_value_blob'];
+ _sqlite3_value_bytes = Module['_sqlite3_value_bytes'] = wasmExports['sqlite3_value_bytes'];
+ _sqlite3_value_double = Module['_sqlite3_value_double'] = wasmExports['sqlite3_value_double'];
+ _sqlite3_value_int = Module['_sqlite3_value_int'] = wasmExports['sqlite3_value_int'];
+ _sqlite3_value_int64 = Module['_sqlite3_value_int64'] = wasmExports['sqlite3_value_int64'];
+ _sqlite3_value_subtype = Module['_sqlite3_value_subtype'] = wasmExports['sqlite3_value_subtype'];
+ _sqlite3_value_pointer = Module['_sqlite3_value_pointer'] = wasmExports['sqlite3_value_pointer'];
+ _sqlite3_value_type = Module['_sqlite3_value_type'] = wasmExports['sqlite3_value_type'];
+ _sqlite3_value_nochange = Module['_sqlite3_value_nochange'] = wasmExports['sqlite3_value_nochange'];
+ _sqlite3_value_frombind = Module['_sqlite3_value_frombind'] = wasmExports['sqlite3_value_frombind'];
+ _sqlite3_value_dup = Module['_sqlite3_value_dup'] = wasmExports['sqlite3_value_dup'];
+ _sqlite3_value_free = Module['_sqlite3_value_free'] = wasmExports['sqlite3_value_free'];
+ _sqlite3_result_blob = Module['_sqlite3_result_blob'] = wasmExports['sqlite3_result_blob'];
+ _sqlite3_result_error_toobig = Module['_sqlite3_result_error_toobig'] = wasmExports['sqlite3_result_error_toobig'];
+ _sqlite3_result_error_nomem = Module['_sqlite3_result_error_nomem'] = wasmExports['sqlite3_result_error_nomem'];
+ _sqlite3_result_double = Module['_sqlite3_result_double'] = wasmExports['sqlite3_result_double'];
+ _sqlite3_result_error = Module['_sqlite3_result_error'] = wasmExports['sqlite3_result_error'];
+ _sqlite3_result_int = Module['_sqlite3_result_int'] = wasmExports['sqlite3_result_int'];
+ _sqlite3_result_int64 = Module['_sqlite3_result_int64'] = wasmExports['sqlite3_result_int64'];
+ _sqlite3_result_null = Module['_sqlite3_result_null'] = wasmExports['sqlite3_result_null'];
+ _sqlite3_result_pointer = Module['_sqlite3_result_pointer'] = wasmExports['sqlite3_result_pointer'];
+ _sqlite3_result_subtype = Module['_sqlite3_result_subtype'] = wasmExports['sqlite3_result_subtype'];
+ _sqlite3_result_text = Module['_sqlite3_result_text'] = wasmExports['sqlite3_result_text'];
+ _sqlite3_result_zeroblob = Module['_sqlite3_result_zeroblob'] = wasmExports['sqlite3_result_zeroblob'];
+ _sqlite3_result_zeroblob64 = Module['_sqlite3_result_zeroblob64'] = wasmExports['sqlite3_result_zeroblob64'];
+ _sqlite3_result_error_code = Module['_sqlite3_result_error_code'] = wasmExports['sqlite3_result_error_code'];
+ _sqlite3_user_data = Module['_sqlite3_user_data'] = wasmExports['sqlite3_user_data'];
+ _sqlite3_context_db_handle = Module['_sqlite3_context_db_handle'] = wasmExports['sqlite3_context_db_handle'];
+ _sqlite3_vtab_nochange = Module['_sqlite3_vtab_nochange'] = wasmExports['sqlite3_vtab_nochange'];
+ _sqlite3_vtab_in_first = Module['_sqlite3_vtab_in_first'] = wasmExports['sqlite3_vtab_in_first'];
+ _sqlite3_vtab_in_next = Module['_sqlite3_vtab_in_next'] = wasmExports['sqlite3_vtab_in_next'];
+ _sqlite3_aggregate_context = Module['_sqlite3_aggregate_context'] = wasmExports['sqlite3_aggregate_context'];
+ _sqlite3_get_auxdata = Module['_sqlite3_get_auxdata'] = wasmExports['sqlite3_get_auxdata'];
+ _sqlite3_set_auxdata = Module['_sqlite3_set_auxdata'] = wasmExports['sqlite3_set_auxdata'];
+ _sqlite3_column_count = Module['_sqlite3_column_count'] = wasmExports['sqlite3_column_count'];
+ _sqlite3_data_count = Module['_sqlite3_data_count'] = wasmExports['sqlite3_data_count'];
+ _sqlite3_column_blob = Module['_sqlite3_column_blob'] = wasmExports['sqlite3_column_blob'];
+ _sqlite3_column_bytes = Module['_sqlite3_column_bytes'] = wasmExports['sqlite3_column_bytes'];
+ _sqlite3_column_double = Module['_sqlite3_column_double'] = wasmExports['sqlite3_column_double'];
+ _sqlite3_column_value = Module['_sqlite3_column_value'] = wasmExports['sqlite3_column_value'];
+ _sqlite3_column_decltype = Module['_sqlite3_column_decltype'] = wasmExports['sqlite3_column_decltype'];
+ _sqlite3_column_database_name = Module['_sqlite3_column_database_name'] = wasmExports['sqlite3_column_database_name'];
+ _sqlite3_column_table_name = Module['_sqlite3_column_table_name'] = wasmExports['sqlite3_column_table_name'];
+ _sqlite3_column_origin_name = Module['_sqlite3_column_origin_name'] = wasmExports['sqlite3_column_origin_name'];
+ _sqlite3_bind_blob = Module['_sqlite3_bind_blob'] = wasmExports['sqlite3_bind_blob'];
+ _sqlite3_bind_double = Module['_sqlite3_bind_double'] = wasmExports['sqlite3_bind_double'];
+ _sqlite3_bind_int = Module['_sqlite3_bind_int'] = wasmExports['sqlite3_bind_int'];
+ _sqlite3_bind_int64 = Module['_sqlite3_bind_int64'] = wasmExports['sqlite3_bind_int64'];
+ _sqlite3_bind_null = Module['_sqlite3_bind_null'] = wasmExports['sqlite3_bind_null'];
+ _sqlite3_bind_pointer = Module['_sqlite3_bind_pointer'] = wasmExports['sqlite3_bind_pointer'];
+ _sqlite3_bind_text = Module['_sqlite3_bind_text'] = wasmExports['sqlite3_bind_text'];
+ _sqlite3_bind_zeroblob = Module['_sqlite3_bind_zeroblob'] = wasmExports['sqlite3_bind_zeroblob'];
+ _sqlite3_bind_parameter_count = Module['_sqlite3_bind_parameter_count'] = wasmExports['sqlite3_bind_parameter_count'];
+ _sqlite3_bind_parameter_name = Module['_sqlite3_bind_parameter_name'] = wasmExports['sqlite3_bind_parameter_name'];
+ _sqlite3_bind_parameter_index = Module['_sqlite3_bind_parameter_index'] = wasmExports['sqlite3_bind_parameter_index'];
+ _sqlite3_db_handle = Module['_sqlite3_db_handle'] = wasmExports['sqlite3_db_handle'];
+ _sqlite3_stmt_readonly = Module['_sqlite3_stmt_readonly'] = wasmExports['sqlite3_stmt_readonly'];
+ _sqlite3_stmt_isexplain = Module['_sqlite3_stmt_isexplain'] = wasmExports['sqlite3_stmt_isexplain'];
+ _sqlite3_stmt_explain = Module['_sqlite3_stmt_explain'] = wasmExports['sqlite3_stmt_explain'];
+ _sqlite3_stmt_busy = Module['_sqlite3_stmt_busy'] = wasmExports['sqlite3_stmt_busy'];
+ _sqlite3_next_stmt = Module['_sqlite3_next_stmt'] = wasmExports['sqlite3_next_stmt'];
+ _sqlite3_stmt_status = Module['_sqlite3_stmt_status'] = wasmExports['sqlite3_stmt_status'];
+ _sqlite3_sql = Module['_sqlite3_sql'] = wasmExports['sqlite3_sql'];
+ _sqlite3_expanded_sql = Module['_sqlite3_expanded_sql'] = wasmExports['sqlite3_expanded_sql'];
+ _sqlite3_preupdate_old = Module['_sqlite3_preupdate_old'] = wasmExports['sqlite3_preupdate_old'];
+ _sqlite3_preupdate_count = Module['_sqlite3_preupdate_count'] = wasmExports['sqlite3_preupdate_count'];
+ _sqlite3_preupdate_depth = Module['_sqlite3_preupdate_depth'] = wasmExports['sqlite3_preupdate_depth'];
+ _sqlite3_preupdate_blobwrite = Module['_sqlite3_preupdate_blobwrite'] = wasmExports['sqlite3_preupdate_blobwrite'];
+ _sqlite3_preupdate_new = Module['_sqlite3_preupdate_new'] = wasmExports['sqlite3_preupdate_new'];
+ _sqlite3_value_numeric_type = Module['_sqlite3_value_numeric_type'] = wasmExports['sqlite3_value_numeric_type'];
+ _sqlite3_set_authorizer = Module['_sqlite3_set_authorizer'] = wasmExports['sqlite3_set_authorizer'];
+ _sqlite3_strglob = Module['_sqlite3_strglob'] = wasmExports['sqlite3_strglob'];
+ _sqlite3_strlike = Module['_sqlite3_strlike'] = wasmExports['sqlite3_strlike'];
+ _sqlite3_auto_extension = Module['_sqlite3_auto_extension'] = wasmExports['sqlite3_auto_extension'];
+ _sqlite3_cancel_auto_extension = Module['_sqlite3_cancel_auto_extension'] = wasmExports['sqlite3_cancel_auto_extension'];
+ _sqlite3_reset_auto_extension = Module['_sqlite3_reset_auto_extension'] = wasmExports['sqlite3_reset_auto_extension'];
+ _sqlite3_prepare_v3 = Module['_sqlite3_prepare_v3'] = wasmExports['sqlite3_prepare_v3'];
+ _sqlite3_create_module = Module['_sqlite3_create_module'] = wasmExports['sqlite3_create_module'];
+ _sqlite3_create_module_v2 = Module['_sqlite3_create_module_v2'] = wasmExports['sqlite3_create_module_v2'];
+ _sqlite3_drop_modules = Module['_sqlite3_drop_modules'] = wasmExports['sqlite3_drop_modules'];
+ _sqlite3_declare_vtab = Module['_sqlite3_declare_vtab'] = wasmExports['sqlite3_declare_vtab'];
+ _sqlite3_vtab_on_conflict = Module['_sqlite3_vtab_on_conflict'] = wasmExports['sqlite3_vtab_on_conflict'];
+ _sqlite3_vtab_collation = Module['_sqlite3_vtab_collation'] = wasmExports['sqlite3_vtab_collation'];
+ _sqlite3_vtab_in = Module['_sqlite3_vtab_in'] = wasmExports['sqlite3_vtab_in'];
+ _sqlite3_vtab_rhs_value = Module['_sqlite3_vtab_rhs_value'] = wasmExports['sqlite3_vtab_rhs_value'];
+ _sqlite3_vtab_distinct = Module['_sqlite3_vtab_distinct'] = wasmExports['sqlite3_vtab_distinct'];
+ _sqlite3_keyword_name = Module['_sqlite3_keyword_name'] = wasmExports['sqlite3_keyword_name'];
+ _sqlite3_keyword_count = Module['_sqlite3_keyword_count'] = wasmExports['sqlite3_keyword_count'];
+ _sqlite3_keyword_check = Module['_sqlite3_keyword_check'] = wasmExports['sqlite3_keyword_check'];
+ _sqlite3_complete = Module['_sqlite3_complete'] = wasmExports['sqlite3_complete'];
+ _sqlite3_libversion = Module['_sqlite3_libversion'] = wasmExports['sqlite3_libversion'];
+ _sqlite3_libversion_number = Module['_sqlite3_libversion_number'] = wasmExports['sqlite3_libversion_number'];
+ _sqlite3_shutdown = Module['_sqlite3_shutdown'] = wasmExports['sqlite3_shutdown'];
+ _sqlite3_last_insert_rowid = Module['_sqlite3_last_insert_rowid'] = wasmExports['sqlite3_last_insert_rowid'];
+ _sqlite3_set_last_insert_rowid = Module['_sqlite3_set_last_insert_rowid'] = wasmExports['sqlite3_set_last_insert_rowid'];
+ _sqlite3_changes64 = Module['_sqlite3_changes64'] = wasmExports['sqlite3_changes64'];
+ _sqlite3_changes = Module['_sqlite3_changes'] = wasmExports['sqlite3_changes'];
+ _sqlite3_total_changes64 = Module['_sqlite3_total_changes64'] = wasmExports['sqlite3_total_changes64'];
+ _sqlite3_total_changes = Module['_sqlite3_total_changes'] = wasmExports['sqlite3_total_changes'];
+ _sqlite3_txn_state = Module['_sqlite3_txn_state'] = wasmExports['sqlite3_txn_state'];
+ _sqlite3_close_v2 = Module['_sqlite3_close_v2'] = wasmExports['sqlite3_close_v2'];
+ _sqlite3_busy_handler = Module['_sqlite3_busy_handler'] = wasmExports['sqlite3_busy_handler'];
+ _sqlite3_progress_handler = Module['_sqlite3_progress_handler'] = wasmExports['sqlite3_progress_handler'];
+ _sqlite3_busy_timeout = Module['_sqlite3_busy_timeout'] = wasmExports['sqlite3_busy_timeout'];
+ _sqlite3_interrupt = Module['_sqlite3_interrupt'] = wasmExports['sqlite3_interrupt'];
+ _sqlite3_is_interrupted = Module['_sqlite3_is_interrupted'] = wasmExports['sqlite3_is_interrupted'];
+ _sqlite3_create_function = Module['_sqlite3_create_function'] = wasmExports['sqlite3_create_function'];
+ _sqlite3_create_function_v2 = Module['_sqlite3_create_function_v2'] = wasmExports['sqlite3_create_function_v2'];
+ _sqlite3_create_window_function = Module['_sqlite3_create_window_function'] = wasmExports['sqlite3_create_window_function'];
+ _sqlite3_overload_function = Module['_sqlite3_overload_function'] = wasmExports['sqlite3_overload_function'];
+ _sqlite3_trace_v2 = Module['_sqlite3_trace_v2'] = wasmExports['sqlite3_trace_v2'];
+ _sqlite3_commit_hook = Module['_sqlite3_commit_hook'] = wasmExports['sqlite3_commit_hook'];
+ _sqlite3_update_hook = Module['_sqlite3_update_hook'] = wasmExports['sqlite3_update_hook'];
+ _sqlite3_rollback_hook = Module['_sqlite3_rollback_hook'] = wasmExports['sqlite3_rollback_hook'];
+ _sqlite3_preupdate_hook = Module['_sqlite3_preupdate_hook'] = wasmExports['sqlite3_preupdate_hook'];
+ _sqlite3_set_errmsg = Module['_sqlite3_set_errmsg'] = wasmExports['sqlite3_set_errmsg'];
+ _sqlite3_error_offset = Module['_sqlite3_error_offset'] = wasmExports['sqlite3_error_offset'];
+ _sqlite3_errcode = Module['_sqlite3_errcode'] = wasmExports['sqlite3_errcode'];
+ _sqlite3_extended_errcode = Module['_sqlite3_extended_errcode'] = wasmExports['sqlite3_extended_errcode'];
+ _sqlite3_errstr = Module['_sqlite3_errstr'] = wasmExports['sqlite3_errstr'];
+ _sqlite3_limit = Module['_sqlite3_limit'] = wasmExports['sqlite3_limit'];
+ _sqlite3_open = Module['_sqlite3_open'] = wasmExports['sqlite3_open'];
+ _sqlite3_open_v2 = Module['_sqlite3_open_v2'] = wasmExports['sqlite3_open_v2'];
+ _sqlite3_create_collation = Module['_sqlite3_create_collation'] = wasmExports['sqlite3_create_collation'];
+ _sqlite3_create_collation_v2 = Module['_sqlite3_create_collation_v2'] = wasmExports['sqlite3_create_collation_v2'];
+ _sqlite3_collation_needed = Module['_sqlite3_collation_needed'] = wasmExports['sqlite3_collation_needed'];
+ _sqlite3_get_autocommit = Module['_sqlite3_get_autocommit'] = wasmExports['sqlite3_get_autocommit'];
+ _sqlite3_table_column_metadata = Module['_sqlite3_table_column_metadata'] = wasmExports['sqlite3_table_column_metadata'];
+ _sqlite3_extended_result_codes = Module['_sqlite3_extended_result_codes'] = wasmExports['sqlite3_extended_result_codes'];
+ _sqlite3_uri_key = Module['_sqlite3_uri_key'] = wasmExports['sqlite3_uri_key'];
+ _sqlite3_uri_int64 = Module['_sqlite3_uri_int64'] = wasmExports['sqlite3_uri_int64'];
+ _sqlite3_db_name = Module['_sqlite3_db_name'] = wasmExports['sqlite3_db_name'];
+ _sqlite3_db_filename = Module['_sqlite3_db_filename'] = wasmExports['sqlite3_db_filename'];
+ _sqlite3_db_readonly = Module['_sqlite3_db_readonly'] = wasmExports['sqlite3_db_readonly'];
+ _sqlite3_compileoption_used = Module['_sqlite3_compileoption_used'] = wasmExports['sqlite3_compileoption_used'];
+ _sqlite3_compileoption_get = Module['_sqlite3_compileoption_get'] = wasmExports['sqlite3_compileoption_get'];
+ _sqlite3session_diff = Module['_sqlite3session_diff'] = wasmExports['sqlite3session_diff'];
+ _sqlite3session_attach = Module['_sqlite3session_attach'] = wasmExports['sqlite3session_attach'];
+ _sqlite3session_create = Module['_sqlite3session_create'] = wasmExports['sqlite3session_create'];
+ _sqlite3session_delete = Module['_sqlite3session_delete'] = wasmExports['sqlite3session_delete'];
+ _sqlite3session_table_filter = Module['_sqlite3session_table_filter'] = wasmExports['sqlite3session_table_filter'];
+ _sqlite3session_changeset = Module['_sqlite3session_changeset'] = wasmExports['sqlite3session_changeset'];
+ _sqlite3session_changeset_strm = Module['_sqlite3session_changeset_strm'] = wasmExports['sqlite3session_changeset_strm'];
+ _sqlite3session_patchset_strm = Module['_sqlite3session_patchset_strm'] = wasmExports['sqlite3session_patchset_strm'];
+ _sqlite3session_patchset = Module['_sqlite3session_patchset'] = wasmExports['sqlite3session_patchset'];
+ _sqlite3session_enable = Module['_sqlite3session_enable'] = wasmExports['sqlite3session_enable'];
+ _sqlite3session_indirect = Module['_sqlite3session_indirect'] = wasmExports['sqlite3session_indirect'];
+ _sqlite3session_isempty = Module['_sqlite3session_isempty'] = wasmExports['sqlite3session_isempty'];
+ _sqlite3session_memory_used = Module['_sqlite3session_memory_used'] = wasmExports['sqlite3session_memory_used'];
+ _sqlite3session_object_config = Module['_sqlite3session_object_config'] = wasmExports['sqlite3session_object_config'];
+ _sqlite3session_changeset_size = Module['_sqlite3session_changeset_size'] = wasmExports['sqlite3session_changeset_size'];
+ _sqlite3changeset_start = Module['_sqlite3changeset_start'] = wasmExports['sqlite3changeset_start'];
+ _sqlite3changeset_start_v2 = Module['_sqlite3changeset_start_v2'] = wasmExports['sqlite3changeset_start_v2'];
+ _sqlite3changeset_start_strm = Module['_sqlite3changeset_start_strm'] = wasmExports['sqlite3changeset_start_strm'];
+ _sqlite3changeset_start_v2_strm = Module['_sqlite3changeset_start_v2_strm'] = wasmExports['sqlite3changeset_start_v2_strm'];
+ _sqlite3changeset_next = Module['_sqlite3changeset_next'] = wasmExports['sqlite3changeset_next'];
+ _sqlite3changeset_op = Module['_sqlite3changeset_op'] = wasmExports['sqlite3changeset_op'];
+ _sqlite3changeset_pk = Module['_sqlite3changeset_pk'] = wasmExports['sqlite3changeset_pk'];
+ _sqlite3changeset_old = Module['_sqlite3changeset_old'] = wasmExports['sqlite3changeset_old'];
+ _sqlite3changeset_new = Module['_sqlite3changeset_new'] = wasmExports['sqlite3changeset_new'];
+ _sqlite3changeset_conflict = Module['_sqlite3changeset_conflict'] = wasmExports['sqlite3changeset_conflict'];
+ _sqlite3changeset_fk_conflicts = Module['_sqlite3changeset_fk_conflicts'] = wasmExports['sqlite3changeset_fk_conflicts'];
+ _sqlite3changeset_finalize = Module['_sqlite3changeset_finalize'] = wasmExports['sqlite3changeset_finalize'];
+ _sqlite3changeset_invert = Module['_sqlite3changeset_invert'] = wasmExports['sqlite3changeset_invert'];
+ _sqlite3changeset_invert_strm = Module['_sqlite3changeset_invert_strm'] = wasmExports['sqlite3changeset_invert_strm'];
+ _sqlite3changeset_apply_v2 = Module['_sqlite3changeset_apply_v2'] = wasmExports['sqlite3changeset_apply_v2'];
+ _sqlite3changeset_apply_v3 = Module['_sqlite3changeset_apply_v3'] = wasmExports['sqlite3changeset_apply_v3'];
+ _sqlite3changeset_apply = Module['_sqlite3changeset_apply'] = wasmExports['sqlite3changeset_apply'];
+ _sqlite3changeset_apply_v3_strm = Module['_sqlite3changeset_apply_v3_strm'] = wasmExports['sqlite3changeset_apply_v3_strm'];
+ _sqlite3changeset_apply_v2_strm = Module['_sqlite3changeset_apply_v2_strm'] = wasmExports['sqlite3changeset_apply_v2_strm'];
+ _sqlite3changeset_apply_strm = Module['_sqlite3changeset_apply_strm'] = wasmExports['sqlite3changeset_apply_strm'];
+ _sqlite3changegroup_new = Module['_sqlite3changegroup_new'] = wasmExports['sqlite3changegroup_new'];
+ _sqlite3changegroup_add = Module['_sqlite3changegroup_add'] = wasmExports['sqlite3changegroup_add'];
+ _sqlite3changegroup_output = Module['_sqlite3changegroup_output'] = wasmExports['sqlite3changegroup_output'];
+ _sqlite3changegroup_add_strm = Module['_sqlite3changegroup_add_strm'] = wasmExports['sqlite3changegroup_add_strm'];
+ _sqlite3changegroup_output_strm = Module['_sqlite3changegroup_output_strm'] = wasmExports['sqlite3changegroup_output_strm'];
+ _sqlite3changegroup_delete = Module['_sqlite3changegroup_delete'] = wasmExports['sqlite3changegroup_delete'];
+ _sqlite3changeset_concat = Module['_sqlite3changeset_concat'] = wasmExports['sqlite3changeset_concat'];
+ _sqlite3changeset_concat_strm = Module['_sqlite3changeset_concat_strm'] = wasmExports['sqlite3changeset_concat_strm'];
+ _sqlite3session_config = Module['_sqlite3session_config'] = wasmExports['sqlite3session_config'];
+ _sqlite3_sourceid = Module['_sqlite3_sourceid'] = wasmExports['sqlite3_sourceid'];
+ _sqlite3__wasm_pstack_ptr = Module['_sqlite3__wasm_pstack_ptr'] = wasmExports['sqlite3__wasm_pstack_ptr'];
+ _sqlite3__wasm_pstack_restore = Module['_sqlite3__wasm_pstack_restore'] = wasmExports['sqlite3__wasm_pstack_restore'];
+ _sqlite3__wasm_pstack_alloc = Module['_sqlite3__wasm_pstack_alloc'] = wasmExports['sqlite3__wasm_pstack_alloc'];
+ _sqlite3__wasm_pstack_remaining = Module['_sqlite3__wasm_pstack_remaining'] = wasmExports['sqlite3__wasm_pstack_remaining'];
+ _sqlite3__wasm_pstack_quota = Module['_sqlite3__wasm_pstack_quota'] = wasmExports['sqlite3__wasm_pstack_quota'];
+ _sqlite3__wasm_test_struct = Module['_sqlite3__wasm_test_struct'] = wasmExports['sqlite3__wasm_test_struct'];
+ _sqlite3__wasm_enum_json = Module['_sqlite3__wasm_enum_json'] = wasmExports['sqlite3__wasm_enum_json'];
+ _sqlite3__wasm_vfs_unlink = Module['_sqlite3__wasm_vfs_unlink'] = wasmExports['sqlite3__wasm_vfs_unlink'];
+ _sqlite3__wasm_db_vfs = Module['_sqlite3__wasm_db_vfs'] = wasmExports['sqlite3__wasm_db_vfs'];
+ _sqlite3__wasm_db_reset = Module['_sqlite3__wasm_db_reset'] = wasmExports['sqlite3__wasm_db_reset'];
+ _sqlite3__wasm_db_export_chunked = Module['_sqlite3__wasm_db_export_chunked'] = wasmExports['sqlite3__wasm_db_export_chunked'];
+ _sqlite3__wasm_db_serialize = Module['_sqlite3__wasm_db_serialize'] = wasmExports['sqlite3__wasm_db_serialize'];
+ _sqlite3__wasm_vfs_create_file = Module['_sqlite3__wasm_vfs_create_file'] = wasmExports['sqlite3__wasm_vfs_create_file'];
+ _sqlite3__wasm_posix_create_file = Module['_sqlite3__wasm_posix_create_file'] = wasmExports['sqlite3__wasm_posix_create_file'];
+ _sqlite3__wasm_kvvfsMakeKey = Module['_sqlite3__wasm_kvvfsMakeKey'] = wasmExports['sqlite3__wasm_kvvfsMakeKey'];
+ _sqlite3__wasm_kvvfs_methods = Module['_sqlite3__wasm_kvvfs_methods'] = wasmExports['sqlite3__wasm_kvvfs_methods'];
+ _sqlite3__wasm_vtab_config = Module['_sqlite3__wasm_vtab_config'] = wasmExports['sqlite3__wasm_vtab_config'];
+ _sqlite3__wasm_db_config_ip = Module['_sqlite3__wasm_db_config_ip'] = wasmExports['sqlite3__wasm_db_config_ip'];
+ _sqlite3__wasm_db_config_pii = Module['_sqlite3__wasm_db_config_pii'] = wasmExports['sqlite3__wasm_db_config_pii'];
+ _sqlite3__wasm_db_config_s = Module['_sqlite3__wasm_db_config_s'] = wasmExports['sqlite3__wasm_db_config_s'];
+ _sqlite3__wasm_config_i = Module['_sqlite3__wasm_config_i'] = wasmExports['sqlite3__wasm_config_i'];
+ _sqlite3__wasm_config_ii = Module['_sqlite3__wasm_config_ii'] = wasmExports['sqlite3__wasm_config_ii'];
+ _sqlite3__wasm_config_j = Module['_sqlite3__wasm_config_j'] = wasmExports['sqlite3__wasm_config_j'];
+ _sqlite3__wasm_qfmt_token = Module['_sqlite3__wasm_qfmt_token'] = wasmExports['sqlite3__wasm_qfmt_token'];
+ _sqlite3__wasm_kvvfs_decode = Module['_sqlite3__wasm_kvvfs_decode'] = wasmExports['sqlite3__wasm_kvvfs_decode'];
+ _sqlite3__wasm_kvvfs_encode = Module['_sqlite3__wasm_kvvfs_encode'] = wasmExports['sqlite3__wasm_kvvfs_encode'];
+ _sqlite3__wasm_init_wasmfs = Module['_sqlite3__wasm_init_wasmfs'] = wasmExports['sqlite3__wasm_init_wasmfs'];
+ _sqlite3__wasm_test_intptr = Module['_sqlite3__wasm_test_intptr'] = wasmExports['sqlite3__wasm_test_intptr'];
+ _sqlite3__wasm_test_voidptr = Module['_sqlite3__wasm_test_voidptr'] = wasmExports['sqlite3__wasm_test_voidptr'];
+ _sqlite3__wasm_test_int64_max = Module['_sqlite3__wasm_test_int64_max'] = wasmExports['sqlite3__wasm_test_int64_max'];
+ _sqlite3__wasm_test_int64_min = Module['_sqlite3__wasm_test_int64_min'] = wasmExports['sqlite3__wasm_test_int64_min'];
+ _sqlite3__wasm_test_int64_times2 = Module['_sqlite3__wasm_test_int64_times2'] = wasmExports['sqlite3__wasm_test_int64_times2'];
+ _sqlite3__wasm_test_int64_minmax = Module['_sqlite3__wasm_test_int64_minmax'] = wasmExports['sqlite3__wasm_test_int64_minmax'];
+ _sqlite3__wasm_test_int64ptr = Module['_sqlite3__wasm_test_int64ptr'] = wasmExports['sqlite3__wasm_test_int64ptr'];
+ _sqlite3__wasm_test_stack_overflow = Module['_sqlite3__wasm_test_stack_overflow'] = wasmExports['sqlite3__wasm_test_stack_overflow'];
+ _sqlite3__wasm_test_str_hello = Module['_sqlite3__wasm_test_str_hello'] = wasmExports['sqlite3__wasm_test_str_hello'];
+ _sqlite3__wasm_SQLTester_strglob = Module['_sqlite3__wasm_SQLTester_strglob'] = wasmExports['sqlite3__wasm_SQLTester_strglob'];
+ _malloc = Module['_malloc'] = wasmExports['malloc'];
+ _free = Module['_free'] = wasmExports['free'];
+ _realloc = Module['_realloc'] = wasmExports['realloc'];
+ _emscripten_builtin_memalign = wasmExports['emscripten_builtin_memalign'];
+ __emscripten_stack_restore = wasmExports['_emscripten_stack_restore'];
+ __emscripten_stack_alloc = wasmExports['_emscripten_stack_alloc'];
+ _emscripten_stack_get_current = wasmExports['emscripten_stack_get_current'];
+ __indirect_function_table = wasmExports['__indirect_function_table'];
+}
+
+var wasmImports = {
+
+ __syscall_chmod: ___syscall_chmod,
+
+ __syscall_faccessat: ___syscall_faccessat,
+
+ __syscall_fchmod: ___syscall_fchmod,
+
+ __syscall_fchown32: ___syscall_fchown32,
+
+ __syscall_fcntl64: ___syscall_fcntl64,
+
+ __syscall_fstat64: ___syscall_fstat64,
+
+ __syscall_ftruncate64: ___syscall_ftruncate64,
+
+ __syscall_getcwd: ___syscall_getcwd,
+
+ __syscall_ioctl: ___syscall_ioctl,
+
+ __syscall_lstat64: ___syscall_lstat64,
+
+ __syscall_mkdirat: ___syscall_mkdirat,
+
+ __syscall_newfstatat: ___syscall_newfstatat,
+
+ __syscall_openat: ___syscall_openat,
+
+ __syscall_readlinkat: ___syscall_readlinkat,
+
+ __syscall_rmdir: ___syscall_rmdir,
+
+ __syscall_stat64: ___syscall_stat64,
+
+ __syscall_unlinkat: ___syscall_unlinkat,
+
+ __syscall_utimensat: ___syscall_utimensat,
+
+ _localtime_js: __localtime_js,
+
+ _mmap_js: __mmap_js,
+
+ _munmap_js: __munmap_js,
+
+ _tzset_js: __tzset_js,
+
+ clock_time_get: _clock_time_get,
+
+ emscripten_date_now: _emscripten_date_now,
+
+ emscripten_get_heap_max: _emscripten_get_heap_max,
+
+ emscripten_get_now: _emscripten_get_now,
+
+ emscripten_resize_heap: _emscripten_resize_heap,
+
+ environ_get: _environ_get,
+
+ environ_sizes_get: _environ_sizes_get,
+
+ fd_close: _fd_close,
+
+ fd_fdstat_get: _fd_fdstat_get,
+
+ fd_read: _fd_read,
+
+ fd_seek: _fd_seek,
+
+ fd_sync: _fd_sync,
+
+ fd_write: _fd_write,
+
+ memory: wasmMemory
+};
+
+
+
+
+
+function run() {
+
+ if (runDependencies > 0) {
+ dependenciesFulfilled = run;
+ return;
+ }
+
+ preRun();
+
+
+ if (runDependencies > 0) {
+ dependenciesFulfilled = run;
+ return;
+ }
+
+ function doRun() {
+
+
+ Module['calledRun'] = true;
+
+ if (ABORT) return;
+
+ initRuntime();
+
+ readyPromiseResolve?.(Module);
+ Module['onRuntimeInitialized']?.();
+
+ postRun();
+ }
+
+ if (Module['setStatus']) {
+ Module['setStatus']('Running...');
+ setTimeout(() => {
+ setTimeout(() => Module['setStatus'](''), 1);
+ doRun();
+ }, 1);
+ } else
+ {
+ doRun();
+ }
+}
+
+var wasmExports;
+
+
+
+wasmExports = await (createWasm());
+
+run();
+
+
+
+
+
+Module.runSQLite3PostLoadInit = async function(
+ sqlite3InitScriptInfo,
+ EmscriptenModule,
+ sqlite3IsUnderTest
+){
+
+ 'use strict';
+ delete EmscriptenModule.runSQLite3PostLoadInit;
+
+
+
+
+
+
+
+'use strict';
+globalThis.sqlite3ApiBootstrap = async function sqlite3ApiBootstrap(
+ apiConfig = (globalThis.sqlite3ApiConfig || sqlite3ApiBootstrap.defaultConfig)
+){
+ if(sqlite3ApiBootstrap.sqlite3){
+ (sqlite3ApiBootstrap.sqlite3.config || console).warn(
+ "sqlite3ApiBootstrap() called multiple times.",
+ "Config and external initializers are ignored on calls after the first."
+ );
+ return sqlite3ApiBootstrap.sqlite3;
+ }
+ const nu = (...obj)=>Object.assign(Object.create(null),...obj);
+ const config = nu({
+ exports: undefined,
+ memory: undefined,
+ bigIntEnabled: !!globalThis.BigInt64Array,
+ debug: console.debug.bind(console),
+ warn: console.warn.bind(console),
+ error: console.error.bind(console),
+ log: console.log.bind(console),
+ wasmfsOpfsDir: '/opfs',
+
+ useStdAlloc: false
+ }, apiConfig);
+
+ Object.assign(config, {
+ allocExportName: config.useStdAlloc ? 'malloc' : 'sqlite3_malloc',
+ deallocExportName: config.useStdAlloc ? 'free' : 'sqlite3_free',
+ reallocExportName: config.useStdAlloc ? 'realloc' : 'sqlite3_realloc'
+ });
+
+ [
+
+
+ 'exports', 'memory', 'functionTable', 'wasmfsOpfsDir'
+ ].forEach((k)=>{
+ if('function' === typeof config[k]){
+ config[k] = config[k]();
+ }
+ });
+
+
+ const capi = nu();
+
+ const wasm = nu();
+
+
+ const __rcStr = (rc)=>{
+ return (capi.sqlite3_js_rc_str && capi.sqlite3_js_rc_str(rc))
+ || ("Unknown result code #"+rc);
+ };
+
+
+ const isInt32 = (n)=>
+ 'number'===typeof n
+ && n===(n | 0)
+ && n<=2147483647 && n>=-2147483648;
+
+
+ class SQLite3Error extends Error {
+
+ constructor(...args){
+ let rc;
+ if(args.length){
+ if(isInt32(args[0])){
+ rc = args[0];
+ if(1===args.length){
+ super(__rcStr(args[0]));
+ }else{
+ const rcStr = __rcStr(rc);
+ if('object'===typeof args[1]){
+ super(rcStr,args[1]);
+ }else{
+ args[0] = rcStr+':';
+ super(args.join(' '));
+ }
+ }
+ }else{
+ if(2===args.length && 'object'===typeof args[1]){
+ super(...args);
+ }else{
+ super(args.join(' '));
+ }
+ }
+ }
+ this.resultCode = rc || capi.SQLITE_ERROR;
+ this.name = 'SQLite3Error';
+ }
+ };
+
+
+ SQLite3Error.toss = (...args)=>{
+ throw new SQLite3Error(...args);
+ };
+ const toss3 = SQLite3Error.toss;
+
+ if(config.wasmfsOpfsDir && !/^\/[^/]+$/.test(config.wasmfsOpfsDir)){
+ toss3("config.wasmfsOpfsDir must be falsy or in the form '/dir-name'.");
+ }
+
+
+ const bigIntFits64 = function f(b){
+ if(!f._max){
+ f._max = BigInt("0x7fffffffffffffff");
+ f._min = ~f._max;
+ }
+ return b >= f._min && b <= f._max;
+ };
+
+
+ const bigIntFits32 = (b)=>(b >= (-0x7fffffffn - 1n) && b <= 0x7fffffffn);
+
+
+ const bigIntFitsDouble = function f(b){
+ if(!f._min){
+ f._min = Number.MIN_SAFE_INTEGER;
+ f._max = Number.MAX_SAFE_INTEGER;
+ }
+ return b >= f._min && b <= f._max;
+ };
+
+
+ const isTypedArray = (v)=>{
+ return (v && v.constructor && isInt32(v.constructor.BYTES_PER_ELEMENT)) ? v : false;
+ };
+
+
+ const isBindableTypedArray = (v)=>
+ v && (v instanceof Uint8Array
+ || v instanceof Int8Array
+ || v instanceof ArrayBuffer);
+
+
+ const isSQLableTypedArray = (v)=>
+ v && (v instanceof Uint8Array
+ || v instanceof Int8Array
+ || v instanceof ArrayBuffer);
+
+
+ const affirmBindableTypedArray = (v)=>
+ isBindableTypedArray(v)
+ || toss3("Value is not of a supported TypedArray type.");
+
+
+ const flexibleString = function(v){
+ if(isSQLableTypedArray(v)){
+ return wasm.typedArrayToString(
+ (v instanceof ArrayBuffer) ? new Uint8Array(v) : v,
+ 0, v.length
+ );
+ }
+ else if(Array.isArray(v)) return v.join("");
+ else if(wasm.isPtr(v)) v = wasm.cstrToJs(v);
+ return v;
+ };
+
+
+ class WasmAllocError extends Error {
+
+ constructor(...args){
+ if(2===args.length && 'object'===typeof args[1]){
+ super(...args);
+ }else if(args.length){
+ super(args.join(' '));
+ }else{
+ super("Allocation failed.");
+ }
+ this.resultCode = capi.SQLITE_NOMEM;
+ this.name = 'WasmAllocError';
+ }
+ };
+
+ WasmAllocError.toss = (...args)=>{
+ throw new WasmAllocError(...args);
+ };
+
+ Object.assign(capi, {
+
+ sqlite3_bind_blob: undefined,
+
+
+ sqlite3_bind_text: undefined,
+
+
+ sqlite3_create_function_v2: (
+ pDb, funcName, nArg, eTextRep, pApp,
+ xFunc, xStep, xFinal, xDestroy
+ )=>{},
+
+ sqlite3_create_function: (
+ pDb, funcName, nArg, eTextRep, pApp,
+ xFunc, xStep, xFinal
+ )=>{},
+
+ sqlite3_create_window_function: (
+ pDb, funcName, nArg, eTextRep, pApp,
+ xStep, xFinal, xValue, xInverse, xDestroy
+ )=>{},
+
+ sqlite3_prepare_v3: (dbPtr, sql, sqlByteLen, prepFlags,
+ stmtPtrPtr, strPtrPtr)=>{},
+
+
+ sqlite3_prepare_v2: (dbPtr, sql, sqlByteLen,
+ stmtPtrPtr,strPtrPtr)=>{},
+
+
+ sqlite3_exec: (pDb, sql, callback, pVoid, pErrMsg)=>{},
+
+
+ sqlite3_randomness: (n, outPtr)=>{},
+ });
+
+
+ const util = {
+ affirmBindableTypedArray, flexibleString,
+ bigIntFits32, bigIntFits64, bigIntFitsDouble,
+ isBindableTypedArray,
+ isInt32, isSQLableTypedArray, isTypedArray,
+ isUIThread: ()=>(globalThis.window===globalThis && !!globalThis.document),
+
+ toss: function(...args){throw new Error(args.join(' '))},
+ toss3,
+ typedArrayPart: wasm.typedArrayPart,
+ nu,
+ assert: function(arg,msg){
+ if( !arg ){
+ util.toss("Assertion failed:",msg);
+ }
+ },
+
+ affirmDbHeader: function(bytes){
+ if(bytes instanceof ArrayBuffer) bytes = new Uint8Array(bytes);
+ const header = "SQLite format 3";
+ if( header.length > bytes.byteLength ){
+ toss3("Input does not contain an SQLite3 database header.");
+ }
+ for(let i = 0; i < header.length; ++i){
+ if( header.charCodeAt(i) !== bytes[i] ){
+ toss3("Input does not contain an SQLite3 database header.");
+ }
+ }
+ },
+
+ affirmIsDb: function(bytes){
+ if(bytes instanceof ArrayBuffer) bytes = new Uint8Array(bytes);
+ const n = bytes.byteLength;
+ if(n<512 || n%512!==0) {
+ toss3("Byte array size",n,"is invalid for an SQLite3 db.");
+ }
+ util.affirmDbHeader(bytes);
+ }
+ };
+
+
+ Object.assign(wasm, {
+
+
+ exports: config.exports
+ || toss3("Missing API config.exports (WASM module exports)."),
+
+
+ memory: config.memory
+ || config.exports['memory']
+ || toss3("API config object requires a WebAssembly.Memory object",
+ "in either config.exports.memory (exported)",
+ "or config.memory (imported)."),
+
+
+ pointerSize: ('number'===typeof config.exports.sqlite3_libversion()) ? 4 : 8,
+
+
+ bigIntEnabled: !!config.bigIntEnabled,
+
+
+ functionTable: config.functionTable,
+
+
+ alloc: undefined,
+
+
+ realloc: undefined,
+
+
+ dealloc: undefined
+
+
+ });
+
+
+ wasm.allocFromTypedArray = function(srcTypedArray){
+ if(srcTypedArray instanceof ArrayBuffer){
+ srcTypedArray = new Uint8Array(srcTypedArray);
+ }
+ affirmBindableTypedArray(srcTypedArray);
+ const pRet = wasm.alloc(srcTypedArray.byteLength || 1);
+ wasm.heapForSize(srcTypedArray.constructor)
+ .set(srcTypedArray.byteLength ? srcTypedArray : [0], Number(pRet))
+ ;
+ return pRet;
+ };
+
+ {
+
+ const keyAlloc = config.allocExportName,
+ keyDealloc = config.deallocExportName,
+ keyRealloc = config.reallocExportName;
+ for(const key of [keyAlloc, keyDealloc, keyRealloc]){
+ const f = wasm.exports[key];
+ if(!(f instanceof Function)) toss3("Missing required exports[",key,"] function.");
+ }
+
+ wasm.alloc = function f(n){
+ return f.impl(n) || WasmAllocError.toss("Failed to allocate",n," bytes.");
+ };
+ wasm.alloc.impl = wasm.exports[keyAlloc];
+ wasm.realloc = function f(m,n){
+ const m2 = f.impl(wasm.ptr.coerce(m),n);
+ return n ? (m2 || WasmAllocError.toss("Failed to reallocate",n," bytes.")) : wasm.ptr.null;
+ };
+ wasm.realloc.impl = wasm.exports[keyRealloc];
+ wasm.dealloc = function f(m){
+ f.impl(wasm.ptr.coerce(m))
+ ;
+ };
+ wasm.dealloc.impl = wasm.exports[keyDealloc];
+ }
+
+
+ wasm.compileOptionUsed = function f(optName){
+ if(!arguments.length){
+ if(f._result) return f._result;
+ else if(!f._opt){
+ f._rx = /^([^=]+)=(.+)/;
+ f._rxInt = /^-?\d+$/;
+ f._opt = function(opt, rv){
+ const m = f._rx.exec(opt);
+ rv[0] = (m ? m[1] : opt);
+ rv[1] = m ? (f._rxInt.test(m[2]) ? +m[2] : m[2]) : true;
+ };
+ }
+ const rc = nu(), ov = [0,0];
+ let i = 0, k;
+ while((k = capi.sqlite3_compileoption_get(i++))){
+ f._opt(k,ov);
+ rc[ov[0]] = ov[1];
+ }
+ return f._result = rc;
+ }else if(Array.isArray(optName)){
+ const rc = nu();
+ optName.forEach((v)=>{
+ rc[v] = capi.sqlite3_compileoption_used(v);
+ });
+ return rc;
+ }else if('object' === typeof optName){
+ Object.keys(optName).forEach((k)=> {
+ optName[k] = capi.sqlite3_compileoption_used(k);
+ });
+ return optName;
+ }
+ return (
+ 'string'===typeof optName
+ ) ? !!capi.sqlite3_compileoption_used(optName) : false;
+ };
+
+
+ wasm.pstack = nu({
+
+ restore: wasm.exports.sqlite3__wasm_pstack_restore,
+
+
+ alloc: function(n){
+ if('string'===typeof n && !(n = wasm.sizeofIR(n))){
+ WasmAllocError.toss("Invalid value for pstack.alloc(",arguments[0],")");
+ }
+ return wasm.exports.sqlite3__wasm_pstack_alloc(n)
+ || WasmAllocError.toss("Could not allocate",n,
+ "bytes from the pstack.");
+ },
+
+
+ allocChunks: function(n,sz){
+ if('string'===typeof sz && !(sz = wasm.sizeofIR(sz))){
+ WasmAllocError.toss("Invalid size value for allocChunks(",arguments[1],")");
+ }
+ const mem = wasm.pstack.alloc(n * sz);
+ const rc = [mem];
+ let i = 1, offset = sz;
+ for(; i < n; ++i, offset += sz) rc.push(wasm.ptr.add(mem, offset));
+ return rc;
+ },
+
+
+ allocPtr: (n=1,safePtrSize=true)=>{
+ return 1===n
+ ? wasm.pstack.alloc(safePtrSize ? 8 : wasm.ptr.size)
+ : wasm.pstack.allocChunks(n, safePtrSize ? 8 : wasm.ptr.size);
+ },
+
+
+ call: function(f){
+ const stackPos = wasm.pstack.pointer;
+ try{ return f(sqlite3) }
+ finally{ wasm.pstack.restore(stackPos); }
+ }
+
+ });
+
+ Object.defineProperties(wasm.pstack, {
+
+ pointer: {
+ configurable: false, iterable: true, writeable: false,
+ get: wasm.exports.sqlite3__wasm_pstack_ptr
+
+
+
+ },
+
+
+ quota: {
+ configurable: false, iterable: true, writeable: false,
+ get: wasm.exports.sqlite3__wasm_pstack_quota
+ },
+
+
+ remaining: {
+ configurable: false, iterable: true, writeable: false,
+ get: wasm.exports.sqlite3__wasm_pstack_remaining
+ }
+ });
+
+
+ capi.sqlite3_randomness = (...args)=>{
+ if(1===args.length
+ && util.isTypedArray(args[0])
+ && 1===args[0].BYTES_PER_ELEMENT){
+ const ta = args[0];
+ if(0===ta.byteLength){
+ wasm.exports.sqlite3_randomness(0,wasm.ptr.null);
+ return ta;
+ }
+ const stack = wasm.pstack.pointer;
+ try {
+ let n = ta.byteLength, offset = 0;
+ const r = wasm.exports.sqlite3_randomness;
+ const heap = wasm.heap8u();
+ const nAlloc = n < 512 ? n : 512;
+ const ptr = wasm.pstack.alloc(nAlloc);
+ do{
+ const j = (n>nAlloc ? nAlloc : n);
+ r(j, ptr);
+ ta.set(wasm.typedArrayPart(heap, ptr, wasm.ptr.add(ptr,j)), offset);
+ n -= j;
+ offset += j;
+ } while(n > 0);
+ }catch(e){
+ config.error("Highly unexpected (and ignored!) "+
+ "exception in sqlite3_randomness():",e);
+ }finally{
+ wasm.pstack.restore(stack);
+ }
+ return ta;
+ }
+ wasm.exports.sqlite3_randomness(...args);
+ };
+
+
+ capi.sqlite3_wasmfs_opfs_dir = function(){
+ if(undefined !== this.dir) return this.dir;
+
+ const pdir = config.wasmfsOpfsDir;
+ if(!pdir
+ || !globalThis.FileSystemHandle
+ || !globalThis.FileSystemDirectoryHandle
+ || !globalThis.FileSystemFileHandle
+ || !wasm.exports.sqlite3__wasm_init_wasmfs){
+ return this.dir = "";
+ }
+ try{
+ if(pdir && 0===wasm.xCallWrapped(
+ 'sqlite3__wasm_init_wasmfs', 'i32', ['string'], pdir
+ )){
+ return this.dir = pdir;
+ }else{
+ return this.dir = "";
+ }
+ }catch(e){
+
+ return this.dir = "";
+ }
+ }.bind(nu());
+
+
+ capi.sqlite3_wasmfs_filename_is_persistent = function(name){
+ const p = capi.sqlite3_wasmfs_opfs_dir();
+ return (p && name) ? name.startsWith(p+'/') : false;
+ };
+
+
+ capi.sqlite3_js_db_uses_vfs = function(pDb,vfsName,dbName=0){
+ try{
+ const pK = capi.sqlite3_vfs_find(vfsName);
+ if(!pK) return false;
+ else if(!pDb){
+ return pK===capi.sqlite3_vfs_find(0) ? pK : false;
+ }else{
+ return pK===capi.sqlite3_js_db_vfs(pDb,dbName) ? pK : false;
+ }
+ }catch(e){
+
+ return false;
+ }
+ };
+
+
+ capi.sqlite3_js_vfs_list = function(){
+ const rc = [];
+ let pVfs = capi.sqlite3_vfs_find(wasm.ptr.null);
+ while(pVfs){
+ const oVfs = new capi.sqlite3_vfs(pVfs);
+ rc.push(wasm.cstrToJs(oVfs.$zName));
+ pVfs = oVfs.$pNext;
+ oVfs.dispose();
+ }
+ return rc;
+ };
+
+
+ capi.sqlite3_js_db_export = function(pDb, schema=0){
+ pDb = wasm.xWrap.testConvertArg('sqlite3*', pDb);
+ if(!pDb) toss3('Invalid sqlite3* argument.');
+ if(!wasm.bigIntEnabled) toss3('BigInt support is not enabled.');
+ const scope = wasm.scopedAllocPush();
+ let pOut;
+ try{
+ const pSize = wasm.scopedAlloc(8 + wasm.ptr.size);
+ const ppOut = wasm.ptr.add(pSize, 8);
+
+ const zSchema = schema
+ ? (wasm.isPtr(schema) ? schema : wasm.scopedAllocCString(''+schema))
+ : wasm.ptr.null;
+ let rc = wasm.exports.sqlite3__wasm_db_serialize(
+ pDb, zSchema, ppOut, pSize, 0
+ );
+ if(rc){
+ toss3("Database serialization failed with code",
+ sqlite3.capi.sqlite3_js_rc_str(rc));
+ }
+ pOut = wasm.peekPtr(ppOut);
+ const nOut = wasm.peek(pSize, 'i64');
+ rc = nOut
+ ? wasm.heap8u().slice(Number(pOut), Number(pOut) + Number(nOut))
+ : new Uint8Array();
+ return rc;
+ }finally{
+ if(pOut) wasm.exports.sqlite3_free(pOut);
+ wasm.scopedAllocPop(scope);
+ }
+ };
+
+
+ capi.sqlite3_js_db_vfs =
+ (dbPointer, dbName=wasm.ptr.null)=>util.sqlite3__wasm_db_vfs(dbPointer, dbName);
+
+
+ capi.sqlite3_js_aggregate_context = (pCtx, n)=>{
+ return capi.sqlite3_aggregate_context(pCtx, n)
+ || (n ? WasmAllocError.toss("Cannot allocate",n,
+ "bytes for sqlite3_aggregate_context()")
+ : 0);
+ };
+
+
+ capi.sqlite3_js_posix_create_file = function(filename, data, dataLen){
+ let pData;
+ if(data && wasm.isPtr(data)){
+ pData = data;
+ }else if(data instanceof ArrayBuffer || data instanceof Uint8Array){
+ pData = wasm.allocFromTypedArray(data);
+ if(arguments.length<3 || !util.isInt32(dataLen) || dataLen<0){
+ dataLen = data.byteLength;
+ }
+ }else{
+ SQLite3Error.toss("Invalid 2nd argument for sqlite3_js_posix_create_file().");
+ }
+ try{
+ if(!util.isInt32(dataLen) || dataLen<0){
+ SQLite3Error.toss("Invalid 3rd argument for sqlite3_js_posix_create_file().");
+ }
+ const rc = util.sqlite3__wasm_posix_create_file(filename, pData, dataLen);
+ if(rc) SQLite3Error.toss("Creation of file failed with sqlite3 result code",
+ capi.sqlite3_js_rc_str(rc));
+ }finally{
+ if( pData && pData!==data ) wasm.dealloc(pData);
+ }
+ };
+
+
+ capi.sqlite3_js_vfs_create_file = function(vfs, filename, data, dataLen){
+ config.warn("sqlite3_js_vfs_create_file() is deprecated and",
+ "should be avoided because it can lead to C-level crashes.",
+ "See its documentation for alternatives.");
+ let pData;
+ if(data){
+ if( wasm.isPtr(data) ){
+ pData = data;
+ }else{
+ if( data instanceof ArrayBuffer ){
+ data = new Uint8Array(data);
+ }
+ if( data instanceof Uint8Array ){
+ pData = wasm.allocFromTypedArray(data);
+ if(arguments.length<4 || !util.isInt32(dataLen) || dataLen<0){
+ dataLen = data.byteLength;
+ }
+ }else{
+ SQLite3Error.toss("Invalid 3rd argument type for sqlite3_js_vfs_create_file().");
+ }
+ }
+ }else{
+ pData = 0;
+ }
+ if(!util.isInt32(dataLen) || dataLen<0){
+ if( pData && pData!==data ) wasm.dealloc(pData);
+ SQLite3Error.toss("Invalid 4th argument for sqlite3_js_vfs_create_file().");
+ }
+ try{
+ const rc = util.sqlite3__wasm_vfs_create_file(vfs, filename, pData, dataLen);
+ if(rc) SQLite3Error.toss("Creation of file failed with sqlite3 result code",
+ capi.sqlite3_js_rc_str(rc));
+ }finally{
+ if( pData && pData!==data ) wasm.dealloc(pData);
+ }
+ };
+
+
+ capi.sqlite3_js_sql_to_string = (sql)=>{
+ if('string' === typeof sql){
+ return sql;
+ }
+ const x = flexibleString(v);
+ return x===v ? undefined : x;
+ }
+
+
+ capi.sqlite3_db_config = function(pDb, op, ...args){
+ switch(op){
+ case capi.SQLITE_DBCONFIG_ENABLE_FKEY:
+ case capi.SQLITE_DBCONFIG_ENABLE_TRIGGER:
+ case capi.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER:
+ case capi.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION:
+ case capi.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE:
+ case capi.SQLITE_DBCONFIG_ENABLE_QPSG:
+ case capi.SQLITE_DBCONFIG_TRIGGER_EQP:
+ case capi.SQLITE_DBCONFIG_RESET_DATABASE:
+ case capi.SQLITE_DBCONFIG_DEFENSIVE:
+ case capi.SQLITE_DBCONFIG_WRITABLE_SCHEMA:
+ case capi.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE:
+ case capi.SQLITE_DBCONFIG_DQS_DML:
+ case capi.SQLITE_DBCONFIG_DQS_DDL:
+ case capi.SQLITE_DBCONFIG_ENABLE_VIEW:
+ case capi.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT:
+ case capi.SQLITE_DBCONFIG_TRUSTED_SCHEMA:
+ case capi.SQLITE_DBCONFIG_STMT_SCANSTATUS:
+ case capi.SQLITE_DBCONFIG_REVERSE_SCANORDER:
+ case capi.SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE:
+ case capi.SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE:
+ case capi.SQLITE_DBCONFIG_ENABLE_COMMENTS:
+ case capi.SQLITE_DBCONFIG_FP_DIGITS:
+ if( !this.ip ){
+ this.ip = wasm.xWrap('sqlite3__wasm_db_config_ip','int',
+ ['sqlite3*', 'int', 'int', '*']);
+ }
+ return this.ip(pDb, op, args[0], args[1] || 0);
+ case capi.SQLITE_DBCONFIG_LOOKASIDE:
+ if( !this.pii ){
+ this.pii = wasm.xWrap('sqlite3__wasm_db_config_pii', 'int',
+ ['sqlite3*', 'int', '*', 'int', 'int']);
+ }
+ return this.pii(pDb, op, args[0], args[1], args[2]);
+ case capi.SQLITE_DBCONFIG_MAINDBNAME:
+ if(!this.s){
+ this.s = wasm.xWrap('sqlite3__wasm_db_config_s','int',
+ ['sqlite3*', 'int', 'string:static']
+ );
+ }
+ return this.s(pDb, op, args[0]);
+ default:
+ return capi.SQLITE_MISUSE;
+ }
+ }.bind(nu());
+
+
+ capi.sqlite3_value_to_js = function(pVal,throwIfCannotConvert=true){
+ let arg;
+ const valType = capi.sqlite3_value_type(pVal);
+ switch(valType){
+ case capi.SQLITE_INTEGER:
+ if(wasm.bigIntEnabled){
+ arg = capi.sqlite3_value_int64(pVal);
+ if(util.bigIntFitsDouble(arg)) arg = Number(arg);
+ }
+ else arg = capi.sqlite3_value_double(pVal);
+ break;
+ case capi.SQLITE_FLOAT:
+ arg = capi.sqlite3_value_double(pVal);
+ break;
+ case capi.SQLITE_TEXT:
+ arg = capi.sqlite3_value_text(pVal);
+ break;
+ case capi.SQLITE_BLOB:{
+ const n = capi.sqlite3_value_bytes(pVal);
+ const pBlob = capi.sqlite3_value_blob(pVal);
+ if(n && !pBlob) sqlite3.WasmAllocError.toss(
+ "Cannot allocate memory for blob argument of",n,"byte(s)"
+ );
+ arg = n
+ ? wasm.heap8u().slice(Number(pBlob), Number(pBlob) + Number(n))
+ : null;
+ break;
+ }
+ case capi.SQLITE_NULL:
+ arg = null; break;
+ default:
+ if(throwIfCannotConvert){
+ toss3(capi.SQLITE_MISMATCH,
+ "Unhandled sqlite3_value_type():",valType);
+ }
+ arg = undefined;
+ }
+ return arg;
+ };
+
+
+ capi.sqlite3_values_to_js = function(argc,pArgv,throwIfCannotConvert=true){
+ let i;
+ const tgt = [];
+ for(i = 0; i < argc; ++i){
+
+ tgt.push(capi.sqlite3_value_to_js(
+ wasm.peekPtr(wasm.ptr.add(pArgv, wasm.ptr.size * i)),
+ throwIfCannotConvert
+ ));
+ }
+ return tgt;
+ };
+
+
+ capi.sqlite3_result_error_js = function(pCtx,e){
+ if(e instanceof WasmAllocError){
+ capi.sqlite3_result_error_nomem(pCtx);
+ }else{
+ ;
+ capi.sqlite3_result_error(pCtx, ''+e, -1);
+ }
+ };
+
+
+ capi.sqlite3_result_js = function(pCtx,val){
+ if(val instanceof Error){
+ capi.sqlite3_result_error_js(pCtx, val);
+ return;
+ }
+ try{
+ switch(typeof val) {
+ case 'undefined':
+
+ break;
+ case 'boolean':
+ capi.sqlite3_result_int(pCtx, val ? 1 : 0);
+ break;
+ case 'bigint':
+ if(util.bigIntFits32(val)){
+ capi.sqlite3_result_int(pCtx, Number(val));
+ }else if(util.bigIntFitsDouble(val)){
+ capi.sqlite3_result_double(pCtx, Number(val));
+ }else if(wasm.bigIntEnabled){
+ if(util.bigIntFits64(val)) capi.sqlite3_result_int64(pCtx, val);
+ else toss3("BigInt value",val.toString(),"is too BigInt for int64.");
+ }else{
+ toss3("BigInt value",val.toString(),"is too BigInt.");
+ }
+ break;
+ case 'number': {
+ let f;
+ if(util.isInt32(val)){
+ f = capi.sqlite3_result_int;
+ }else if(wasm.bigIntEnabled
+ && Number.isInteger(val)
+ && util.bigIntFits64(BigInt(val))){
+ f = capi.sqlite3_result_int64;
+ }else{
+ f = capi.sqlite3_result_double;
+ }
+ f(pCtx, val);
+ break;
+ }
+ case 'string': {
+ const [p, n] = wasm.allocCString(val,true);
+ capi.sqlite3_result_text(pCtx, p, n, capi.SQLITE_WASM_DEALLOC);
+ break;
+ }
+ case 'object':
+ if(null===val) {
+ capi.sqlite3_result_null(pCtx);
+ break;
+ }else if(util.isBindableTypedArray(val)){
+ const pBlob = wasm.allocFromTypedArray(val);
+ capi.sqlite3_result_blob(
+ pCtx, pBlob, val.byteLength,
+ capi.SQLITE_WASM_DEALLOC
+ );
+ break;
+ }
+
+ default:
+ toss3("Don't not how to handle this UDF result value:",(typeof val), val);
+ }
+ }catch(e){
+ capi.sqlite3_result_error_js(pCtx, e);
+ }
+ };
+
+
+ capi.sqlite3_column_js = function(pStmt, iCol, throwIfCannotConvert=true){
+ const v = capi.sqlite3_column_value(pStmt, iCol);
+ return (0===v) ? undefined : capi.sqlite3_value_to_js(v, throwIfCannotConvert);
+ };
+
+ if( true ){
+
+ const __newOldValue = function(pObj, iCol, impl){
+ impl = capi[impl];
+ if(!this.ptr) this.ptr = wasm.allocPtr();
+ else wasm.pokePtr(this.ptr, 0);
+ const rc = impl(pObj, iCol, this.ptr);
+ if(rc) return SQLite3Error.toss(rc,arguments[2]+"() failed with code "+rc);
+ const pv = wasm.peekPtr(this.ptr);
+ return pv ? capi.sqlite3_value_to_js( pv, true ) : undefined;
+ }.bind(nu());
+
+
+ capi.sqlite3_preupdate_new_js =
+ (pDb, iCol)=>__newOldValue(pDb, iCol, 'sqlite3_preupdate_new');
+
+
+ capi.sqlite3_preupdate_old_js =
+ (pDb, iCol)=>__newOldValue(pDb, iCol, 'sqlite3_preupdate_old');
+
+
+ capi.sqlite3changeset_new_js =
+ (pChangesetIter, iCol) => __newOldValue(pChangesetIter, iCol,
+ 'sqlite3changeset_new');
+
+
+ capi.sqlite3changeset_old_js =
+ (pChangesetIter, iCol)=>__newOldValue(pChangesetIter, iCol,
+ 'sqlite3changeset_old');
+ }
+
+
+ capi.sqlite3_js_retry_busy = function(maxTimes, callback, beforeRetry){
+ for(let n = 1; n <= maxTimes; ++n){
+ try{
+ if( beforeRetry && n>1 ) beforeRetry(n);
+ const rc = callback();
+ if( capi.SQLITE_BUSY===rc ){
+ if( n===maxTimes ){
+ throw new SQLite3Error(rc, [
+ "sqlite3_js_retry_busy() max retry attempts (",
+ maxTimes,
+ ") reached."
+ ].join(''));
+ }
+ continue;
+ }
+ return rc;
+ }catch(e){
+ if( n<maxTimes
+ && (e instanceof SQLite3Error)
+ && e.resultCode===capi.SQLITE_BUSY ){
+ continue;
+ }
+ throw e;
+ }
+ }
+ };
+
+
+ const sqlite3 = {
+ WasmAllocError: WasmAllocError,
+ SQLite3Error: SQLite3Error,
+ capi,
+ util ,
+ wasm,
+ config,
+
+ version: nu(),
+
+
+ client: undefined,
+
+
+ asyncPostInit: async function ff(){
+ if(ff.isReady instanceof Promise) return ff.isReady;
+ let lia = this.initializersAsync;
+ delete this.initializersAsync;
+ const postInit = async ()=>{
+ if(!sqlite3.__isUnderTest){
+
+ delete sqlite3.util;
+ delete sqlite3.StructBinder;
+ delete sqlite3.opfs;
+ }
+ return sqlite3;
+ };
+ const catcher = (e)=>{
+ config.error("an async sqlite3 initializer failed:",e);
+ throw e;
+ };
+ if(!lia || !lia.length){
+ return ff.isReady = postInit().catch(catcher);
+ }
+ lia = lia.map((f)=>{
+ return (f instanceof Function) ? async x=>f(sqlite3) : f;
+ });
+ lia.push(postInit);
+ let p = Promise.resolve(sqlite3);
+ while(lia.length) p = p.then(lia.shift());
+ return ff.isReady = p.catch(catcher);
+ }.bind(sqlite3ApiBootstrap),
+
+ scriptInfo: undefined
+ };
+ if( 'undefined'!==typeof sqlite3IsUnderTest ){
+ sqlite3.__isUnderTest = !!sqlite3IsUnderTest;
+ }
+ try{
+ sqlite3ApiBootstrap.initializers.forEach((f)=>{
+ f(sqlite3);
+ });
+ }catch(e){
+
+ console.error("sqlite3 bootstrap initializer threw:",e);
+ throw e;
+ }
+ delete sqlite3ApiBootstrap.initializers;
+ sqlite3ApiBootstrap.sqlite3 = sqlite3;
+ if( 'undefined'!==typeof sqlite3InitScriptInfo ){
+ sqlite3InitScriptInfo.debugModule(
+ "sqlite3ApiBootstrap() complete", sqlite3
+ );
+ sqlite3.scriptInfo
+ = sqlite3InitScriptInfo;
+ }
+ if( sqlite3.__isUnderTest ){
+ if( 'undefined'!==typeof EmscriptenModule ){
+ sqlite3.config.emscripten = EmscriptenModule;
+ }
+
+ const iw = sqlite3.scriptInfo?.instantiateWasm;
+ if( iw ){
+
+ sqlite3.wasm.module = iw.module;
+ sqlite3.wasm.instance = iw.instance;
+ sqlite3.wasm.imports = iw.imports;
+ }
+ }
+
+
+ delete globalThis.sqlite3ApiConfig;
+ delete globalThis.sqlite3ApiBootstrap;
+ delete sqlite3ApiBootstrap.defaultConfig;
+ return sqlite3.asyncPostInit().then((s)=>{
+ if( 'undefined'!==typeof sqlite3InitScriptInfo ){
+ sqlite3InitScriptInfo.debugModule(
+ "sqlite3.asyncPostInit() complete", s
+ );
+ }
+ delete s.asyncPostInit;
+ delete s.scriptInfo;
+ delete s.emscripten;
+ return s;
+ });
+};
+
+
+globalThis.sqlite3ApiBootstrap.initializers = [];
+
+
+globalThis.sqlite3ApiBootstrap.initializersAsync = [];
+
+
+globalThis.sqlite3ApiBootstrap.defaultConfig = Object.create(null);
+
+
+globalThis.sqlite3ApiBootstrap.sqlite3 = undefined;
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+ sqlite3.version = {"libVersion": "3.53.4", "libVersionNumber": 3053004, "sourceId": "2026-07-24 19:02:57 bf7c7f30031888f4e796e429ab3978879485813aaca6f641c7b33e4e09459bcc","downloadVersion": 3530400,"scm":{ "sha3-256": "bf7c7f30031888f4e796e429ab3978879485813aaca6f641c7b33e4e09459bcc","branch": "branch-3.53","tags": "release version-3.53.4","datetime": "2026-07-24T19:02:57.525Z"}};
+});
+
+
+'use strict';
+globalThis.WhWasmUtilInstaller =
+function WhWasmUtilInstaller(target){
+ 'use strict';
+ if(undefined===target.bigIntEnabled){
+ target.bigIntEnabled = !!globalThis['BigInt64Array'];
+ }
+
+
+ const toss = (...args)=>{throw new Error(args.join(' '))};
+
+ if( !target.pointerSize && !target.pointerIR
+ && target.alloc && target.dealloc ){
+
+ const ptr = target.alloc(1);
+ target.pointerSize = ('bigint'===typeof ptr ? 8 : 4);
+ target.dealloc(ptr);
+ }
+
+
+ if( target.pointerSize && !target.pointerIR ){
+ target.pointerIR = (4===target.pointerSize ? 'i32' : 'i64');
+ }
+ const __ptrIR = (target.pointerIR ??= 'i32');
+ const __ptrSize = (target.pointerSize ??=
+ ('i32'===__ptrIR ? 4 : ('i64'===__ptrIR ? 8 : 0)));
+ delete target.pointerSize;
+ delete target.pointerIR;
+
+ if( 'i32'!==__ptrIR && 'i64'!==__ptrIR ){
+ toss("Invalid pointerIR:",__ptrIR);
+ }else if( 8!==__ptrSize && 4!==__ptrSize ){
+ toss("Invalid pointerSize:",__ptrSize);
+ }
+
+
+ const __BigInt = target.bigIntEnabled
+ ? (v)=>BigInt(v || 0)
+ : (v)=>toss("BigInt support is disabled in this build.");
+
+ const __Number = (v)=>Number(v||0);
+
+
+ const __asPtrType = (4===__ptrSize) ? __Number : __BigInt;
+
+
+ const __NullPtr = __asPtrType(0);
+
+
+ const __ptrAdd = function(...args){
+ let rc = __asPtrType(0);
+ for(const v of args) rc += __asPtrType(v);
+ return rc;
+ };
+
+
+ {
+ const __ptr = Object.create(null);
+ Object.defineProperty(target, 'ptr', {
+ enumerable: true,
+ get: ()=>__ptr,
+ set: ()=>toss("The ptr property is read-only.")
+ });
+ (function f(name, val){
+ Object.defineProperty(__ptr, name, {
+ enumerable: true,
+ get: ()=>val,
+ set: ()=>toss("ptr["+name+"] is read-only.")
+ });
+ return f;
+ })(
+ 'null', __NullPtr
+ )(
+ 'size', __ptrSize
+ )(
+ 'ir', __ptrIR
+ )(
+ 'coerce', __asPtrType
+ )(
+ 'add', __ptrAdd
+ )(
+ 'addn', (4===__ptrIR) ? __ptrAdd : (...args)=>Number(__ptrAdd(...args))
+ );
+ }
+
+ if(!target.exports){
+ Object.defineProperty(target, 'exports', {
+ enumerable: true, configurable: true,
+ get: ()=>(target.instance?.exports)
+ });
+ }
+
+
+ const cache = Object.create(null);
+
+ cache.heapSize = 0;
+
+ cache.memory = null;
+
+ cache.freeFuncIndexes = [];
+
+ cache.scopedAlloc = [];
+
+
+ cache.scopedAlloc.pushPtr = (ptr)=>{
+ cache.scopedAlloc[cache.scopedAlloc.length-1].push(ptr);
+ return ptr;
+ };
+
+ cache.utf8Decoder = new TextDecoder();
+ cache.utf8Encoder = new TextEncoder('utf-8');
+
+
+ target.sizeofIR = (n)=>{
+ switch(n){
+ case 'i8': return 1;
+ case 'i16': return 2;
+ case 'i32': case 'f32': case 'float': return 4;
+ case 'i64': case 'f64': case 'double': return 8;
+ case '*': return __ptrSize;
+ default:
+ return (''+n).endsWith('*') ? __ptrSize : undefined;
+ }
+ };
+
+
+ const heapWrappers = function(){
+ if(!cache.memory){
+ cache.memory = (target.memory instanceof WebAssembly.Memory)
+ ? target.memory : target.exports.memory;
+ }else if(cache.heapSize === cache.memory.buffer.byteLength){
+ return cache;
+ }
+
+ const b = cache.memory.buffer;
+ cache.HEAP8 = new Int8Array(b); cache.HEAP8U = new Uint8Array(b);
+ cache.HEAP16 = new Int16Array(b); cache.HEAP16U = new Uint16Array(b);
+ cache.HEAP32 = new Int32Array(b); cache.HEAP32U = new Uint32Array(b);
+ cache.HEAP32F = new Float32Array(b); cache.HEAP64F = new Float64Array(b);
+ if(target.bigIntEnabled){
+ if( 'undefined'!==typeof BigInt64Array ){
+ cache.HEAP64 = new BigInt64Array(b); cache.HEAP64U = new BigUint64Array(b);
+ }else{
+ toss("BigInt support is enabled, but the BigInt64Array type is missing.");
+ }
+ }
+ cache.heapSize = b.byteLength;
+ return cache;
+ };
+
+
+ target.heap8 = ()=>heapWrappers().HEAP8;
+
+
+ target.heap8u = ()=>heapWrappers().HEAP8U;
+
+
+ target.heap16 = ()=>heapWrappers().HEAP16;
+
+
+ target.heap16u = ()=>heapWrappers().HEAP16U;
+
+
+ target.heap32 = ()=>heapWrappers().HEAP32;
+
+
+ target.heap32u = ()=>heapWrappers().HEAP32U;
+
+
+ target.heapForSize = function(n,unsigned = true){
+ let ctor;
+ const c = (cache.memory && cache.heapSize === cache.memory.buffer.byteLength)
+ ? cache : heapWrappers();
+ switch(n){
+ case Int8Array: return c.HEAP8; case Uint8Array: return c.HEAP8U;
+ case Int16Array: return c.HEAP16; case Uint16Array: return c.HEAP16U;
+ case Int32Array: return c.HEAP32; case Uint32Array: return c.HEAP32U;
+ case 8: return unsigned ? c.HEAP8U : c.HEAP8;
+ case 16: return unsigned ? c.HEAP16U : c.HEAP16;
+ case 32: return unsigned ? c.HEAP32U : c.HEAP32;
+ case 64:
+ if(c.HEAP64) return unsigned ? c.HEAP64U : c.HEAP64;
+ break;
+ default:
+ if(target.bigIntEnabled){
+ if(n===globalThis['BigUint64Array']) return c.HEAP64U;
+ else if(n===globalThis['BigInt64Array']) return c.HEAP64;
+ break;
+ }
+ }
+ toss("Invalid heapForSize() size: expecting 8, 16, 32,",
+ "or (if BigInt is enabled) 64.");
+ };
+
+ const __funcTable = target.functionTable;
+ delete target.functionTable;
+
+
+ target.functionTable = __funcTable
+ ? ()=>__funcTable
+ : ()=>target.exports.__indirect_function_table
+ ;
+
+
+ target.functionEntry = function(fptr){
+ const ft = target.functionTable();
+
+
+
+ return fptr < ft.length ? ft.get(__asPtrType(fptr)) : undefined;
+ };
+
+
+ target.jsFuncToWasm = function f(func, sig){
+
+ if(!f._){
+ f._ = {
+
+ sigTypes: Object.assign(Object.create(null),{
+ i: 'i32', p: __ptrIR, P: __ptrIR, s: __ptrIR,
+ j: 'i64', f: 'f32', d: 'f64'
+ }),
+
+
+ typeCodes: Object.assign(Object.create(null),{
+ f64: 0x7c, f32: 0x7d, i64: 0x7e, i32: 0x7f
+ }),
+
+
+ uleb128Encode: (tgt, method, n)=>{
+ if(n<128) tgt[method](n);
+ else tgt[method]( (n % 128) | 128, n>>7);
+ },
+
+
+ rxJSig: /^(\w)\((\w*)\)$/,
+
+
+ sigParams: (sig)=>{
+ const m = f._.rxJSig.exec(sig);
+ return m ? m[2] : sig.substr(1);
+ },
+
+
+ letterType: (x)=>f._.sigTypes[x] || toss("Invalid signature letter:",x),
+
+
+ pushSigType: (dest, letter)=>dest.push(f._.typeCodes[f._.letterType(letter)])
+
+
+
+ };
+ }
+ if('string'===typeof func){
+ const x = sig;
+ sig = func;
+ func = x;
+ }
+ const _ = f._;
+ const sigParams = _.sigParams(sig);
+ const wasmCode = [0x01, 0x60];
+ _.uleb128Encode(wasmCode, 'push', sigParams.length);
+ for(const x of sigParams) _.pushSigType(wasmCode, x);
+ if('v'===sig[0]) wasmCode.push(0);
+ else{
+ wasmCode.push(1);
+ _.pushSigType(wasmCode, sig[0]);
+ }
+ _.uleb128Encode(wasmCode, 'unshift', wasmCode.length);
+ wasmCode.unshift(
+ 0x00, 0x61, 0x73, 0x6d,
+ 0x01, 0x00, 0x00, 0x00,
+ 0x01
+ );
+ wasmCode.push(
+ 0x02, 0x07,
+
+ 0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00,
+ 0x07, 0x05,
+
+ 0x01, 0x01, 0x66, 0x00, 0x00
+ );
+ return (new WebAssembly.Instance(
+ new WebAssembly.Module(new Uint8Array(wasmCode)), {
+ e: { f: func }
+ })).exports['f'];
+ };
+
+
+ const __installFunction = function f(func, sig, scoped){
+ if(scoped && !cache.scopedAlloc.length){
+ toss("No scopedAllocPush() scope is active.");
+ }
+ if('string'===typeof func){
+ const x = sig;
+ sig = func;
+ func = x;
+ }
+ if('string'!==typeof sig || !(func instanceof Function)){
+ toss("Invalid arguments: expecting (function,signature) "+
+ "or (signature,function).");
+ }
+ const ft = target.functionTable();
+ const oldLen = __asPtrType(ft.length);
+ let ptr;
+ while( (ptr = cache.freeFuncIndexes.pop()) ){
+ if(ft.get(ptr)){
+
+ ptr = null;
+ continue;
+ }else{
+
+ break;
+ }
+ }
+ if(!ptr){
+ ptr = __asPtrType(oldLen);
+ ft.grow(__asPtrType(1));
+ }
+ try{
+
+ ft.set(ptr, func);
+ if(scoped){
+ cache.scopedAlloc.pushPtr(ptr);
+ }
+ return ptr;
+ }catch(e){
+ if(!(e instanceof TypeError)){
+ if(ptr===oldLen) cache.freeFuncIndexes.push(oldLen);
+ throw e;
+ }
+ }
+
+ try {
+ const fptr = target.jsFuncToWasm(func, sig);
+ ft.set(ptr, fptr);
+ if(scoped){
+ cache.scopedAlloc.pushPtr(ptr);
+ }
+ }catch(e){
+ if(ptr===oldLen) cache.freeFuncIndexes.push(oldLen);
+ throw e;
+ }
+ return ptr;
+ };
+
+
+ target.installFunction = (func, sig)=>__installFunction(func, sig, false);
+
+
+ target.scopedInstallFunction = (func, sig)=>__installFunction(func, sig, true);
+
+
+ target.uninstallFunction = function(ptr){
+ if(!ptr && __NullPtr!==ptr) return undefined;
+
+ const ft = target.functionTable();
+ cache.freeFuncIndexes.push(ptr);
+ const rc = ft.get(ptr);
+ ft.set(ptr, null);
+ return rc;
+ };
+
+
+ target.peek = function f(ptr, type='i8'){
+ if(type.endsWith('*')) type = __ptrIR;
+ const c = (cache.memory && cache.heapSize === cache.memory.buffer.byteLength)
+ ? cache : heapWrappers();
+ const list = Array.isArray(ptr) ? [] : undefined;
+ let rc;
+ do{
+ if(list) ptr = arguments[0].shift();
+ switch(type){
+ case 'i1':
+ case 'i8': rc = c.HEAP8[Number(ptr)>>0]; break;
+ case 'i16': rc = c.HEAP16[Number(ptr)>>1]; break;
+ case 'i32': rc = c.HEAP32[Number(ptr)>>2]; break;
+ case 'float': case 'f32': rc = c.HEAP32F[Number(ptr)>>2]; break;
+ case 'double': case 'f64': rc = Number(c.HEAP64F[Number(ptr)>>3]); break;
+ case 'i64':
+ if(c.HEAP64){
+ rc = __BigInt(c.HEAP64[Number(ptr)>>3]);
+ break;
+ }
+
+ default:
+ toss('Invalid type for peek():',type);
+ }
+ if(list) list.push(rc);
+ }while(list && arguments[0].length);
+ return list || rc;
+ };
+
+
+ target.poke = function(ptr, value, type='i8'){
+ if (type.endsWith('*')) type = __ptrIR;
+ const c = (cache.memory && cache.heapSize === cache.memory.buffer.byteLength)
+ ? cache : heapWrappers();
+ for(const p of (Array.isArray(ptr) ? ptr : [ptr])){
+ switch (type) {
+ case 'i1':
+ case 'i8': c.HEAP8[Number(p)>>0] = value; continue;
+ case 'i16': c.HEAP16[Number(p)>>1] = value; continue;
+ case 'i32': c.HEAP32[Number(p)>>2] = value; continue;
+ case 'float': case 'f32': c.HEAP32F[Number(p)>>2] = value; continue;
+ case 'double': case 'f64': c.HEAP64F[Number(p)>>3] = value; continue;
+ case 'i64':
+ if(c.HEAP64){
+ c.HEAP64[Number(p)>>3] = __BigInt(value);
+ continue;
+ }
+
+ default:
+ toss('Invalid type for poke(): ' + type);
+ }
+ }
+ return this;
+ };
+
+
+ target.peekPtr = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), __ptrIR );
+
+
+ target.pokePtr = (ptr, value=0)=>target.poke(ptr, value, __ptrIR);
+
+
+ target.peek8 = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'i8' );
+
+ target.poke8 = (ptr, value)=>target.poke(ptr, value, 'i8');
+
+ target.peek16 = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'i16' );
+
+ target.poke16 = (ptr, value)=>target.poke(ptr, value, 'i16');
+
+ target.peek32 = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'i32' );
+
+ target.poke32 = (ptr, value)=>target.poke(ptr, value, 'i32');
+
+ target.peek64 = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'i64' );
+
+ target.poke64 = (ptr, value)=>target.poke(ptr, value, 'i64');
+
+ target.peek32f = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'f32' );
+
+ target.poke32f = (ptr, value)=>target.poke(ptr, value, 'f32');
+
+ target.peek64f = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'f64' );
+
+ target.poke64f = (ptr, value)=>target.poke(ptr, value, 'f64');
+
+
+ target.getMemValue = target.peek;
+
+ target.getPtrValue = target.peekPtr;
+
+ target.setMemValue = target.poke;
+
+ target.setPtrValue = target.pokePtr;
+
+
+ target.isPtr32 = (ptr)=>(
+ 'number'===typeof ptr && ptr>=0 && ptr===(ptr|0)
+ );
+
+
+ target.isPtr64 = (ptr)=>(
+ ('bigint'===typeof ptr) ? ptr >= 0 : target.isPtr32(ptr)
+ );
+
+
+ target.isPtr = (4===__ptrSize) ? target.isPtr32 : target.isPtr64;
+
+
+ target.cstrlen = function(ptr){
+ if(!ptr || !target.isPtr(ptr)) return null;
+ ptr = Number(ptr) ;
+ const h = heapWrappers().HEAP8U;
+ let pos = ptr;
+ for( ; h[pos] !== 0; ++pos ){}
+ return pos - ptr;
+ };
+
+
+ const __SAB = ('undefined'===typeof SharedArrayBuffer)
+ ? function(){} : SharedArrayBuffer;
+
+ const isSharedTypedArray = (aTypedArray)=>(aTypedArray.buffer instanceof __SAB);
+
+ target.isSharedTypedArray = isSharedTypedArray;
+
+
+ const typedArrayPart = (aTypedArray, begin, end)=>{
+ if( 8===__ptrSize ){
+
+ if( 'bigint'===typeof begin ) begin = Number(begin);
+ if( 'bigint'===typeof end ) end = Number(end);
+ }
+ return isSharedTypedArray(aTypedArray)
+ ? aTypedArray.slice(begin, end)
+ : aTypedArray.subarray(begin, end);
+ };
+
+ target.typedArrayPart = typedArrayPart;
+
+
+ const typedArrayToString = (typedArray, begin, end)=>
+ cache.utf8Decoder.decode(
+ typedArrayPart(typedArray, begin, end)
+ );
+
+ target.typedArrayToString = typedArrayToString;
+
+
+ target.cstrToJs = function(ptr){
+ const n = target.cstrlen(ptr);
+ return n
+ ? typedArrayToString(heapWrappers().HEAP8U, Number(ptr), Number(ptr)+n)
+ : (null===n ? n : "");
+ };
+
+
+ target.jstrlen = function(str){
+
+ if('string'!==typeof str) return null;
+ const n = str.length;
+ let len = 0;
+ for(let i = 0; i < n; ++i){
+ let u = str.charCodeAt(i);
+ if(u>=0xd800 && u<=0xdfff){
+ u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF);
+ }
+ if(u<=0x7f) ++len;
+ else if(u<=0x7ff) len += 2;
+ else if(u<=0xffff) len += 3;
+ else len += 4;
+ }
+ return len;
+ };
+
+
+ target.jstrcpy = function(jstr, tgt, offset = 0, maxBytes = -1, addNul = true){
+
+ if(!tgt || (!(tgt instanceof Int8Array) && !(tgt instanceof Uint8Array))){
+ toss("jstrcpy() target must be an Int8Array or Uint8Array.");
+ }
+ maxBytes = Number(maxBytes);
+ offset = Number(offset);
+ if(maxBytes<0) maxBytes = tgt.length - offset;
+ if(!(maxBytes>0) || !(offset>=0)) return 0;
+ let i = 0, max = jstr.length;
+ const begin = offset, end = offset + maxBytes - (addNul ? 1 : 0);
+ for(; i < max && offset < end; ++i){
+ let u = jstr.charCodeAt(i);
+ if(u>=0xd800 && u<=0xdfff){
+ u = 0x10000 + ((u & 0x3FF) << 10) | (jstr.charCodeAt(++i) & 0x3FF);
+ }
+ if(u<=0x7f){
+ if(offset >= end) break;
+ tgt[offset++] = u;
+ }else if(u<=0x7ff){
+ if(offset + 1 >= end) break;
+ tgt[offset++] = 0xC0 | (u >> 6);
+ tgt[offset++] = 0x80 | (u & 0x3f);
+ }else if(u<=0xffff){
+ if(offset + 2 >= end) break;
+ tgt[offset++] = 0xe0 | (u >> 12);
+ tgt[offset++] = 0x80 | ((u >> 6) & 0x3f);
+ tgt[offset++] = 0x80 | (u & 0x3f);
+ }else{
+ if(offset + 3 >= end) break;
+ tgt[offset++] = 0xf0 | (u >> 18);
+ tgt[offset++] = 0x80 | ((u >> 12) & 0x3f);
+ tgt[offset++] = 0x80 | ((u >> 6) & 0x3f);
+ tgt[offset++] = 0x80 | (u & 0x3f);
+ }
+ }
+ if(addNul) tgt[offset++] = 0;
+ return offset - begin;
+ };
+
+
+ target.cstrncpy = function(tgtPtr, srcPtr, n){
+ if(!tgtPtr || !srcPtr) toss("cstrncpy() does not accept NULL strings.");
+ if(n<0) n = target.cstrlen(strPtr)+1;
+ else if(!(n>0)) return 0;
+ const heap = target.heap8u();
+ let i = 0, ch;
+ const tgtNumber = Number(tgtPtr), srcNumber = Number(srcPtr);
+ for(; i < n && (ch = heap[srcNumber+i]); ++i){
+ heap[tgtNumber+i] = ch;
+ }
+ if(i<n) heap[tgtNumber + i++] = 0;
+ return i;
+ };
+
+
+ target.jstrToUintArray = (str, addNul=false)=>{
+ return cache.utf8Encoder.encode(addNul ? (str+"\0") : str);
+ };
+
+ const __affirmAlloc = (obj,funcName)=>{
+ if(!(obj.alloc instanceof Function) ||
+ !(obj.dealloc instanceof Function)){
+ toss("Object is missing alloc() and/or dealloc() function(s)",
+ "required by",funcName+"().");
+ }
+ };
+
+ const __allocCStr = function(jstr, returnWithLength, allocator, funcName){
+ __affirmAlloc(target, funcName);
+ if('string'!==typeof jstr) return null;
+ const u = cache.utf8Encoder.encode(jstr),
+ ptr = allocator(u.length+1);
+ let toFree = ptr;
+ try{
+ const heap = heapWrappers().HEAP8U;
+ heap.set(u, Number(ptr));
+ heap[__ptrAdd(ptr, u.length)] = 0;
+ toFree = __NullPtr;
+ return returnWithLength ? [ptr, u.length] : ptr;
+ }finally{
+ if( toFree ) target.dealloc(toFree);
+ }
+ };
+
+
+ target.allocCString =
+ (jstr, returnWithLength=false)=>__allocCStr(jstr, returnWithLength,
+ target.alloc, 'allocCString()');
+
+
+ target.scopedAllocPush = function(){
+ __affirmAlloc(target, 'scopedAllocPush');
+ const a = [];
+ cache.scopedAlloc.push(a);
+ return a;
+ };
+
+
+ target.scopedAllocPop = function(state){
+ __affirmAlloc(target, 'scopedAllocPop');
+ const n = arguments.length
+ ? cache.scopedAlloc.indexOf(state)
+ : cache.scopedAlloc.length-1;
+ if(n<0) toss("Invalid state object for scopedAllocPop().");
+ if(0===arguments.length) state = cache.scopedAlloc[n];
+ cache.scopedAlloc.splice(n,1);
+ for(let p; (p = state.pop()); ){
+ if(target.functionEntry(p)){
+
+ target.uninstallFunction(p);
+ }else{
+ target.dealloc(p);
+ }
+ }
+ };
+
+
+ target.scopedAlloc = function(n){
+ if(!cache.scopedAlloc.length){
+ toss("No scopedAllocPush() scope is active.");
+ }
+ const p = __asPtrType(target.alloc(n));
+ return cache.scopedAlloc.pushPtr(p);
+ };
+
+ Object.defineProperty(target.scopedAlloc, 'level', {
+ configurable: false, enumerable: false,
+ get: ()=>cache.scopedAlloc.length,
+ set: ()=>toss("The 'active' property is read-only.")
+ });
+
+
+ target.scopedAllocCString =
+ (jstr, returnWithLength=false)=>__allocCStr(jstr, returnWithLength,
+ target.scopedAlloc,
+ 'scopedAllocCString()');
+
+
+ const __allocMainArgv = function(isScoped, list){
+ const pList = target[
+ isScoped ? 'scopedAlloc' : 'alloc'
+ ]((list.length + 1) * target.ptr.size);
+ let i = 0;
+ list.forEach((e)=>{
+ target.pokePtr(__ptrAdd(pList, target.ptr.size * i++),
+ target[
+ isScoped ? 'scopedAllocCString' : 'allocCString'
+ ](""+e));
+ });
+ target.pokePtr(__ptrAdd(pList, target.ptr.size * i), 0);
+ return pList;
+ };
+
+
+ target.scopedAllocMainArgv = (list)=>__allocMainArgv(true, list);
+
+
+ target.allocMainArgv = (list)=>__allocMainArgv(false, list);
+
+
+ target.cArgvToJs = (argc, pArgv)=>{
+ const list = [];
+ for(let i = 0; i < argc; ++i){
+ const arg = target.peekPtr(__ptrAdd(pArgv, target.ptr.size * i));
+ list.push( arg ? target.cstrToJs(arg) : null );
+ }
+ return list;
+ };
+
+
+ target.scopedAllocCall = function(func){
+ target.scopedAllocPush();
+ try{ return func() } finally{ target.scopedAllocPop() }
+ };
+
+
+ const __allocPtr = function(howMany, safePtrSize, method){
+ __affirmAlloc(target, method);
+ const pIr = safePtrSize ? 'i64' : __ptrIR;
+ let m = target[method](howMany * (safePtrSize ? 8 : __ptrSize));
+ target.poke(m, 0, pIr)
+ if(1===howMany){
+ return m;
+ }
+ const a = [m];
+ for(let i = 1; i < howMany; ++i){
+ m = __ptrAdd(m, (safePtrSize ? 8 : __ptrSize));
+ a[i] = m;
+ target.poke(m, 0, pIr);
+ }
+ return a;
+ };
+
+
+ target.allocPtr =
+ (howMany=1, safePtrSize=true)=>__allocPtr(howMany, safePtrSize, 'alloc');
+
+
+ target.scopedAllocPtr =
+ (howMany=1, safePtrSize=true)=>__allocPtr(howMany, safePtrSize, 'scopedAlloc');
+
+
+ target.xGet = function(name){
+ return target.exports[name] || toss("Cannot find exported symbol:",name);
+ };
+
+ const __argcMismatch =
+ (f,n)=>toss(f+"() requires",n,"argument(s).");
+
+
+ target.xCall = function(fname, ...args){
+ const f = (fname instanceof Function) ? fname : target.xGet(fname);
+ if(!(f instanceof Function)) toss("Exported symbol",fname,"is not a function.");
+ if(f.length!==args.length){
+ __argcMismatch(((f===fname) ? f.name : fname),f.length)
+ ;
+ }
+ return (2===arguments.length && Array.isArray(arguments[1]))
+ ? f.apply(null, arguments[1])
+ : f.apply(null, args);
+ };
+
+
+ cache.xWrap = Object.create(null);
+ cache.xWrap.convert = Object.create(null);
+
+ cache.xWrap.convert.arg = new Map;
+
+ cache.xWrap.convert.result = new Map;
+
+ const xArg = cache.xWrap.convert.arg, xResult = cache.xWrap.convert.result;
+
+ const __xArgPtr = __asPtrType;
+ xArg
+ .set('i64', __BigInt)
+ .set('i32', (i)=>i|0)
+ .set('i16', (i)=>((i | 0) & 0xFFFF))
+ .set('i8', (i)=>((i | 0) & 0xFF))
+ .set('f32', (i)=>Number(i).valueOf())
+ .set('float', xArg.get('f32'))
+ .set('f64', xArg.get('f32'))
+ .set('double', xArg.get('f64'))
+ .set('int', xArg.get('i32'))
+ .set('null', (i)=>i)
+ .set(null, xArg.get('null'))
+ .set('**', __xArgPtr)
+ .set('*', __xArgPtr)
+ ;
+ xResult.set('*', __xArgPtr)
+ .set('pointer', __xArgPtr)
+ .set('number', (v)=>Number(v))
+ .set('void', (v)=>undefined)
+ .set(undefined, xResult.get('void'))
+ .set('null', (v)=>v)
+ .set(null, xResult.get('null'))
+ ;
+
+
+ for(const t of [
+ 'i8', 'i16', 'i32', 'i64', 'int',
+ 'f32', 'float', 'f64', 'double'
+ ]){
+ xArg.set(t+'*', __xArgPtr);
+ xResult.set(t+'*', __xArgPtr);
+ xResult.set(
+ t, xArg.get(t)
+ || toss("Maintenance required: missing arg converter for",t)
+ );
+ }
+
+
+ const __xArgString = (v)=>{
+ return ('string'===typeof v)
+ ? target.scopedAllocCString(v)
+ : __asPtrType(v);
+ };
+
+ xArg.set('string', __xArgString)
+ .set('utf8', __xArgString)
+
+ ;
+
+ xResult
+ .set('string', (i)=>target.cstrToJs(i))
+ .set('utf8', xResult.get('string'))
+ .set('string:dealloc', (i)=>{
+ try { return i ? target.cstrToJs(i) : null }
+ finally{ target.dealloc(i) }
+ })
+ .set('utf8:dealloc', xResult.get('string:dealloc'))
+ .set('json', (i)=>JSON.parse(target.cstrToJs(i)))
+ .set('json:dealloc', (i)=>{
+ try{ return i ? JSON.parse(target.cstrToJs(i)) : null }
+ finally{ target.dealloc(i) }
+ });
+
+
+ const AbstractArgAdapter = class {
+ constructor(opt){
+ this.name = opt.name || 'unnamed adapter';
+ }
+
+ convertArg(v,argv,argIndex){
+ toss("AbstractArgAdapter must be subclassed.");
+ }
+ };
+
+
+ xArg.FuncPtrAdapter = class FuncPtrAdapter extends AbstractArgAdapter {
+ constructor(opt) {
+ super(opt);
+ if(xArg.FuncPtrAdapter.warnOnUse){
+ console.warn('xArg.FuncPtrAdapter is an internal-only API',
+ 'and is not intended to be invoked from',
+ 'client-level code. Invoked with:',opt);
+ }
+ this.name = opt.name || "unnamed";
+ this.signature = opt.signature;
+ if(opt.contextKey instanceof Function){
+ this.contextKey = opt.contextKey;
+ if(!opt.bindScope) opt.bindScope = 'context';
+ }
+ this.bindScope = opt.bindScope
+ || toss("FuncPtrAdapter options requires a bindScope (explicit or implied).");
+ if(FuncPtrAdapter.bindScopes.indexOf(opt.bindScope)<0){
+ toss("Invalid options.bindScope ("+opt.bindMod+") for FuncPtrAdapter. "+
+ "Expecting one of: ("+FuncPtrAdapter.bindScopes.join(', ')+')');
+ }
+ this.isTransient = 'transient'===this.bindScope;
+ this.isContext = 'context'===this.bindScope;
+ this.isPermanent = 'permanent'===this.bindScope;
+ this.singleton = ('singleton'===this.bindScope) ? [] : undefined;
+
+ this.callProxy = (opt.callProxy instanceof Function)
+ ? opt.callProxy : undefined;
+ }
+
+
+
+
+ contextKey(argv,argIndex){
+ return this;
+ }
+
+
+ contextMap(key){
+ const cm = (this.__cmap || (this.__cmap = new Map));
+ let rc = cm.get(key);
+ if(undefined===rc) cm.set(key, (rc = []));
+ return rc;
+ }
+
+
+ convertArg(v,argv,argIndex){
+ let pair = this.singleton;
+ if(!pair && this.isContext){
+ pair = this.contextMap(this.contextKey(argv,argIndex));
+
+ }
+ if( 0 ){
+ FuncPtrAdapter.debugOut("FuncPtrAdapter.convertArg()",this.name,
+ 'signature =',this.signature,
+ 'transient ?=',this.transient,
+ 'pair =',pair,
+ 'v =',v);
+ }
+ if(pair && 2===pair.length && pair[0]===v){
+
+ return pair[1];
+ }
+ if(v instanceof Function){
+
+
+ if(this.callProxy){
+ v = this.callProxy(v);
+ }
+ const fp = __installFunction(v, this.signature, this.isTransient);
+ if(FuncPtrAdapter.debugFuncInstall){
+ FuncPtrAdapter.debugOut("FuncPtrAdapter installed", this,
+ this.contextKey(argv,argIndex), '@'+fp, v);
+ }
+ if(pair){
+
+ if(pair[1]){
+ if(FuncPtrAdapter.debugFuncInstall){
+ FuncPtrAdapter.debugOut("FuncPtrAdapter uninstalling", this,
+ this.contextKey(argv,argIndex), '@'+pair[1], v);
+ }
+ try{
+
+ cache.scopedAlloc.pushPtr(pair[1]);
+ }
+ catch(e){}
+ }
+ pair[0] = arguments[0] || __NullPtr;
+ pair[1] = fp;
+ }
+ return fp;
+ }else if(target.isPtr(v) || null===v || undefined===v){
+ if(pair && pair[1] && pair[1]!==v){
+
+ if(FuncPtrAdapter.debugFuncInstall){
+ FuncPtrAdapter.debugOut("FuncPtrAdapter uninstalling", this,
+ this.contextKey(argv,argIndex), '@'+pair[1], v);
+ }
+ try{cache.scopedAlloc.pushPtr(pair[1]);}
+ catch(e){}
+ pair[0] = pair[1] = (v || __NullPtr);
+ }
+ return v || __NullPtr;
+ }else{
+ throw new TypeError("Invalid FuncPtrAdapter argument type. "+
+ "Expecting a function pointer or a "+
+ (this.name ? this.name+' ' : '')+
+ "function matching signature "+
+ this.signature+".");
+ }
+ }
+ };
+
+
+ xArg.FuncPtrAdapter.warnOnUse = false;
+
+
+ xArg.FuncPtrAdapter.debugFuncInstall = false;
+
+
+ xArg.FuncPtrAdapter.debugOut = console.debug.bind(console);
+
+
+ xArg.FuncPtrAdapter.bindScopes = [
+ 'transient', 'context', 'singleton', 'permanent'
+ ];
+
+
+ const __xArgAdapterCheck =
+ (t)=>xArg.get(t) || toss("Argument adapter not found:",t);
+
+
+ const __xResultAdapterCheck =
+ (t)=>xResult.get(t) || toss("Result adapter not found:",t);
+
+
+ cache.xWrap.convertArg = (t,...args)=>__xArgAdapterCheck(t)(...args);
+
+ cache.xWrap.convertArgNoCheck = (t,...args)=>xArg.get(t)(...args);
+
+
+ cache.xWrap.convertResult =
+ (t,v)=>(null===t ? v : (t ? __xResultAdapterCheck(t)(v) : undefined));
+
+ cache.xWrap.convertResultNoCheck =
+ (t,v)=>(null===t ? v : (t ? xResult.get(t)(v) : undefined));
+
+
+ target.xWrap = function callee(fArg, resultType, ...argTypes){
+ if(3===arguments.length && Array.isArray(arguments[2])){
+ argTypes = arguments[2];
+ }
+ if(target.isPtr(fArg)){
+ fArg = target.functionEntry(fArg)
+ || toss("Function pointer not found in WASM function table.");
+ }
+ const fIsFunc = (fArg instanceof Function);
+ const xf = fIsFunc ? fArg : target.xGet(fArg);
+ if(fIsFunc) fArg = xf.name || 'unnamed function';
+ if(argTypes.length!==xf.length) __argcMismatch(fArg, xf.length);
+ if( 0===xf.length
+ && (null===resultType || 'null'===resultType) ){
+
+ return xf;
+ }
+ ;
+ __xResultAdapterCheck(resultType);
+ for(const t of argTypes){
+ if(t instanceof AbstractArgAdapter) xArg.set(t, (...args)=>t.convertArg(...args));
+ else __xArgAdapterCheck(t);
+ }
+ const cxw = cache.xWrap;
+ if(0===xf.length){
+
+ return (...args)=>(args.length
+ ? __argcMismatch(fArg, xf.length)
+ : cxw.convertResult(resultType, xf.call(null)));
+ }
+ return function(...args){
+ if(args.length!==xf.length) __argcMismatch(fArg, xf.length);
+ const scope = target.scopedAllocPush();
+ try{
+
+ let i = 0;
+ if( callee.debug ){
+ console.debug("xWrap() preparing: resultType ",resultType, 'xf',xf,"argTypes",argTypes,"args",args);
+ }
+ for(; i < args.length; ++i) args[i] = cxw.convertArgNoCheck(
+ argTypes[i], args[i], args, i
+ );
+ if( callee.debug ){
+ console.debug("xWrap() calling: resultType ",resultType, 'xf',xf,"argTypes",argTypes,"args",args);
+ }
+ return cxw.convertResultNoCheck(resultType, xf.apply(null,args));
+ }finally{
+ target.scopedAllocPop(scope);
+ }
+ };
+ };
+
+
+ const __xAdapter = function(func, argc, typeName, adapter, modeName, xcvPart){
+ if('string'===typeof typeName){
+ if(1===argc) return xcvPart.get(typeName);
+ else if(2===argc){
+ if(!adapter){
+ xcvPart.delete(typeName);
+ return func;
+ }else if(!(adapter instanceof Function)){
+ toss(modeName,"requires a function argument.");
+ }
+ xcvPart.set(typeName, adapter);
+ return func;
+ }
+ }
+ toss("Invalid arguments to",modeName);
+ };
+
+
+ target.xWrap.resultAdapter = function f(typeName, adapter){
+ return __xAdapter(f, arguments.length, typeName, adapter,
+ 'resultAdapter()', xResult);
+ };
+
+
+ target.xWrap.argAdapter = function f(typeName, adapter){
+ return __xAdapter(f, arguments.length, typeName, adapter,
+ 'argAdapter()', xArg);
+ };
+
+ target.xWrap.FuncPtrAdapter = xArg.FuncPtrAdapter;
+
+
+ target.xCallWrapped = function(fArg, resultType, argTypes, ...args){
+ if(Array.isArray(arguments[3])) args = arguments[3];
+ return target.xWrap(fArg, resultType, argTypes||[]).apply(null, args||[]);
+ };
+
+
+ target.xWrap.testConvertArg = cache.xWrap.convertArg;
+
+
+ target.xWrap.testConvertResult = cache.xWrap.convertResult;
+
+ return target;
+};
+
+
+globalThis.WhWasmUtilInstaller
+.yawl = function yawl(config){
+ 'use strict';
+ const wfetch = ()=>fetch(config.uri, {credentials: 'same-origin'});
+ const wui = this;
+ const finalThen = function(arg){
+
+ if(config.wasmUtilTarget){
+ const toss = (...args)=>{throw new Error(args.join(' '))};
+ const tgt = config.wasmUtilTarget;
+ tgt.module = arg.module;
+ tgt.instance = arg.instance;
+
+ if(!tgt.instance.exports.memory){
+
+ tgt.memory = config?.imports?.env?.memory
+ || toss("Missing 'memory' object!");
+ }
+ if(!tgt.alloc && arg.instance.exports.malloc){
+ const exports = arg.instance.exports;
+ tgt.alloc = function(n){
+ return exports.malloc(n) || toss("Allocation of",n,"bytes failed.");
+ };
+ tgt.dealloc = function(m){m && exports.free(m)};
+ }
+ wui(tgt);
+ }
+ arg.config = config;
+ if(config.onload) config.onload(arg);
+ return arg ;
+ };
+ const loadWasm = WebAssembly.instantiateStreaming
+ ? ()=>WebAssembly
+ .instantiateStreaming(wfetch(), config.imports||{})
+ .then(finalThen)
+ : ()=> wfetch()
+ .then(response => response.arrayBuffer())
+ .then(bytes => WebAssembly.instantiate(bytes, config.imports||{}))
+ .then(finalThen)
+ ;
+ return loadWasm;
+}.bind(
+globalThis.WhWasmUtilInstaller
+);
+
+'use strict';
+globalThis.Jaccwabyt =
+function StructBinderFactory(config){
+ 'use strict';
+
+
+
+ const toss = (...args)=>{throw new Error(args.join(' '))};
+
+ {
+ let h = config.heap;
+ if( h instanceof WebAssembly.Memory ){
+ h = function(){return new Uint8Array(this.buffer)}.bind(h);
+ }else if( !(h instanceof Function) ){
+
+ toss("config.heap must be WebAssembly.Memory instance or",
+ "a function which returns one.");
+ }
+ config.heap = h;
+ }
+ ['alloc','dealloc'].forEach(function(k){
+ (config[k] instanceof Function) ||
+ toss("Config option '"+k+"' must be a function.");
+ });
+ const SBF = StructBinderFactory;
+ const heap = config.heap,
+ alloc = config.alloc,
+ dealloc = config.dealloc,
+ realloc = (config.realloc || function(){
+ toss("This StructBinderFactory was configured without realloc()");
+
+ }),
+ log = config.log || console.debug.bind(console),
+ memberPrefix = (config.memberPrefix || ""),
+ memberSuffix = (config.memberSuffix || ""),
+ BigInt = globalThis['BigInt'],
+ BigInt64Array = globalThis['BigInt64Array'],
+ bigIntEnabled = config.bigIntEnabled ?? !!BigInt64Array;
+
+
+ let ptr;
+ const ptrSize = config.pointerSize
+ || config.ptrSize
+ || ('bigint'===typeof (ptr = alloc(1)) ? 8 : 4);
+ const ptrIR = config.pointerIR
+ || config.ptrIR
+ || (4===ptrSize ? 'i32' : 'i64');
+ if( ptr ){
+ dealloc(ptr);
+ ptr = undefined;
+ }
+
+
+ if(ptrSize!==4 && ptrSize!==8) toss("Invalid pointer size:",ptrSize);
+ if(ptrIR!=='i32' && ptrIR!=='i64') toss("Invalid pointer representation:",ptrIR);
+
+
+ const __BigInt = (bigIntEnabled && BigInt)
+ ? (v)=>BigInt(v || 0)
+ : (v)=>toss("BigInt support is disabled in this build.");
+ const __asPtrType = ('i32'==ptrIR) ? Number : __BigInt;
+ const __NullPtr = __asPtrType(0);
+
+
+ const __ptrAdd = function(...args){
+ let rc = __NullPtr;
+ for( let i = 0; i < args.length; ++i ){
+ rc += __asPtrType(args[i]);
+ }
+ return rc;
+ };
+
+ const __ptrAddSelf = function(...args){
+ return __ptrAdd(this.pointer,...args);
+ };
+
+ if(!SBF.debugFlags){
+ SBF.__makeDebugFlags = function(deriveFrom=null){
+
+ if(deriveFrom && deriveFrom.__flags) deriveFrom = deriveFrom.__flags;
+ const f = function f(flags){
+ if(0===arguments.length){
+ return f.__flags;
+ }
+ if(flags<0){
+ delete f.__flags.getter; delete f.__flags.setter;
+ delete f.__flags.alloc; delete f.__flags.dealloc;
+ }else{
+ f.__flags.getter = 0!==(0x01 & flags);
+ f.__flags.setter = 0!==(0x02 & flags);
+ f.__flags.alloc = 0!==(0x04 & flags);
+ f.__flags.dealloc = 0!==(0x08 & flags);
+ }
+ return f._flags;
+ };
+ Object.defineProperty(f,'__flags', {
+ iterable: false, writable: false,
+ value: Object.create(deriveFrom)
+ });
+ if(!deriveFrom) f(0);
+ return f;
+ };
+ SBF.debugFlags = SBF.__makeDebugFlags();
+ }
+
+ const isLittleEndian = true || (function() {
+ const buffer = new ArrayBuffer(2);
+ new DataView(buffer).setInt16(0, 256, true );
+
+ return new Int16Array(buffer)[0] === 256;
+ })() ;
+
+
+
+
+ const isFuncSig = (s)=>'('===s[1];
+
+ const isPtrSig = (s)=>'p'===s || 'P'===s || 's'===s;
+ const isAutoPtrSig = (s)=>'P'===s ;
+
+ const sigLetter = (s)=>s ? (isFuncSig(s) ? 'p' : s[0]) : undefined;
+
+
+ const sigIR = function(s){
+ switch(sigLetter(s)){
+ case 'c': case 'C': return 'i8';
+ case 'i': return 'i32';
+ case 'p': case 'P': case 's': return ptrIR;
+ case 'j': return 'i64';
+ case 'f': return 'float';
+ case 'd': return 'double';
+ }
+ toss("Unhandled signature IR:",s);
+ };
+
+
+ const sigSize = function(s){
+ switch(sigLetter(s)){
+ case 'c': case 'C': return 1;
+ case 'i': return 4;
+ case 'p': case 'P': case 's': return ptrSize;
+ case 'j': return 8;
+ case 'f': return 4;
+ case 'd': return 8;
+ }
+ toss("Unhandled signature sizeof:",s);
+ };
+
+ const affirmBigIntArray = BigInt64Array
+ ? ()=>true : ()=>toss('BigInt64Array is not available.');
+
+
+ const sigDVGetter = function(s){
+ switch(sigLetter(s)) {
+ case 'p': case 'P': case 's': {
+ switch(ptrSize){
+ case 4: return 'getInt32';
+ case 8: return affirmBigIntArray() && 'getBigInt64';
+ }
+ break;
+ }
+ case 'i': return 'getInt32';
+ case 'c': return 'getInt8';
+ case 'C': return 'getUint8';
+ case 'j': return affirmBigIntArray() && 'getBigInt64';
+ case 'f': return 'getFloat32';
+ case 'd': return 'getFloat64';
+ }
+ toss("Unhandled DataView getter for signature:",s);
+ };
+
+
+ const sigDVSetter = function(s){
+ switch(sigLetter(s)){
+ case 'p': case 'P': case 's': {
+ switch(ptrSize){
+ case 4: return 'setInt32';
+ case 8: return affirmBigIntArray() && 'setBigInt64';
+ }
+ break;
+ }
+ case 'i': return 'setInt32';
+ case 'c': return 'setInt8';
+ case 'C': return 'setUint8';
+ case 'j': return affirmBigIntArray() && 'setBigInt64';
+ case 'f': return 'setFloat32';
+ case 'd': return 'setFloat64';
+ }
+ toss("Unhandled DataView setter for signature:",s);
+ };
+
+
+ const sigDVSetWrapper = function(s){
+ switch(sigLetter(s)) {
+ case 'i': case 'f': case 'c': case 'C': case 'd': return Number;
+ case 'j': return __BigInt;
+ case 'p': case 'P': case 's':
+ switch(ptrSize){
+ case 4: return Number;
+ case 8: return __BigInt;
+ }
+ break;
+ }
+ toss("Unhandled DataView set wrapper for signature:",s);
+ };
+
+
+ const sPropName = (s,k)=>s+'::'+k;
+
+ const __propThrowOnSet = function(structName,propName){
+ return ()=>toss(sPropName(structName,propName),"is read-only.");
+ };
+
+
+ const getInstanceHandle = function f(obj, create=true){
+ let ii = f.map.get(obj);
+ if( !ii && create ){
+ f.map.set(obj, (ii=f.create(obj)));
+ }
+ return ii;
+ };
+ getInstanceHandle.map = new WeakMap;
+ getInstanceHandle.create = (forObj)=>{
+ return Object.assign(Object.create(null),{
+ o: forObj,
+ p: undefined,
+ ownsPointer: false,
+ zod: false,
+ xb: 0
+ });
+ };
+
+
+ const rmInstanceHandle = (obj)=>getInstanceHandle.map.delete(obj)
+ ;
+
+ const __isPtr32 = (ptr)=>('number'===typeof ptr && (ptr===(ptr|0)) && ptr>=0);
+ const __isPtr64 = (ptr)=>(
+ ('bigint'===typeof ptr && ptr >= 0) || __isPtr32(ptr)
+ );
+
+
+ const __isPtr = (4===ptrSize) ? __isPtr32 : __isPtr64;
+
+ const __isNonNullPtr = (v)=>__isPtr(v) && (v>0);
+
+
+ const __freeStruct = function(ctor, obj, m){
+ const ii = getInstanceHandle(obj, false);
+ if( !ii ) return;
+ rmInstanceHandle(obj);
+ if( !m && !(m = ii.p) ){
+ console.warn("Cannot(?) happen: __freeStruct() found no instanceInfo");
+ return;
+ }
+ if(Array.isArray(obj.ondispose)){
+ let x;
+ while((x = obj.ondispose.pop())){
+ try{
+ if(x instanceof Function) x.call(obj);
+ else if(x instanceof StructType) x.dispose();
+ else if(__isPtr(x)) dealloc(x);
+
+
+ }catch(e){
+ console.warn("ondispose() for",ctor.structName,'@',
+ m,'threw. NOT propagating it.',e);
+ }
+ }
+ }else if(obj.ondispose instanceof Function){
+ try{obj.ondispose()}
+ catch(e){
+
+ console.warn("ondispose() for",ctor.structName,'@',
+ m,'threw. NOT propagating it.',e);
+ }
+ }
+ delete obj.ondispose;
+ if(ctor.debugFlags.__flags.dealloc){
+ log("debug.dealloc:",(ii.ownsPointer?"":"EXTERNAL"),
+ ctor.structName,"instance:",
+ ctor.structInfo.sizeof,"bytes @"+m);
+ }
+ if(ii.ownsPointer){
+ if( ii.zod || ctor.structInfo.zeroOnDispose ){
+ heap().fill(0, Number(m),
+ Number(m) + ctor.structInfo.sizeof + ii.xb);
+ }
+ dealloc(m);
+ }
+ };
+
+
+ const rop0 = ()=>{return {configurable: false, writable: false,
+ iterable: false}};
+
+
+ const rop = (v)=>{return {...rop0(), value: v}};
+
+
+ const __allocStruct = function f(ctor, obj, xm){
+ let opt;
+ const checkPtr = (ptr)=>{
+ __isNonNullPtr(ptr) ||
+ toss("Invalid pointer value",arguments[0],"for",ctor.structName,"constructor.");
+ };
+ if( arguments.length>=3 ){
+ if( xm && ('object'===typeof xm) ){
+ opt = xm;
+ xm = opt?.wrap;
+ }else{
+ checkPtr(xm);
+ opt = {wrap: xm};
+ }
+ }else{
+ opt = {}
+ }
+
+ const fill = !xm ;
+ let nAlloc = 0;
+ let ownsPointer = false;
+ if(xm){
+
+ checkPtr(xm);
+ ownsPointer = !!opt?.takeOwnership;
+ }else{
+ const nX = opt?.extraBytes ?? 0;
+ if( nX<0 || (nX!==(nX|0)) ){
+ toss("Invalid extraBytes value:",opt?.extraBytes);
+ }
+ nAlloc = ctor.structInfo.sizeof + nX;
+ xm = alloc(nAlloc)
+ || toss("Allocation of",ctor.structName,"structure failed.");
+ ownsPointer = true;
+ }
+ try {
+ if( opt?.debugFlags ){
+
+ obj.debugFlags(opt.debugFlags);
+ }
+ if(ctor.debugFlags.__flags.alloc){
+ log("debug.alloc:",(fill?"":"EXTERNAL"),
+ ctor.structName,"instance:",
+ ctor.structInfo.sizeof,"bytes @"+xm);
+ }
+ if(fill){
+ heap().fill(0, Number(xm), Number(xm) + nAlloc);
+ }
+ const ii = getInstanceHandle(obj);
+ ii.p = xm;
+ ii.ownsPointer = ownsPointer;
+ ii.xb = nAlloc ? (nAlloc-ctor.structInfo.sizeof) : 0;
+ ii.zod = !!opt?.zeroOnDispose;
+ if( opt?.ondispose && opt.ondispose!==xm ){
+ obj.addOnDispose( opt.ondispose );
+ }
+ }catch(e){
+ __freeStruct(ctor, obj, xm);
+ throw e;
+ }
+ };
+
+
+ const looksLikeASig = function f(sig){
+ f.rxSig1 ??= /^[ipPsjfdcC]$/;
+ f.rxSig2 ??= /^[vipPsjfdcC]\([ipPsjfdcC]*\)$/;
+ return f.rxSig1.test(sig) || f.rxSig2.test(sig);
+ };
+
+
+ const __adaptorsFor = function(who){
+ let x = this.get(who);
+ if( !x ){
+ x = [ Object.create(null), Object.create(null), Object.create(null) ];
+ this.set(who, x);
+ }
+ return x;
+ }.bind(new WeakMap);
+
+
+ const __adaptor = function(who, which, key, proxy){
+ const a = __adaptorsFor(who)[which];
+ if(3===arguments.length) return a[key];
+ if( proxy ) return a[key] = proxy;
+ return delete a[key];
+ };
+
+ const noopAdapter = (x)=>x;
+
+
+ const __adaptGet = function(key, ...args){
+ return __adaptor(this, 0, key, ...args);
+ };
+
+ const __affirmNotASig = function(ctx,key){
+ looksLikeASig(key) &&
+ toss(ctx,"(",key,") collides with a data type signature.");
+ };
+
+
+ const __adaptSet = function(key, ...args){
+ __affirmNotASig('Setter adaptor',key);
+ return __adaptor(this, 1, key, ...args);
+ };
+
+
+ const __adaptStruct = function(key, ...args){
+ __affirmNotASig('Struct adaptor',key);
+ return __adaptor(this, 2, key, ...args);
+ };
+
+
+ const __adaptStruct2 = function(who,key){
+ const si = ('string'===typeof key)
+ ? __adaptor(who, 2, key) : key;
+ if( 'object'!==typeof si ){
+ toss("Invalid struct mapping object. Arg =",key,JSON.stringify(si));
+ }
+ return si;
+ };
+
+ const __memberKey = (k)=>memberPrefix + k + memberSuffix;
+ const __memberKeyProp = rop(__memberKey);
+
+
+
+ const __lookupMember = function(structInfo, memberName, tossIfNotFound=true){
+ let m = structInfo.members[memberName];
+ if(!m && (memberPrefix || memberSuffix)){
+
+ for(const v of Object.values(structInfo.members)){
+ if(v.key===memberName){ m = v; break; }
+ }
+ if(!m && tossIfNotFound){
+ toss(sPropName(structInfo.name || structInfo.structName, memberName),
+ 'is not a mapped struct member.');
+ }
+ }
+ return m;
+ };
+
+
+ const __memberSignature = function f(obj,memberName,emscriptenFormat=false){
+ if(!f._) f._ = (x)=>x.replace(/[^vipPsjrdcC]/g,"").replace(/[pPscC]/g,'i');
+ const m = __lookupMember(obj.structInfo, memberName, true);
+ return emscriptenFormat ? f._(m.signature) : m.signature;
+ };
+
+
+ const __structMemberKeys = rop(function(){
+ const a = [];
+ for(const k of Object.keys(this.structInfo.members)){
+ a.push(this.memberKey(k));
+ }
+ return a;
+ });
+
+ const __utf8Decoder = new TextDecoder('utf-8');
+ const __utf8Encoder = new TextEncoder();
+
+ const __SAB = ('undefined'===typeof SharedArrayBuffer)
+ ? function(){} : SharedArrayBuffer;
+ const __utf8Decode = function(arrayBuffer, begin, end){
+ if( 8===ptrSize ){
+ begin = Number(begin);
+ end = Number(end);
+ }
+ return __utf8Decoder.decode(
+ (arrayBuffer.buffer instanceof __SAB)
+ ? arrayBuffer.slice(begin, end)
+ : arrayBuffer.subarray(begin, end)
+ );
+ };
+
+
+ const __memberIsString = function(obj,memberName, tossIfNotFound=false){
+ const m = __lookupMember(obj.structInfo, memberName, tossIfNotFound);
+ return (m && 1===m.signature.length && 's'===m.signature[0]) ? m : false;
+ };
+
+
+ const __affirmCStringSignature = function(member){
+ if('s'===member.signature) return;
+ toss("Invalid member type signature for C-string value:",
+ JSON.stringify(member));
+ };
+
+
+ const __memberToJsString = function f(obj,memberName){
+ const m = __lookupMember(obj.structInfo, memberName, true);
+ __affirmCStringSignature(m);
+ const addr = obj[m.key];
+
+ if(!addr) return null;
+ let pos = addr;
+ const mem = heap();
+ for( ; mem[pos]!==0; ++pos ) {
+
+ };
+
+ return (addr===pos) ? "" : __utf8Decode(mem, addr, pos);
+ };
+
+
+ const __addOnDispose = function(obj, ...v){
+ if(obj.ondispose){
+ if(!Array.isArray(obj.ondispose)){
+ obj.ondispose = [obj.ondispose];
+ }
+ }else{
+ obj.ondispose = [];
+ }
+ obj.ondispose.push(...v);
+ };
+
+
+ const __allocCString = function(str){
+ const u = __utf8Encoder.encode(str);
+ const mem = alloc(u.length+1);
+ if(!mem) toss("Allocation error while duplicating string:",str);
+ const h = heap();
+
+
+ h.set(u, Number(mem));
+ h[__ptrAdd(mem, u.length)] = 0;
+
+ return mem;
+ };
+
+
+ const __setMemberCString = function(obj, memberName, str){
+ const m = __lookupMember(obj.structInfo, memberName, true);
+ __affirmCStringSignature(m);
+
+ const mem = __allocCString(str);
+ obj[m.key] = mem;
+ __addOnDispose(obj, mem);
+ return obj;
+ };
+
+
+ const StructType = function StructType(structName, structInfo){
+ if(arguments[2]!==rop){
+ toss("Do not call the StructType constructor",
+ "from client-level code.");
+ }
+ Object.defineProperties(this,{
+
+ structName: rop(structName),
+ structInfo: rop(structInfo)
+ });
+ };
+
+
+ StructType.prototype = Object.create(null, {
+ dispose: rop(function(){__freeStruct(this.constructor, this)}),
+ lookupMember: rop(function(memberName, tossIfNotFound=true){
+ return __lookupMember(this.structInfo, memberName, tossIfNotFound);
+ }),
+ memberToJsString: rop(function(memberName){
+ return __memberToJsString(this, memberName);
+ }),
+ memberIsString: rop(function(memberName, tossIfNotFound=true){
+ return __memberIsString(this, memberName, tossIfNotFound);
+ }),
+ memberKey: __memberKeyProp,
+ memberKeys: __structMemberKeys,
+ memberSignature: rop(function(memberName, emscriptenFormat=false){
+ return __memberSignature(this, memberName, emscriptenFormat);
+ }),
+ memoryDump: rop(function(){
+ const p = this.pointer;
+ return p
+ ? new Uint8Array(heap().slice(Number(p), Number(p) + this.structInfo.sizeof))
+ : null;
+ }),
+ extraBytes: {
+ configurable: false, enumerable: false,
+ get: function(){return getInstanceHandle(this, false)?.xb ?? 0;}
+ },
+ zeroOnDispose: {
+ configurable: false, enumerable: false,
+ get: function(){
+ return getInstanceHandle(this, false)?.zod
+ ?? !!this.structInfo.zeroOnDispose;
+ }
+ },
+ pointer: {
+ configurable: false, enumerable: false,
+ get: function(){return getInstanceHandle(this, false)?.p},
+ set: ()=>toss("Cannot assign the 'pointer' property of a struct.")
+
+
+
+ },
+ setMemberCString: rop(function(memberName, str){
+ return __setMemberCString(this, memberName, str);
+ })
+ });
+
+ Object.assign(StructType.prototype,{
+ addOnDispose: function(...v){
+ __addOnDispose(this,...v);
+ return this;
+ }
+ });
+
+
+ Object.defineProperties(StructType, {
+ allocCString: rop(__allocCString),
+ isA: rop((v)=>v instanceof StructType),
+ hasExternalPointer: rop((v)=>{
+ const ii = getInstanceHandle(v, false);
+ return !!(ii?.p && !ii?.ownsPointer);
+ }),
+ memberKey: __memberKeyProp
+
+ });
+
+
+ const memberGetterProxy = function(si){
+ return si.get || (si.adaptGet
+ ? StructBinder.adaptGet(si.adaptGet)
+ : undefined);
+ };
+
+
+ const memberSetterProxy = function(si){
+ return si.set || (si.adaptSet
+ ? StructBinder.adaptSet(si.adaptSet)
+ : undefined);
+ };
+
+
+ const makeMemberStructWrapper = function callee(ctor, name, si){
+
+ const __innerStructs = (callee.innerStructs ??= new Map());
+ const key = ctor.memberKey(name);
+ if( undefined!==si.signature ){
+ toss("'signature' cannot be used on an embedded struct (",
+ ctor.structName,".",key,").");
+ }
+ if( memberSetterProxy(si) ){
+ toss("'set' and 'adaptSet' are not permitted for nested struct members.");
+ }
+
+ si.structName ??= ctor.structName+'::'+name;
+ si.key = key;
+ si.name = name;
+ si.constructor = this.call(this, si.structName, si);
+
+
+ const getterProxy = memberGetterProxy(si);
+ const prop = Object.assign(Object.create(null),{
+ configurable: false,
+ enumerable: false,
+ set: __propThrowOnSet(ctor.structName, key),
+ get: function(){
+ const dbg = this.debugFlags.__flags;
+ const p = this.pointer;
+ const k = p+'.'+key;
+ let s = __innerStructs.get(k);
+ if(dbg.getter){ log("debug.getter: k =",k); }
+ if( !s ){
+ s = new si.constructor(__ptrAdd(p, si.offset));
+ __innerStructs.set(k, s);
+ this.addOnDispose(()=>s.dispose());
+ s.addOnDispose(()=>__innerStructs.delete(k));
+
+ }
+ if(getterProxy) s = getterProxy.apply(this,[s,key]);
+ if(dbg.getter) log("debug.getter: result =",s);
+ return s;
+ }
+ });
+ Object.defineProperty(ctor.prototype, key, prop);
+ };
+
+
+ const makeMemberWrapper = function f(ctor, name, si){
+ si = __adaptStruct2(this, si);
+ if( si.members ){
+ return makeMemberStructWrapper.call(this, ctor, name, si);
+ }
+
+ if(!f.cache){
+
+ f.cache = {getters: {}, setters: {}, sw:{}};
+ const a = ['i','c','C','p','P','s','f','d','v()'];
+ if(bigIntEnabled) a.push('j');
+ a.forEach(function(v){
+ f.cache.getters[v] = sigDVGetter(v) ;
+ f.cache.setters[v] = sigDVSetter(v) ;
+ f.cache.sw[v] = sigDVSetWrapper(v) ;
+ });
+ f.sigCheck = function(obj, name, key,sig){
+ if(Object.prototype.hasOwnProperty.call(obj, key)){
+ toss(obj.structName,'already has a property named',key+'.');
+ }
+ looksLikeASig(sig)
+ || toss("Malformed signature for",
+ sPropName(obj.structName,name)+":",sig);
+ };
+ }
+ const key = ctor.memberKey(name);
+ f.sigCheck(ctor.prototype, name, key, si.signature);
+ si.key = key;
+ si.name = name;
+ const sigGlyph = sigLetter(si.signature);
+ const xPropName = sPropName(ctor.structName,key);
+ const dbg = ctor.debugFlags.__flags;
+
+ const getterProxy = memberGetterProxy(si);
+ const prop = Object.create(null);
+ prop.configurable = false;
+ prop.enumerable = false;
+ prop.get = function(){
+
+ if(dbg.getter){
+ log("debug.getter:",f.cache.getters[sigGlyph],"for", sigIR(sigGlyph),
+ xPropName,'@', this.pointer,'+',si.offset,'sz',si.sizeof);
+ }
+ let rc = (
+ new DataView(heap().buffer, Number(this.pointer) + si.offset, si.sizeof)
+ )[f.cache.getters[sigGlyph]](0, isLittleEndian);
+
+ if(getterProxy) rc = getterProxy.apply(this,[key,rc]);
+ if(dbg.getter) log("debug.getter:",xPropName,"result =",rc);
+ return rc;
+ };
+ if(si.readOnly){
+ prop.set = __propThrowOnSet(ctor.prototype.structName,key);
+ }else{
+ const setterProxy = memberSetterProxy(si);
+ prop.set = function(v){
+
+ if(dbg.setter){
+ log("debug.setter:",f.cache.setters[sigGlyph],"for", sigIR(sigGlyph),
+ xPropName,'@', this.pointer,'+',si.offset,'sz',si.sizeof, v);
+ }
+ if(!this.pointer){
+ toss("Cannot set native property on a disposed",
+ this.structName,"instance.");
+ }
+ if( setterProxy ) v = setterProxy.apply(this,[key,v]);
+ if( null===v || undefined===v ) v = __NullPtr;
+ else if( isPtrSig(si.signature) && !__isPtr(v) ){
+ if(isAutoPtrSig(si.signature) && (v instanceof StructType)){
+
+ v = v.pointer || __NullPtr;
+ if(dbg.setter) log("debug.setter:",xPropName,"resolved to",v);
+ }else{
+ toss("Invalid value for pointer-type",xPropName+'.');
+ }
+ }
+ (
+ new DataView(heap().buffer, Number(this.pointer) + si.offset,
+ si.sizeof)
+ )[f.cache.setters[sigGlyph]](0, f.cache.sw[sigGlyph](v), isLittleEndian);
+ };
+ }
+ Object.defineProperty(ctor.prototype, key, prop);
+ };
+
+
+ const StructBinderImpl = function StructBinderImpl(
+ structName, si, opt = Object.create(null)
+ ){
+
+ const StructCtor = function StructCtor(arg){
+
+ if(!(this instanceof StructCtor)){
+ toss("The",structName,"constructor may only be called via 'new'.");
+ }
+ __allocStruct(StructCtor, this, ...arguments);
+ };
+ const self = this;
+
+ const ads = (x)=>{
+
+ return (('string'===typeof x) && looksLikeASig(x))
+ ? {signature: x} : __adaptStruct2(self,x);
+ };
+ if(1===arguments.length){
+ si = ads(structName);
+ structName = si.structName || si.name;
+ }else if(2===arguments.length){
+ si = ads(si);
+ si.name ??= structName;
+ }else{
+ si = ads(si);
+ }
+ structName ??= si.structName;
+
+ structName ??= opt.structName;
+ if( !structName ) toss("One of 'name' or 'structName' are required.");
+ if( si.adapt ){
+
+ Object.keys(si.adapt.struct||{}).forEach((k)=>{
+ __adaptStruct.call(StructBinderImpl, k, si.adapt.struct[k]);
+ });
+ Object.keys(si.adapt.set||{}).forEach((k)=>{
+ __adaptSet.call(StructBinderImpl, k, si.adapt.set[k]);
+ });
+ Object.keys(si.adapt.get||{}).forEach((k)=>{
+ __adaptGet.call(StructBinderImpl, k, si.adapt.get[k]);
+ });
+ }
+ if(!si.members && !si.sizeof){
+ si.sizeof = sigSize(si.signature);
+ }
+
+ const debugFlags = rop(SBF.__makeDebugFlags(StructBinder.debugFlags));
+ Object.defineProperties(StructCtor,{
+ debugFlags: debugFlags,
+ isA: rop((v)=>v instanceof StructCtor),
+ memberKey: __memberKeyProp,
+ memberKeys: __structMemberKeys,
+
+ structInfo: rop(si),
+ structName: rop(structName),
+ ptrAdd: rop(__ptrAdd)
+ });
+ StructCtor.prototype = new StructType(structName, si, rop);
+ Object.defineProperties(StructCtor.prototype,{
+ debugFlags: debugFlags,
+ constructor: rop(StructCtor)
+ ,
+ ptrAdd: rop(__ptrAddSelf)
+ });
+ let lastMember = false;
+ let offset = 0;
+ const autoCalc = !!si.autoCalcSizeOffset;
+
+ if( !autoCalc ){
+ if( !si.sizeof ){
+ toss(structName,"description is missing its sizeof property.");
+ }
+
+ si.offset ??= 0;
+ }else{
+ si.offset ??= 0;
+ }
+ Object.keys(si.members || {}).forEach((k)=>{
+
+ let m = ads(si.members[k]);
+ if(!m.members && !m.sizeof){
+
+ m.sizeof = sigSize(m.signature);
+ if(!m.sizeof){
+ toss(sPropName(structName,k), "is missing a sizeof property.",m);
+ }
+ }
+ if( undefined===m.offset ){
+ if( autoCalc ) m.offset = offset;
+ else{
+ toss(sPropName(structName,k),"is missing its offset.",
+ JSON.stringify(m));
+ }
+
+ }
+ si.members[k] = m ;
+ if(!lastMember || lastMember.offset < m.offset) lastMember = m;
+ const oldAutoCalc = !!m.autoCalc;
+ if( autoCalc ) m.autoCalcSizeOffset = true;
+ makeMemberWrapper.call(self, StructCtor, k, m);
+ if( oldAutoCalc ) m.autoCalcSizeOffset = true;
+ else delete m.autoCalcSizeOffset;
+ offset += m.sizeof;
+
+ });
+
+ if( !lastMember ) toss("No member property descriptions found.");
+ if( !si.sizeof ) si.sizeof = offset;
+ if(si.sizeof===1){
+ (si.signature === 'c' || si.signature === 'C') ||
+ toss("Unexpected sizeof==1 member",
+ sPropName(structName,k),
+ "with signature",si.signature);
+ }else{
+
+
+ if(0!==(si.sizeof%4)){
+ console.warn("Invalid struct member description",si);
+ toss(structName,"sizeof is not aligned. sizeof="+si.sizeof);
+ }
+ if(0!==(si.offset%4)){
+ console.warn("Invalid struct member description",si);
+ toss(structName,"offset is not aligned. offset="+si.offset);
+ }
+ }
+ if( si.sizeof < offset ){
+ console.warn("Suspect struct description:",si,"offset =",offset);
+ toss("Mismatch in the calculated vs. the provided sizeof/offset info.",
+ "Expected sizeof",offset,"but got",si.sizeof,"for",si);
+
+ }
+ delete si.autoCalcSizeOffset;
+ return StructCtor;
+ };
+
+ const StructBinder = function StructBinder(structName, structInfo){
+ return (1==arguments.length)
+ ? StructBinderImpl.call(StructBinder, structName)
+ : StructBinderImpl.call(StructBinder, structName, structInfo);
+ };
+ StructBinder.StructType = StructType;
+ StructBinder.config = config;
+ StructBinder.allocCString = __allocCString;
+ StructBinder.adaptGet = __adaptGet;
+ StructBinder.adaptSet = __adaptSet;
+ StructBinder.adaptStruct = __adaptStruct;
+ StructBinder.ptrAdd = __ptrAdd;
+ if(!StructBinder.debugFlags){
+ StructBinder.debugFlags = SBF.__makeDebugFlags(SBF.debugFlags);
+ }
+ return StructBinder;
+};
+
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+ 'use strict';
+ const toss = (...args)=>{throw new Error(args.join(' '))};
+ const capi = sqlite3.capi, wasm = sqlite3.wasm, util = sqlite3.util;
+ globalThis.WhWasmUtilInstaller(wasm);
+ delete globalThis.WhWasmUtilInstaller;
+
+ if(0){
+
+
+ const dealloc = wasm.exports[sqlite3.config.deallocExportName];
+ const nFunc = wasm.functionTable().length;
+ let i;
+ for(i = 0; i < nFunc; ++i){
+ const e = wasm.functionEntry(i);
+ if(dealloc === e){
+ capi.SQLITE_WASM_DEALLOC = i;
+ break;
+ }
+ }
+ if(dealloc !== wasm.functionEntry(capi.SQLITE_WASM_DEALLOC)){
+ toss("Internal error: cannot find function pointer for SQLITE_WASM_DEALLOC.");
+ }
+ }
+
+
+ const bindingSignatures = {
+ core: [
+
+ ["sqlite3_aggregate_context","void*", "sqlite3_context*", "int"],
+
+
+ ["sqlite3_bind_double","int", "sqlite3_stmt*", "int", "f64"],
+ ["sqlite3_bind_int","int", "sqlite3_stmt*", "int", "int"],
+ ["sqlite3_bind_null",undefined, "sqlite3_stmt*", "int"],
+ ["sqlite3_bind_parameter_count", "int", "sqlite3_stmt*"],
+ ["sqlite3_bind_parameter_index","int", "sqlite3_stmt*", "string"],
+ ["sqlite3_bind_parameter_name", "string", "sqlite3_stmt*", "int"],
+ ["sqlite3_bind_pointer", "int",
+ "sqlite3_stmt*", "int", "*", "string:static", "*"],
+
+ ["sqlite3_bind_zeroblob", "int", "sqlite3_stmt*", "int", "int"],
+ ["sqlite3_busy_handler","int", [
+ "sqlite3*",
+ new wasm.xWrap.FuncPtrAdapter({
+ signature: 'i(pi)',
+ contextKey: (argv,argIndex)=>argv[0]
+ }),
+ "*"
+ ]],
+ ["sqlite3_busy_timeout","int", "sqlite3*", "int"],
+
+
+ ["sqlite3_changes", "int", "sqlite3*"],
+ ["sqlite3_clear_bindings","int", "sqlite3_stmt*"],
+ ["sqlite3_collation_needed", "int", "sqlite3*", "*", "*"],
+ ["sqlite3_column_blob","*", "sqlite3_stmt*", "int"],
+ ["sqlite3_column_bytes","int", "sqlite3_stmt*", "int"],
+ ["sqlite3_column_count", "int", "sqlite3_stmt*"],
+ ["sqlite3_column_decltype", "string", "sqlite3_stmt*", "int"],
+ ["sqlite3_column_double","f64", "sqlite3_stmt*", "int"],
+ ["sqlite3_column_int","int", "sqlite3_stmt*", "int"],
+ ["sqlite3_column_name","string", "sqlite3_stmt*", "int"],
+ ["sqlite3_column_type","int", "sqlite3_stmt*", "int"],
+ ["sqlite3_column_value","sqlite3_value*", "sqlite3_stmt*", "int"],
+ ["sqlite3_commit_hook", "void*", [
+ "sqlite3*",
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'sqlite3_commit_hook',
+ signature: 'i(p)',
+ contextKey: (argv)=>argv[0]
+ }),
+ '*'
+ ]],
+ ["sqlite3_compileoption_get", "string", "int"],
+ ["sqlite3_compileoption_used", "int", "string"],
+ ["sqlite3_complete", "int", "string:flexible"],
+ ["sqlite3_context_db_handle", "sqlite3*", "sqlite3_context*"],
+
+
+ ["sqlite3_data_count", "int", "sqlite3_stmt*"],
+ ["sqlite3_db_filename", "string", "sqlite3*", "string"],
+ ["sqlite3_db_handle", "sqlite3*", "sqlite3_stmt*"],
+ ["sqlite3_db_name", "string", "sqlite3*", "int"],
+ ["sqlite3_db_readonly", "int", "sqlite3*", "string"],
+ ["sqlite3_db_status", "int", "sqlite3*", "int", "*", "*", "int"],
+ ["sqlite3_errcode", "int", "sqlite3*"],
+ ["sqlite3_errmsg", "string", "sqlite3*"],
+ ["sqlite3_error_offset", "int", "sqlite3*"],
+ ["sqlite3_errstr", "string", "int"],
+ ["sqlite3_exec", "int", [
+ "sqlite3*", "string:flexible",
+ new wasm.xWrap.FuncPtrAdapter({
+ signature: 'i(pipp)',
+ bindScope: 'transient',
+ callProxy: (callback)=>{
+ let aNames;
+ return (pVoid, nCols, pColVals, pColNames)=>{
+ try {
+ const aVals = wasm.cArgvToJs(nCols, pColVals);
+ if(!aNames) aNames = wasm.cArgvToJs(nCols, pColNames);
+ return callback(aVals, aNames) | 0;
+ }catch(e){
+
+ return e.resultCode || capi.SQLITE_ERROR;
+ }
+ }
+ }
+ }),
+ "*", "**"
+ ]],
+ ["sqlite3_expanded_sql", "string", "sqlite3_stmt*"],
+ ["sqlite3_extended_errcode", "int", "sqlite3*"],
+ ["sqlite3_extended_result_codes", "int", "sqlite3*", "int"],
+ ["sqlite3_file_control", "int", "sqlite3*", "string", "int", "*"],
+ ["sqlite3_finalize", "int", "sqlite3_stmt*"],
+ ["sqlite3_free", undefined,"*"],
+ ["sqlite3_get_autocommit", "int", "sqlite3*"],
+ ["sqlite3_get_auxdata", "*", "sqlite3_context*", "int"],
+ ["sqlite3_initialize", undefined],
+ ["sqlite3_interrupt", undefined, "sqlite3*"],
+ ["sqlite3_is_interrupted", "int", "sqlite3*"],
+ ["sqlite3_keyword_count", "int"],
+ ["sqlite3_keyword_name", "int", ["int", "**", "*"]],
+ ["sqlite3_keyword_check", "int", ["string", "int"]],
+ ["sqlite3_libversion", "string"],
+ ["sqlite3_libversion_number", "int"],
+ ["sqlite3_limit", "int", ["sqlite3*", "int", "int"]],
+ ["sqlite3_malloc", "*","int"],
+ ["sqlite3_next_stmt", "sqlite3_stmt*", ["sqlite3*","sqlite3_stmt*"]],
+ ["sqlite3_open", "int", "string", "*"],
+ ["sqlite3_open_v2", "int", "string", "*", "int", "string"],
+
+
+ ["sqlite3_realloc", "*","*","int"],
+ ["sqlite3_reset", "int", "sqlite3_stmt*"],
+
+ ["sqlite3_result_blob", undefined, "sqlite3_context*", "*", "int", "*"],
+ ["sqlite3_result_double", undefined, "sqlite3_context*", "f64"],
+ ["sqlite3_result_error", undefined, "sqlite3_context*", "string", "int"],
+ ["sqlite3_result_error_code", undefined, "sqlite3_context*", "int"],
+ ["sqlite3_result_error_nomem", undefined, "sqlite3_context*"],
+ ["sqlite3_result_error_toobig", undefined, "sqlite3_context*"],
+ ["sqlite3_result_int", undefined, "sqlite3_context*", "int"],
+ ["sqlite3_result_null", undefined, "sqlite3_context*"],
+ ["sqlite3_result_pointer", undefined,
+ "sqlite3_context*", "*", "string:static", "*"],
+ ["sqlite3_result_subtype", undefined, "sqlite3_value*", "int"],
+ ["sqlite3_result_text", undefined, "sqlite3_context*", "string", "int", "*"],
+ ["sqlite3_result_zeroblob", undefined, "sqlite3_context*", "int"],
+ ["sqlite3_rollback_hook", "void*", [
+ "sqlite3*",
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'sqlite3_rollback_hook',
+ signature: 'v(p)',
+ contextKey: (argv)=>argv[0]
+ }),
+ '*'
+ ]],
+
+ ["sqlite3_set_auxdata", undefined, [
+ "sqlite3_context*", "int", "*",
+ true
+ ? "*"
+ : new wasm.xWrap.FuncPtrAdapter({
+
+ name: 'xDestroyAuxData',
+ signature: 'v(p)',
+ contextKey: (argv, argIndex)=>argv[0]
+ })
+ ]],
+ ['sqlite3_set_errmsg', 'int', 'sqlite3*', 'int', 'string'],
+ ["sqlite3_shutdown", undefined],
+ ["sqlite3_sourceid", "string"],
+ ["sqlite3_sql", "string", "sqlite3_stmt*"],
+ ["sqlite3_status", "int", "int", "*", "*", "int"],
+ ["sqlite3_step", "int", "sqlite3_stmt*"],
+ ["sqlite3_stmt_busy", "int", "sqlite3_stmt*"],
+ ["sqlite3_stmt_readonly", "int", "sqlite3_stmt*"],
+ ["sqlite3_stmt_status", "int", "sqlite3_stmt*", "int", "int"],
+ ["sqlite3_strglob", "int", "string","string"],
+ ["sqlite3_stricmp", "int", "string", "string"],
+ ["sqlite3_strlike", "int", "string", "string","int"],
+ ["sqlite3_strnicmp", "int", "string", "string", "int"],
+ ["sqlite3_table_column_metadata", "int",
+ "sqlite3*", "string", "string", "string",
+ "**", "**", "*", "*", "*"],
+ ["sqlite3_total_changes", "int", "sqlite3*"],
+ ["sqlite3_trace_v2", "int", [
+ "sqlite3*", "int",
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'sqlite3_trace_v2::callback',
+ signature: 'i(ippp)',
+ contextKey: (argv,argIndex)=>argv[0]
+ }),
+ "*"
+ ]],
+ ["sqlite3_txn_state", "int", ["sqlite3*","string"]],
+
+ ["sqlite3_uri_boolean", "int", "sqlite3_filename", "string", "int"],
+ ["sqlite3_uri_key", "string", "sqlite3_filename", "int"],
+ ["sqlite3_uri_parameter", "string", "sqlite3_filename", "string"],
+ ["sqlite3_user_data","void*", "sqlite3_context*"],
+ ["sqlite3_value_blob", "*", "sqlite3_value*"],
+ ["sqlite3_value_bytes","int", "sqlite3_value*"],
+ ["sqlite3_value_double","f64", "sqlite3_value*"],
+ ["sqlite3_value_dup", "sqlite3_value*", "sqlite3_value*"],
+ ["sqlite3_value_free", undefined, "sqlite3_value*"],
+ ["sqlite3_value_frombind", "int", "sqlite3_value*"],
+ ["sqlite3_value_int","int", "sqlite3_value*"],
+ ["sqlite3_value_nochange", "int", "sqlite3_value*"],
+ ["sqlite3_value_numeric_type", "int", "sqlite3_value*"],
+ ["sqlite3_value_pointer", "*", "sqlite3_value*", "string:static"],
+ ["sqlite3_value_subtype", "int", "sqlite3_value*"],
+ ["sqlite3_value_type", "int", "sqlite3_value*"],
+ ["sqlite3_vfs_find", "*", "string"],
+ ["sqlite3_vfs_register", "int", "sqlite3_vfs*", "int"],
+ ["sqlite3_vfs_unregister", "int", "sqlite3_vfs*"]
+
+
+ ],
+
+ int64: [
+ ["sqlite3_bind_int64","int", ["sqlite3_stmt*", "int", "i64"]],
+ ["sqlite3_changes64","i64", ["sqlite3*"]],
+ ["sqlite3_column_int64","i64", ["sqlite3_stmt*", "int"]],
+ ["sqlite3_deserialize", "int", "sqlite3*", "string", "*", "i64", "i64", "int"]
+ ,
+ ["sqlite3_last_insert_rowid", "i64", ["sqlite3*"]],
+ ["sqlite3_malloc64", "*","i64"],
+ ["sqlite3_msize", "i64", "*"],
+ ["sqlite3_overload_function", "int", ["sqlite3*","string","int"]],
+ ["sqlite3_realloc64", "*","*", "i64"],
+ ["sqlite3_result_int64", undefined, "*", "i64"],
+ ["sqlite3_result_zeroblob64", "int", "*", "i64"],
+ ["sqlite3_serialize","*", "sqlite3*", "string", "*", "int"],
+ ["sqlite3_set_last_insert_rowid", undefined, ["sqlite3*", "i64"]],
+ ["sqlite3_status64", "int", "int", "*", "*", "int"],
+ ["sqlite3_db_status64", "int", "sqlite3*", "int", "*", "*", "int"],
+ ["sqlite3_total_changes64", "i64", ["sqlite3*"]],
+ ["sqlite3_update_hook", "*", [
+ "sqlite3*",
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'sqlite3_update_hook::callback',
+ signature: "v(pippj)",
+ contextKey: (argv)=>argv[0],
+ callProxy: (callback)=>{
+ return (p,op,z0,z1,rowid)=>{
+ callback(p, op, wasm.cstrToJs(z0), wasm.cstrToJs(z1), rowid);
+ };
+ }
+ }),
+ "*"
+ ]],
+ ["sqlite3_uri_int64", "i64", ["sqlite3_filename", "string", "i64"]],
+ ["sqlite3_value_int64","i64", "sqlite3_value*"]
+
+ ],
+
+ wasmInternal: [
+ ["sqlite3__wasm_db_reset", "int", "sqlite3*"],
+ ["sqlite3__wasm_db_vfs", "sqlite3_vfs*", "sqlite3*","string"],
+ [
+ "sqlite3__wasm_vfs_create_file", "int", "sqlite3_vfs*","string","*", "int"
+ ],
+ ["sqlite3__wasm_posix_create_file", "int", "string","*", "int"],
+ ["sqlite3__wasm_vfs_unlink", "int", "sqlite3_vfs*","string"],
+ ["sqlite3__wasm_qfmt_token","string:dealloc", "string","int"]
+ ]
+ } ;
+
+ if( !!wasm.exports.sqlite3_progress_handler ){
+ bindingSignatures.core.push(
+ ["sqlite3_progress_handler", undefined, [
+ "sqlite3*", "int", new wasm.xWrap.FuncPtrAdapter({
+ name: 'xProgressHandler',
+ signature: 'i(p)',
+ bindScope: 'context',
+ contextKey: (argv,argIndex)=>argv[0]
+ }), "*"
+ ]]
+ );
+ }
+
+ if( !!wasm.exports.sqlite3_stmt_explain ){
+ bindingSignatures.core.push(
+ ["sqlite3_stmt_explain", "int", "sqlite3_stmt*", "int"],
+ ["sqlite3_stmt_isexplain", "int", "sqlite3_stmt*"]
+ );
+ }
+
+ if( !!wasm.exports.sqlite3_set_authorizer ){
+ bindingSignatures.core.push(
+ ["sqlite3_set_authorizer", "int", [
+ "sqlite3*",
+ new wasm.xWrap.FuncPtrAdapter({
+ name: "sqlite3_set_authorizer::xAuth",
+ signature: "i(pi"+"ssss)",
+ contextKey: (argv, argIndex)=>argv[0],
+
+ callProxy: (callback)=>{
+ return (pV, iCode, s0, s1, s2, s3)=>{
+ try{
+ s0 = s0 && wasm.cstrToJs(s0); s1 = s1 && wasm.cstrToJs(s1);
+ s2 = s2 && wasm.cstrToJs(s2); s3 = s3 && wasm.cstrToJs(s3);
+ return callback(pV, iCode, s0, s1, s2, s3) | 0;
+ }catch(e){
+ return e.resultCode || capi.SQLITE_ERROR;
+ }
+ }
+ }
+ }),
+ "*"
+ ]]
+ );
+ }
+
+ if( !!wasm.exports.sqlite3_column_origin_name ){
+ bindingSignatures.core.push(
+ ["sqlite3_column_database_name","string", "sqlite3_stmt*", "int"],
+ ["sqlite3_column_origin_name","string", "sqlite3_stmt*", "int"],
+ ["sqlite3_column_table_name","string", "sqlite3_stmt*", "int"]
+ );
+ }
+
+ if(false && wasm.compileOptionUsed('SQLITE_ENABLE_NORMALIZE')){
+
+ bindingSignatures.core.push(["sqlite3_normalized_sql", "string", "sqlite3_stmt*"]);
+ }
+
+
+ if( wasm.bigIntEnabled && !!wasm.exports.sqlite3_declare_vtab ){
+ bindingSignatures.int64.push(
+ ["sqlite3_create_module", "int",
+ ["sqlite3*","string","sqlite3_module*","*"]],
+ ["sqlite3_create_module_v2", "int",
+ ["sqlite3*","string","sqlite3_module*","*","*"]],
+ ["sqlite3_declare_vtab", "int", ["sqlite3*", "string:flexible"]],
+ ["sqlite3_drop_modules", "int", ["sqlite3*", "**"]],
+ ["sqlite3_vtab_collation","string","sqlite3_index_info*","int"],
+
+ ["sqlite3_vtab_distinct","int", "sqlite3_index_info*"],
+ ["sqlite3_vtab_in","int", "sqlite3_index_info*", "int", "int"],
+ ["sqlite3_vtab_in_first", "int", "sqlite3_value*", "**"],
+ ["sqlite3_vtab_in_next", "int", "sqlite3_value*", "**"],
+ ["sqlite3_vtab_nochange","int", "sqlite3_context*"],
+ ["sqlite3_vtab_on_conflict","int", "sqlite3*"],
+ ["sqlite3_vtab_rhs_value","int", "sqlite3_index_info*", "int", "**"]
+ );
+ }
+
+ if(wasm.bigIntEnabled && !!wasm.exports.sqlite3_preupdate_hook){
+ bindingSignatures.int64.push(
+ ["sqlite3_preupdate_blobwrite", "int", "sqlite3*"],
+ ["sqlite3_preupdate_count", "int", "sqlite3*"],
+ ["sqlite3_preupdate_depth", "int", "sqlite3*"],
+ ["sqlite3_preupdate_hook", "*", [
+ "sqlite3*",
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'sqlite3_preupdate_hook',
+ signature: "v(ppippjj)",
+ contextKey: (argv)=>argv[0],
+ callProxy: (callback)=>{
+ return (p,db,op,zDb,zTbl,iKey1,iKey2)=>{
+ callback(p, db, op, wasm.cstrToJs(zDb), wasm.cstrToJs(zTbl),
+ iKey1, iKey2);
+ };
+ }
+ }),
+ "*"
+ ]],
+ ["sqlite3_preupdate_new", "int", ["sqlite3*", "int", "**"]],
+ ["sqlite3_preupdate_old", "int", ["sqlite3*", "int", "**"]]
+ );
+ }
+
+
+ if(wasm.bigIntEnabled
+ && !!wasm.exports.sqlite3changegroup_add
+ && !!wasm.exports.sqlite3session_create
+ && !!wasm.exports.sqlite3_preupdate_hook ){
+
+ const __ipsProxy = {
+ signature: 'i(ps)',
+ callProxy:(callback)=>{
+ return (p,s)=>{
+ try{return callback(p, wasm.cstrToJs(s)) | 0}
+ catch(e){return e.resultCode || capi.SQLITE_ERROR}
+ }
+ }
+ };
+
+ bindingSignatures.int64.push(
+ ['sqlite3changegroup_add', 'int', ['sqlite3_changegroup*', 'int', 'void*']],
+ ['sqlite3changegroup_add_strm', 'int', [
+ 'sqlite3_changegroup*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*'
+ ]],
+ ['sqlite3changegroup_delete', undefined, ['sqlite3_changegroup*']],
+ ['sqlite3changegroup_new', 'int', ['**']],
+ ['sqlite3changegroup_output', 'int', ['sqlite3_changegroup*', 'int*', '**']],
+ ['sqlite3changegroup_output_strm', 'int', [
+ 'sqlite3_changegroup*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xOutput', signature: 'i(ppi)', bindScope: 'transient'
+ }),
+ 'void*'
+ ]],
+ ['sqlite3changeset_apply', 'int', [
+ 'sqlite3*', 'int', 'void*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xFilter', bindScope: 'transient', ...__ipsProxy
+ }),
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xConflict', signature: 'i(pip)', bindScope: 'transient'
+ }),
+ 'void*'
+ ]],
+ ['sqlite3changeset_apply_strm', 'int', [
+ 'sqlite3*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xFilter', bindScope: 'transient', ...__ipsProxy
+ }),
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xConflict', signature: 'i(pip)', bindScope: 'transient'
+ }),
+ 'void*'
+ ]],
+ ['sqlite3changeset_apply_v2', 'int', [
+ 'sqlite3*', 'int', 'void*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xFilter', bindScope: 'transient', ...__ipsProxy
+ }),
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xConflict', signature: 'i(pip)', bindScope: 'transient'
+ }),
+ 'void*', '**', 'int*', 'int'
+
+ ]],
+ ['sqlite3changeset_apply_v2_strm', 'int', [
+ 'sqlite3*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xFilter', bindScope: 'transient', ...__ipsProxy
+ }),
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xConflict', signature: 'i(pip)', bindScope: 'transient'
+ }),
+ 'void*', '**', 'int*', 'int'
+ ]],
+ ['sqlite3changeset_apply_v3', 'int', [
+ 'sqlite3*', 'int', 'void*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xFilter', signature: 'i(pp)', bindScope: 'transient'
+ }),
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xConflict', signature: 'i(pip)', bindScope: 'transient'
+ }),
+ 'void*', '**', 'int*', 'int'
+
+ ]],
+ ['sqlite3changeset_apply_v3_strm', 'int', [
+ 'sqlite3*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xFilter', signature: 'i(pp)', bindScope: 'transient'
+ }),
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xConflict', signature: 'i(pip)', bindScope: 'transient'
+ }),
+ 'void*', '**', 'int*', 'int'
+ ]],
+ ['sqlite3changeset_concat', 'int', ['int','void*', 'int', 'void*', 'int*', '**']],
+ ['sqlite3changeset_concat_strm', 'int', [
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xInputA', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xInputB', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xOutput', signature: 'i(ppi)', bindScope: 'transient'
+ }),
+ 'void*'
+ ]],
+ ['sqlite3changeset_conflict', 'int', ['sqlite3_changeset_iter*', 'int', '**']],
+ ['sqlite3changeset_finalize', 'int', ['sqlite3_changeset_iter*']],
+ ['sqlite3changeset_fk_conflicts', 'int', ['sqlite3_changeset_iter*', 'int*']],
+ ['sqlite3changeset_invert', 'int', ['int', 'void*', 'int*', '**']],
+ ['sqlite3changeset_invert_strm', 'int', [
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xOutput', signature: 'i(ppi)', bindScope: 'transient'
+ }),
+ 'void*'
+ ]],
+ ['sqlite3changeset_new', 'int', ['sqlite3_changeset_iter*', 'int', '**']],
+ ['sqlite3changeset_next', 'int', ['sqlite3_changeset_iter*']],
+ ['sqlite3changeset_old', 'int', ['sqlite3_changeset_iter*', 'int', '**']],
+ ['sqlite3changeset_op', 'int', [
+ 'sqlite3_changeset_iter*', '**', 'int*', 'int*','int*'
+ ]],
+ ['sqlite3changeset_pk', 'int', ['sqlite3_changeset_iter*', '**', 'int*']],
+ ['sqlite3changeset_start', 'int', ['**', 'int', '*']],
+ ['sqlite3changeset_start_strm', 'int', [
+ '**',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*'
+ ]],
+ ['sqlite3changeset_start_v2', 'int', ['**', 'int', '*', 'int']],
+ ['sqlite3changeset_start_v2_strm', 'int', [
+ '**',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*', 'int'
+ ]],
+ ['sqlite3session_attach', 'int', ['sqlite3_session*', 'string']],
+ ['sqlite3session_changeset', 'int', ['sqlite3_session*', 'int*', '**']],
+ ['sqlite3session_changeset_size', 'i64', ['sqlite3_session*']],
+ ['sqlite3session_changeset_strm', 'int', [
+ 'sqlite3_session*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xOutput', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*'
+ ]],
+ ['sqlite3session_config', 'int', ['int', 'void*']],
+ ['sqlite3session_create', 'int', ['sqlite3*', 'string', '**']],
+
+ ['sqlite3session_diff', 'int', ['sqlite3_session*', 'string', 'string', '**']],
+ ['sqlite3session_enable', 'int', ['sqlite3_session*', 'int']],
+ ['sqlite3session_indirect', 'int', ['sqlite3_session*', 'int']],
+ ['sqlite3session_isempty', 'int', ['sqlite3_session*']],
+ ['sqlite3session_memory_used', 'i64', ['sqlite3_session*']],
+ ['sqlite3session_object_config', 'int', ['sqlite3_session*', 'int', 'void*']],
+ ['sqlite3session_patchset', 'int', ['sqlite3_session*', '*', '**']],
+ ['sqlite3session_patchset_strm', 'int', [
+ 'sqlite3_session*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xOutput', signature: 'i(ppp)', bindScope: 'transient'
+ }),
+ 'void*'
+ ]],
+ ['sqlite3session_table_filter', undefined, [
+ 'sqlite3_session*',
+ new wasm.xWrap.FuncPtrAdapter({
+ name: 'xFilter', ...__ipsProxy,
+ contextKey: (argv,argIndex)=>argv[0]
+ }),
+ '*'
+ ]]
+ );
+ }
+
+
+ sqlite3.StructBinder = globalThis.Jaccwabyt({
+ heap: wasm.heap8u,
+ alloc: wasm.alloc,
+ dealloc: wasm.dealloc,
+ bigIntEnabled: wasm.bigIntEnabled,
+ pointerIR: wasm.ptr.ir,
+ memberPrefix: '$'
+ });
+ delete globalThis.Jaccwabyt;
+
+ {
+
+
+ const __xString = wasm.xWrap.argAdapter('string');
+ wasm.xWrap.argAdapter(
+ 'string:flexible', (v)=>__xString(util.flexibleString(v))
+ );
+
+
+ wasm.xWrap.argAdapter(
+ 'string:static',
+ function(v){
+ if(wasm.isPtr(v)) return v;
+ v = ''+v;
+ let rc = this[v];
+ return rc || (this[v] = wasm.allocCString(v));
+ }.bind(Object.create(null))
+ );
+
+
+ const __xArgPtr = wasm.xWrap.argAdapter('*');
+ const nilType = function(){
+
+ };
+ wasm.xWrap.argAdapter('sqlite3_filename', __xArgPtr)
+ ('sqlite3_context*', __xArgPtr)
+ ('sqlite3_value*', __xArgPtr)
+ ('void*', __xArgPtr)
+ ('sqlite3_changegroup*', __xArgPtr)
+ ('sqlite3_changeset_iter*', __xArgPtr)
+ ('sqlite3_session*', __xArgPtr)
+ ('sqlite3_stmt*', (v)=>
+ __xArgPtr((v instanceof (sqlite3?.oo1?.Stmt || nilType))
+ ? v.pointer : v))
+ ('sqlite3*', (v)=>
+ __xArgPtr((v instanceof (sqlite3?.oo1?.DB || nilType))
+ ? v.pointer : v))
+
+ ('sqlite3_vfs*', (v)=>{
+ if('string'===typeof v){
+
+ return capi.sqlite3_vfs_find(v)
+ || sqlite3.SQLite3Error.toss(
+ capi.SQLITE_NOTFOUND,
+ "Unknown sqlite3_vfs name:", v
+ );
+ }
+ return __xArgPtr((v instanceof (capi.sqlite3_vfs || nilType))
+ ? v.pointer : v);
+ });
+ if( wasm.exports.sqlite3_declare_vtab ){
+ wasm.xWrap.argAdapter('sqlite3_index_info*', (v)=>
+ __xArgPtr((v instanceof (capi.sqlite3_index_info || nilType))
+ ? v.pointer : v))
+ ('sqlite3_module*', (v)=>
+ __xArgPtr((v instanceof (capi.sqlite3_module || nilType))
+ ? v.pointer : v)
+ );
+ }
+
+
+ const __xRcPtr = wasm.xWrap.resultAdapter('*');
+ wasm.xWrap.resultAdapter('sqlite3*', __xRcPtr)
+ ('sqlite3_context*', __xRcPtr)
+ ('sqlite3_stmt*', __xRcPtr)
+ ('sqlite3_value*', __xRcPtr)
+ ('sqlite3_vfs*', __xRcPtr)
+ ('void*', __xRcPtr);
+
+
+ for(const e of bindingSignatures.core){
+ capi[e[0]] = wasm.xWrap.apply(null, e);
+ }
+ for(const e of bindingSignatures.wasmInternal){
+ util[e[0]] = wasm.xWrap.apply(null, e);
+ }
+
+
+ for(const e of bindingSignatures.int64){
+ capi[e[0]] = wasm.bigIntEnabled
+ ? wasm.xWrap.apply(null, e)
+ : ()=>toss(e[0]+"() is unavailable due to lack",
+ "of BigInt support in this build.");
+ }
+
+
+ delete bindingSignatures.core;
+ delete bindingSignatures.int64;
+ delete bindingSignatures.wasmInternal;
+
+
+ util.sqlite3__wasm_db_error = function(pDb, resultCode, message){
+ if( !pDb ) return capi.SQLITE_MISUSE;
+ if(resultCode instanceof sqlite3.WasmAllocError){
+ resultCode = capi.SQLITE_NOMEM;
+ message = 0 ;
+ }else if(resultCode instanceof Error){
+ message = message || ''+resultCode;
+ resultCode = (resultCode.resultCode || capi.SQLITE_ERROR);
+ }
+ return capi.sqlite3_set_errmsg(pDb, resultCode, message) || resultCode;
+ };
+ }
+
+ {
+ const cJson = wasm.xCall('sqlite3__wasm_enum_json');
+ if(!cJson){
+ toss("Maintenance required: increase sqlite3__wasm_enum_json()'s",
+ "static buffer size!");
+ }
+ wasm.ctype = JSON.parse(wasm.cstrToJs(cJson));
+
+ const defineGroups = ['access', 'authorizer',
+ 'blobFinalizers', 'changeset',
+ 'config', 'dataTypes',
+ 'dbConfig', 'dbStatus',
+ 'encodings', 'fcntl', 'flock', 'ioCap',
+ 'limits', 'openFlags',
+ 'prepareFlags', 'resultCodes',
+ 'sqlite3Status',
+ 'stmtStatus', 'syncFlags',
+ 'trace', 'txnState', 'udfFlags',
+ 'version'];
+ if(wasm.bigIntEnabled){
+ defineGroups.push('serialize', 'session', 'vtab');
+ }
+ for(const t of defineGroups){
+ for(const e of Object.entries(wasm.ctype[t])){
+
+
+ capi[e[0]] = e[1];
+ }
+ }
+ if(!wasm.functionEntry(capi.SQLITE_WASM_DEALLOC)){
+ toss("Internal error: cannot resolve exported function",
+ "entry SQLITE_WASM_DEALLOC (=="+capi.SQLITE_WASM_DEALLOC+").");
+ }
+ const __rcMap = Object.create(null);
+ for(const e of Object.entries(wasm.ctype['resultCodes'])){
+ __rcMap[e[1]] = e[0];
+ }
+
+ capi.sqlite3_js_rc_str = (rc)=>__rcMap[rc];
+
+
+ const notThese = Object.assign(Object.create(null),{
+
+ WasmTestStruct: true,
+
+ sqlite3_index_info: !wasm.bigIntEnabled,
+ sqlite3_index_constraint: !wasm.bigIntEnabled,
+ sqlite3_index_orderby: !wasm.bigIntEnabled,
+ sqlite3_index_constraint_usage: !wasm.bigIntEnabled
+ });
+ for(const s of wasm.ctype.structs){
+ if(!notThese[s.name]){
+ capi[s.name] = sqlite3.StructBinder(s);
+ }
+ }
+ if(capi.sqlite3_index_info){
+
+ for(const k of ['sqlite3_index_constraint',
+ 'sqlite3_index_orderby',
+ 'sqlite3_index_constraint_usage']){
+ capi.sqlite3_index_info[k] = capi[k];
+ delete capi[k];
+ }
+ capi.sqlite3_vtab_config = wasm.xWrap(
+ 'sqlite3__wasm_vtab_config','int',[
+ 'sqlite3*', 'int', 'int']
+ );
+ }
+ }
+
+
+ const __dbArgcMismatch = (pDb,f,n)=>{
+ return util.sqlite3__wasm_db_error(pDb, capi.SQLITE_MISUSE,
+ f+"() requires "+n+" argument"+
+ (1===n?"":'s')+".");
+ };
+
+
+ const __errEncoding = (pDb)=>{
+ return util.sqlite3__wasm_db_error(
+ pDb, capi.SQLITE_FORMAT, "SQLITE_UTF8 is the only supported encoding."
+ );
+ };
+
+
+ const __argPDb = (pDb)=>wasm.xWrap.argAdapter('sqlite3*')(pDb);
+ const __argStr = (str)=>wasm.isPtr(str) ? wasm.cstrToJs(str) : str;
+ const __dbCleanupMap = function(
+ pDb, mode
+ ){
+ pDb = __argPDb(pDb);
+ let m = this.dbMap.get(pDb);
+ if(!mode){
+ this.dbMap.delete(pDb);
+ return m;
+ }else if(!m && mode>0){
+ this.dbMap.set(pDb, (m = Object.create(null)));
+ }
+ return m;
+ }.bind(Object.assign(Object.create(null),{
+ dbMap: new Map
+ }));
+
+ __dbCleanupMap.addCollation = function(pDb, name){
+ const m = __dbCleanupMap(pDb, 1);
+ if(!m.collation) m.collation = new Set;
+ m.collation.add(__argStr(name).toLowerCase());
+ };
+
+ __dbCleanupMap._addUDF = function(pDb, name, arity, map){
+
+ name = __argStr(name).toLowerCase();
+ let u = map.get(name);
+ if(!u) map.set(name, (u = new Set));
+ u.add((arity<0) ? -1 : arity);
+ };
+
+ __dbCleanupMap.addFunction = function(pDb, name, arity){
+ const m = __dbCleanupMap(pDb, 1);
+ if(!m.udf) m.udf = new Map;
+ this._addUDF(pDb, name, arity, m.udf);
+ };
+
+ if( wasm.exports.sqlite3_create_window_function ){
+ __dbCleanupMap.addWindowFunc = function(pDb, name, arity){
+ const m = __dbCleanupMap(pDb, 1);
+ if(!m.wudf) m.wudf = new Map;
+ this._addUDF(pDb, name, arity, m.wudf);
+ };
+ }
+
+
+ __dbCleanupMap.cleanup = function(pDb){
+ pDb = __argPDb(pDb);
+
+
+ for(const obj of [
+
+ ['sqlite3_busy_handler',3],
+ ['sqlite3_commit_hook',3],
+ ['sqlite3_preupdate_hook',3],
+ ['sqlite3_progress_handler',4],
+ ['sqlite3_rollback_hook',3],
+ ['sqlite3_set_authorizer',3],
+ ['sqlite3_trace_v2', 4],
+ ['sqlite3_update_hook',3]
+
+ ]){
+ const [name, arity] = obj;
+ const x = wasm.exports[name];
+ if( !x ){
+
+ continue;
+ }
+ const closeArgs = [pDb];
+ closeArgs.length = arity
+ ;
+
+ try{ capi[name](...closeArgs) }
+ catch(e){
+
+ sqlite3.config.warn("close-time call of",name+"(",closeArgs,") threw:",e);
+ }
+
+ }
+ const m = __dbCleanupMap(pDb, 0);
+ if(!m) return;
+ if(m.collation){
+ for(const name of m.collation){
+ try{
+ capi.sqlite3_create_collation_v2(
+ pDb, name, capi.SQLITE_UTF8, 0, 0, 0
+ );
+ }catch(e){
+
+ }
+ }
+ delete m.collation;
+ }
+ let i;
+ for(i = 0; i < 2; ++i){
+ const fmap = i ? m.wudf : m.udf;
+ if(!fmap) continue;
+ const func = i
+ ? capi.sqlite3_create_window_function
+ : capi.sqlite3_create_function_v2;
+ for(const e of fmap){
+ const name = e[0], arities = e[1];
+ const fargs = [pDb, name, 0, capi.SQLITE_UTF8, 0, 0, 0, 0, 0];
+ if(i) fargs.push(0);
+ for(const arity of arities){
+ try{ fargs[2] = arity; func.apply(null, fargs); }
+ catch(e){}
+ }
+ arities.clear();
+ }
+ fmap.clear();
+ }
+ delete m.udf;
+ delete m.wudf;
+ };
+
+ {
+ const __sqlite3CloseV2 = wasm.xWrap("sqlite3_close_v2", "int", "sqlite3*");
+ capi.sqlite3_close_v2 = function(pDb){
+ if(1!==arguments.length) return __dbArgcMismatch(pDb, 'sqlite3_close_v2', 1);
+ if(pDb){
+ try{__dbCleanupMap.cleanup(pDb)} catch(e){}
+ }
+ return __sqlite3CloseV2(pDb);
+ };
+ }
+
+ if(capi.sqlite3session_create){
+ const __sqlite3SessionDelete = wasm.xWrap(
+ 'sqlite3session_delete', undefined, ['sqlite3_session*']
+ );
+ capi.sqlite3session_delete = function(pSession){
+ if(1!==arguments.length){
+ return __dbArgcMismatch(pDb, 'sqlite3session_delete', 1);
+
+ }
+ else if(pSession){
+
+ capi.sqlite3session_table_filter(pSession, 0, 0);
+ }
+ __sqlite3SessionDelete(pSession);
+ };
+ }
+
+ {
+
+ const contextKey = (argv,argIndex)=>{
+ return 'argv['+argIndex+']:'+argv[0]+
+ ':'+wasm.cstrToJs(argv[1]).toLowerCase()
+ };
+ const __sqlite3CreateCollationV2 = wasm.xWrap(
+ 'sqlite3_create_collation_v2', 'int', [
+ 'sqlite3*', 'string', 'int', '*',
+ new wasm.xWrap.FuncPtrAdapter({
+
+ name: 'xCompare', signature: 'i(pipip)', contextKey
+ }),
+ new wasm.xWrap.FuncPtrAdapter({
+
+ name: 'xDestroy', signature: 'v(p)', contextKey
+ })
+ ]
+ );
+
+
+ capi.sqlite3_create_collation_v2 = function(pDb,zName,eTextRep,pArg,xCompare,xDestroy){
+ if(6!==arguments.length) return __dbArgcMismatch(pDb, 'sqlite3_create_collation_v2', 6);
+ else if( 0 === (eTextRep & 0xf) ){
+ eTextRep |= capi.SQLITE_UTF8;
+ }else if( capi.SQLITE_UTF8 !== (eTextRep & 0xf) ){
+ return __errEncoding(pDb);
+ }
+ try{
+ const rc = __sqlite3CreateCollationV2(pDb, zName, eTextRep, pArg, xCompare, xDestroy);
+ if(0===rc && xCompare instanceof Function){
+ __dbCleanupMap.addCollation(pDb, zName);
+ }
+ return rc;
+ }catch(e){
+ return util.sqlite3__wasm_db_error(pDb, e);
+ }
+ };
+
+ capi.sqlite3_create_collation = (pDb,zName,eTextRep,pArg,xCompare)=>{
+ return (5===arguments.length)
+ ? capi.sqlite3_create_collation_v2(pDb,zName,eTextRep,pArg,xCompare,0)
+ : __dbArgcMismatch(pDb, 'sqlite3_create_collation', 5);
+ };
+
+ }
+
+ {
+
+ const contextKey = function(argv,argIndex){
+ return (
+ argv[0]
+ +':'+(argv[2] < 0 ? -1 : argv[2])
+ +':'+argIndex
+ +':'+wasm.cstrToJs(argv[1]).toLowerCase()
+ )
+ };
+
+
+ const __cfProxy = Object.assign(Object.create(null), {
+ xInverseAndStep: {
+ signature:'v(pip)', contextKey,
+ callProxy: (callback)=>{
+ return (pCtx, argc, pArgv)=>{
+ try{ callback(pCtx, ...capi.sqlite3_values_to_js(argc, pArgv)) }
+ catch(e){ capi.sqlite3_result_error_js(pCtx, e) }
+ };
+ }
+ },
+ xFinalAndValue: {
+ signature:'v(p)', contextKey,
+ callProxy: (callback)=>{
+ return (pCtx)=>{
+ try{ capi.sqlite3_result_js(pCtx, callback(pCtx)) }
+ catch(e){ capi.sqlite3_result_error_js(pCtx, e) }
+ };
+ }
+ },
+ xFunc: {
+ signature:'v(pip)', contextKey,
+ callProxy: (callback)=>{
+ return (pCtx, argc, pArgv)=>{
+ try{
+ capi.sqlite3_result_js(
+ pCtx,
+ callback(pCtx, ...capi.sqlite3_values_to_js(argc, pArgv))
+ );
+ }catch(e){
+
+ capi.sqlite3_result_error_js(pCtx, e);
+ }
+ };
+ }
+ },
+ xDestroy: {
+ signature:'v(p)', contextKey,
+
+ callProxy: (callback)=>{
+ return (pVoid)=>{
+ try{ callback(pVoid) }
+ catch(e){ console.error("UDF xDestroy method threw:",e) }
+ };
+ }
+ }
+ });
+
+ const __sqlite3CreateFunction = wasm.xWrap(
+ "sqlite3_create_function_v2", "int", [
+ "sqlite3*", "string", "int",
+ "int", "*",
+ new wasm.xWrap.FuncPtrAdapter({name: 'xFunc', ...__cfProxy.xFunc}),
+ new wasm.xWrap.FuncPtrAdapter({name: 'xStep', ...__cfProxy.xInverseAndStep}),
+ new wasm.xWrap.FuncPtrAdapter({name: 'xFinal', ...__cfProxy.xFinalAndValue}),
+ new wasm.xWrap.FuncPtrAdapter({name: 'xDestroy', ...__cfProxy.xDestroy})
+ ]
+ );
+
+ const __sqlite3CreateWindowFunction =
+ wasm.exports.sqlite3_create_window_function
+ ? wasm.xWrap(
+ "sqlite3_create_window_function", "int", [
+ "sqlite3*", "string", "int",
+ "int", "*",
+ new wasm.xWrap.FuncPtrAdapter({name: 'xStep', ...__cfProxy.xInverseAndStep}),
+ new wasm.xWrap.FuncPtrAdapter({name: 'xFinal', ...__cfProxy.xFinalAndValue}),
+ new wasm.xWrap.FuncPtrAdapter({name: 'xValue', ...__cfProxy.xFinalAndValue}),
+ new wasm.xWrap.FuncPtrAdapter({name: 'xInverse', ...__cfProxy.xInverseAndStep}),
+ new wasm.xWrap.FuncPtrAdapter({name: 'xDestroy', ...__cfProxy.xDestroy})
+ ]
+ )
+ : undefined;
+
+
+ capi.sqlite3_create_function_v2 = function f(
+ pDb, funcName, nArg, eTextRep, pApp,
+ xFunc,
+ xStep,
+ xFinal,
+ xDestroy
+ ){
+ if( f.length!==arguments.length ){
+ return __dbArgcMismatch(pDb,"sqlite3_create_function_v2",f.length);
+ }else if( 0 === (eTextRep & 0xf) ){
+ eTextRep |= capi.SQLITE_UTF8;
+ }else if( capi.SQLITE_UTF8 !== (eTextRep & 0xf) ){
+ return __errEncoding(pDb);
+ }
+ try{
+ const rc = __sqlite3CreateFunction(pDb, funcName, nArg, eTextRep,
+ pApp, xFunc, xStep, xFinal, xDestroy);
+ if(0===rc && (xFunc instanceof Function
+ || xStep instanceof Function
+ || xFinal instanceof Function
+ || xDestroy instanceof Function)){
+ __dbCleanupMap.addFunction(pDb, funcName, nArg);
+ }
+ return rc;
+ }catch(e){
+ console.error("sqlite3_create_function_v2() setup threw:",e);
+ return util.sqlite3__wasm_db_error(pDb, e, "Creation of UDF threw: "+e);
+ }
+ };
+
+
+ capi.sqlite3_create_function = function f(
+ pDb, funcName, nArg, eTextRep, pApp,
+ xFunc, xStep, xFinal
+ ){
+ return (f.length===arguments.length)
+ ? capi.sqlite3_create_function_v2(pDb, funcName, nArg, eTextRep,
+ pApp, xFunc, xStep, xFinal, 0)
+ : __dbArgcMismatch(pDb,"sqlite3_create_function",f.length);
+ };
+
+
+ if( __sqlite3CreateWindowFunction ){
+ capi.sqlite3_create_window_function = function f(
+ pDb, funcName, nArg, eTextRep, pApp,
+ xStep,
+ xFinal,
+ xValue,
+ xInverse,
+ xDestroy
+ ){
+ if( f.length!==arguments.length ){
+ return __dbArgcMismatch(pDb,"sqlite3_create_window_function",f.length);
+ }else if( 0 === (eTextRep & 0xf) ){
+ eTextRep |= capi.SQLITE_UTF8;
+ }else if( capi.SQLITE_UTF8 !== (eTextRep & 0xf) ){
+ return __errEncoding(pDb);
+ }
+ try{
+ const rc = __sqlite3CreateWindowFunction(pDb, funcName, nArg, eTextRep,
+ pApp, xStep, xFinal, xValue,
+ xInverse, xDestroy);
+ if(0===rc && (xStep instanceof Function
+ || xFinal instanceof Function
+ || xValue instanceof Function
+ || xInverse instanceof Function
+ || xDestroy instanceof Function)){
+ __dbCleanupMap.addWindowFunc(pDb, funcName, nArg);
+ }
+ return rc;
+ }catch(e){
+ console.error("sqlite3_create_window_function() setup threw:",e);
+ return util.sqlite3__wasm_db_error(pDb, e, "Creation of UDF threw: "+e);
+ }
+ };
+ }else{
+ delete capi.sqlite3_create_window_function;
+ }
+
+ capi.sqlite3_create_function_v2.udfSetResult =
+ capi.sqlite3_create_function.udfSetResult = capi.sqlite3_result_js;
+ if(capi.sqlite3_create_window_function){
+ capi.sqlite3_create_window_function.udfSetResult = capi.sqlite3_result_js;
+ }
+
+
+ capi.sqlite3_create_function_v2.udfConvertArgs =
+ capi.sqlite3_create_function.udfConvertArgs = capi.sqlite3_values_to_js;
+ if(capi.sqlite3_create_window_function){
+ capi.sqlite3_create_window_function.udfConvertArgs = capi.sqlite3_values_to_js;
+ }
+
+
+ capi.sqlite3_create_function_v2.udfSetError =
+ capi.sqlite3_create_function.udfSetError = capi.sqlite3_result_error_js;
+ if(capi.sqlite3_create_window_function){
+ capi.sqlite3_create_window_function.udfSetError = capi.sqlite3_result_error_js;
+ }
+
+ };
+
+ {
+
+
+ const __flexiString = (v,n)=>{
+ if('string'===typeof v){
+ n = -1;
+ }else if(util.isSQLableTypedArray(v)){
+ n = v.byteLength;
+ v = wasm.typedArrayToString(
+ (v instanceof ArrayBuffer) ? new Uint8Array(v) : v
+ );
+ }else if(Array.isArray(v)){
+ v = v.join("");
+ n = -1;
+ }
+ return [v, n];
+ };
+
+
+ const __prepare = {
+
+ basic: wasm.xWrap('sqlite3_prepare_v3',
+ "int", ["sqlite3*", "string",
+ "int",
+ "int", "**",
+ "**"]),
+
+ full: wasm.xWrap('sqlite3_prepare_v3',
+ "int", ["sqlite3*", "*", "int", "int",
+ "**", "**"])
+ };
+
+
+ capi.sqlite3_prepare_v3 = function f(pDb, sql, sqlLen, prepFlags, ppStmt, pzTail){
+ if(f.length!==arguments.length){
+ return __dbArgcMismatch(pDb,"sqlite3_prepare_v3",f.length);
+ }
+ const [xSql, xSqlLen] = __flexiString(sql, Number(sqlLen));
+ switch(typeof xSql){
+ case 'string': return __prepare.basic(pDb, xSql, xSqlLen, prepFlags, ppStmt, null);
+ case (typeof wasm.ptr.null):
+ return __prepare.full(pDb, wasm.ptr.coerce(xSql), xSqlLen, prepFlags,
+ ppStmt, pzTail);
+ default:
+ return util.sqlite3__wasm_db_error(
+ pDb, capi.SQLITE_MISUSE,
+ "Invalid SQL argument type for sqlite3_prepare_v2/v3(). typeof="+(typeof xSql)
+ );
+ }
+ };
+
+
+ capi.sqlite3_prepare_v2 = function f(pDb, sql, sqlLen, ppStmt, pzTail){
+ return (f.length===arguments.length)
+ ? capi.sqlite3_prepare_v3(pDb, sql, sqlLen, 0, ppStmt, pzTail)
+ : __dbArgcMismatch(pDb,"sqlite3_prepare_v2",f.length);
+ };
+
+ }
+
+ {
+ const __bindText = wasm.xWrap("sqlite3_bind_text", "int", [
+ "sqlite3_stmt*", "int", "string", "int", "*"
+ ]);
+ const __bindBlob = wasm.xWrap("sqlite3_bind_blob", "int", [
+ "sqlite3_stmt*", "int", "*", "int", "*"
+ ]);
+
+
+ capi.sqlite3_bind_text = function f(pStmt, iCol, text, nText, xDestroy){
+ if(f.length!==arguments.length){
+ return __dbArgcMismatch(capi.sqlite3_db_handle(pStmt),
+ "sqlite3_bind_text", f.length);
+ }else if(wasm.isPtr(text) || null===text){
+ return __bindText(pStmt, iCol, text, nText, xDestroy);
+ }else if(text instanceof ArrayBuffer){
+ text = new Uint8Array(text);
+ }else if(Array.isArray(pMem)){
+ text = pMem.join('');
+ }
+ let p, n;
+ try{
+ if(util.isSQLableTypedArray(text)){
+ p = wasm.allocFromTypedArray(text);
+ n = text.byteLength;
+ }else if('string'===typeof text){
+ [p, n] = wasm.allocCString(text);
+ }else{
+ return util.sqlite3__wasm_db_error(
+ capi.sqlite3_db_handle(pStmt), capi.SQLITE_MISUSE,
+ "Invalid 3rd argument type for sqlite3_bind_text()."
+ );
+ }
+ return __bindText(pStmt, iCol, p, n, capi.SQLITE_WASM_DEALLOC);
+ }catch(e){
+ wasm.dealloc(p);
+ return util.sqlite3__wasm_db_error(
+ capi.sqlite3_db_handle(pStmt), e
+ );
+ }
+ };
+
+
+ capi.sqlite3_bind_blob = function f(pStmt, iCol, pMem, nMem, xDestroy){
+ if(f.length!==arguments.length){
+ return __dbArgcMismatch(capi.sqlite3_db_handle(pStmt),
+ "sqlite3_bind_blob", f.length);
+ }else if(wasm.isPtr(pMem) || null===pMem){
+ return __bindBlob(pStmt, iCol, pMem, nMem, xDestroy);
+ }else if(pMem instanceof ArrayBuffer){
+ pMem = new Uint8Array(pMem);
+ }else if(Array.isArray(pMem)){
+ pMem = pMem.join('');
+ }
+ let p, n;
+ try{
+ if(util.isBindableTypedArray(pMem)){
+ p = wasm.allocFromTypedArray(pMem);
+ n = nMem>=0 ? nMem : pMem.byteLength;
+ }else if('string'===typeof pMem){
+ [p, n] = wasm.allocCString(pMem);
+ }else{
+ return util.sqlite3__wasm_db_error(
+ capi.sqlite3_db_handle(pStmt), capi.SQLITE_MISUSE,
+ "Invalid 3rd argument type for sqlite3_bind_blob()."
+ );
+ }
+ return __bindBlob(pStmt, iCol, p, n, capi.SQLITE_WASM_DEALLOC);
+ }catch(e){
+ wasm.dealloc(p);
+ return util.sqlite3__wasm_db_error(
+ capi.sqlite3_db_handle(pStmt), e
+ );
+ }
+ };
+
+ }
+
+ if(!capi.sqlite3_column_text){
+
+ const argStmt = wasm.xWrap.argAdapter('sqlite3_stmt*'),
+ argInt = wasm.xWrap.argAdapter('int'),
+ argValue = wasm.xWrap.argAdapter('sqlite3_value*'),
+ newStr =
+ (cstr,n)=>wasm.typedArrayToString(wasm.heap8u(),
+ Number(cstr), Number(cstr)+n)
+ capi.sqlite3_column_text = function(stmt, colIndex){
+ const a0 = argStmt(stmt), a1 = argInt(colIndex);
+ const cstr = wasm.exports.sqlite3_column_text(a0, a1);
+ return cstr
+ ? newStr(cstr,wasm.exports.sqlite3_column_bytes(a0, a1))
+ : null;
+ };
+ capi.sqlite3_value_text = function(val){
+ const a0 = argValue(val);
+ const cstr = wasm.exports.sqlite3_value_text(a0);
+ return cstr
+ ? newStr(cstr,wasm.exports.sqlite3_value_bytes(a0))
+ : null;
+ };
+ }
+
+ {
+
+ capi.sqlite3_config = function(op, ...args){
+ if(arguments.length<2) return capi.SQLITE_MISUSE;
+ switch(op){
+ case capi.SQLITE_CONFIG_COVERING_INDEX_SCAN:
+ case capi.SQLITE_CONFIG_MEMSTATUS:
+ case capi.SQLITE_CONFIG_SMALL_MALLOC:
+ case capi.SQLITE_CONFIG_SORTERREF_SIZE:
+ case capi.SQLITE_CONFIG_STMTJRNL_SPILL:
+ case capi.SQLITE_CONFIG_URI:
+ return wasm.exports.sqlite3__wasm_config_i(op, args[0]);
+ case capi.SQLITE_CONFIG_LOOKASIDE:
+ return wasm.exports.sqlite3__wasm_config_ii(op, args[0], args[1]);
+ case capi.SQLITE_CONFIG_MEMDB_MAXSIZE:
+ return wasm.exports.sqlite3__wasm_config_j(op, args[0]);
+ case capi.SQLITE_CONFIG_GETMALLOC:
+ case capi.SQLITE_CONFIG_GETMUTEX:
+ case capi.SQLITE_CONFIG_GETPCACHE2:
+ case capi.SQLITE_CONFIG_GETPCACHE:
+ case capi.SQLITE_CONFIG_HEAP:
+ case capi.SQLITE_CONFIG_LOG:
+ case capi.SQLITE_CONFIG_MALLOC:
+ case capi.SQLITE_CONFIG_MMAP_SIZE:
+ case capi.SQLITE_CONFIG_MULTITHREAD:
+ case capi.SQLITE_CONFIG_MUTEX:
+ case capi.SQLITE_CONFIG_PAGECACHE:
+ case capi.SQLITE_CONFIG_PCACHE2:
+ case capi.SQLITE_CONFIG_PCACHE:
+ case capi.SQLITE_CONFIG_PCACHE_HDRSZ:
+ case capi.SQLITE_CONFIG_PMASZ:
+ case capi.SQLITE_CONFIG_SERIALIZED:
+ case capi.SQLITE_CONFIG_SINGLETHREAD:
+ case capi.SQLITE_CONFIG_SQLLOG:
+ case capi.SQLITE_CONFIG_WIN32_HEAPSIZE:
+ default:
+
+ return capi.SQLITE_NOTFOUND;
+ }
+ };
+ }
+
+ {
+ const __autoExtFptr = new Set;
+
+ capi.sqlite3_auto_extension = function(fPtr){
+ if( fPtr instanceof Function ){
+ fPtr = wasm.installFunction('i(ppp)', fPtr);
+ }else if( 1!==arguments.length || !wasm.isPtr(fPtr) ){
+ return capi.SQLITE_MISUSE;
+ }
+ const rc = wasm.exports.sqlite3_auto_extension(fPtr);
+ if( fPtr!==arguments[0] ){
+ if(0===rc) __autoExtFptr.add(fPtr);
+ else wasm.uninstallFunction(fPtr);
+ }
+ return rc;
+ };
+
+ capi.sqlite3_cancel_auto_extension = function(fPtr){
+ ;
+ if(!fPtr || 1!==arguments.length || !wasm.isPtr(fPtr)) return 0;
+ return wasm.exports.sqlite3_cancel_auto_extension(fPtr);
+
+ };
+
+ capi.sqlite3_reset_auto_extension = function(){
+ wasm.exports.sqlite3_reset_auto_extension();
+ for(const fp of __autoExtFptr) wasm.uninstallFunction(fp);
+ __autoExtFptr.clear();
+ };
+ }
+
+
+ wasm.xWrap.FuncPtrAdapter.warnOnUse = true;
+
+ const StructBinder = sqlite3.StructBinder
+ ;
+
+ const installMethod = function callee(
+ tgt, name, func, applyArgcCheck = callee.installMethodArgcCheck
+ ){
+ if(!(tgt instanceof StructBinder.StructType)){
+ toss("Usage error: target object is-not-a StructType.");
+ }else if(!(func instanceof Function) && !wasm.isPtr(func)){
+ toss("Usage error: expecting a Function or WASM pointer to one.");
+ }
+ if(1===arguments.length){
+ return (n,f)=>callee(tgt, n, f, applyArgcCheck);
+ }
+ if(!callee.argcProxy){
+ callee.argcProxy = function(tgt, funcName, func,sig){
+ return function(...args){
+ if(func.length!==arguments.length){
+ toss("Argument mismatch for",
+ tgt.structInfo.name+"::"+funcName
+ +": Native signature is:",sig);
+ }
+ return func.apply(this, args);
+ }
+ };
+
+ callee.removeFuncList = function(){
+ if(this.ondispose.__removeFuncList){
+ this.ondispose.__removeFuncList.forEach(
+ (v,ndx)=>{
+ if(wasm.isPtr(v)){
+ try{wasm.uninstallFunction(v)}
+ catch(e){}
+ }
+
+ }
+ );
+ delete this.ondispose.__removeFuncList;
+ }
+ };
+ }
+ const sigN = tgt.memberSignature(name);
+ if(sigN.length<2){
+ toss("Member",name,"does not have a function pointer signature:",sigN);
+ }
+ const memKey = tgt.memberKey(name);
+ const fProxy = (applyArgcCheck && !wasm.isPtr(func))
+
+ ? callee.argcProxy(tgt, memKey, func, sigN)
+ : func;
+ if(wasm.isPtr(fProxy)){
+ if(fProxy && !wasm.functionEntry(fProxy)){
+ toss("Pointer",fProxy,"is not a WASM function table entry.");
+ }
+ tgt[memKey] = fProxy;
+ }else{
+ const pFunc = wasm.installFunction(fProxy, sigN);
+ tgt[memKey] = pFunc;
+ if(!tgt.ondispose || !tgt.ondispose.__removeFuncList){
+ tgt.addOnDispose('ondispose.__removeFuncList handler',
+ callee.removeFuncList);
+ tgt.ondispose.__removeFuncList = [];
+ }
+ tgt.ondispose.__removeFuncList.push(memKey, pFunc);
+ }
+ return (n,f)=>callee(tgt, n, f, applyArgcCheck);
+ };
+ installMethod.installMethodArgcCheck = false;
+
+
+ const installMethods = function(
+ structInstance, methods, applyArgcCheck = installMethod.installMethodArgcCheck
+ ){
+ const seen = new Map ;
+ for(const k of Object.keys(methods)){
+ const m = methods[k];
+ const prior = seen.get(m);
+ if(prior){
+ const mkey = structInstance.memberKey(k);
+ structInstance[mkey] = structInstance[structInstance.memberKey(prior)];
+ }else{
+ installMethod(structInstance, k, m, applyArgcCheck);
+ seen.set(m, k);
+ }
+ }
+ return structInstance;
+ };
+
+
+ StructBinder.StructType.prototype.installMethod = function callee(
+ name, func, applyArgcCheck = installMethod.installMethodArgcCheck
+ ){
+ return (arguments.length < 3 && name && 'object'===typeof name)
+ ? installMethods(this, ...arguments)
+ : installMethod(this, ...arguments);
+ };
+
+
+ StructBinder.StructType.prototype.installMethods = function(
+ methods, applyArgcCheck = installMethod.installMethodArgcCheck
+ ){
+ return installMethods(this, methods, applyArgcCheck);
+ };
+
+});
+
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+ const toss3 = (...args)=>{throw new sqlite3.SQLite3Error(...args)};
+
+ const capi = sqlite3.capi, wasm = sqlite3.wasm, util = sqlite3.util;
+
+
+ const outWrapper = function(f){
+ return (...args)=>f("sqlite3.oo1:",...args);
+ };
+
+ const debug = sqlite3.__isUnderTest
+ ? outWrapper(console.debug.bind(console))
+ : outWrapper(sqlite3.config.debug);
+ const warn = sqlite3.__isUnderTest
+ ? outWrapper(console.warn.bind(console))
+ : outWrapper(sqlite3.config.warn);
+ const error = sqlite3.__isUnderTest
+ ? outWrapper(console.error.bind(console))
+ : outWrapper(sqlite3.config.error);
+
+
+ const __ptrMap = new WeakMap();
+
+ const __doesNotOwnHandle = new Set();
+
+ const __stmtMap = new WeakMap();
+
+
+ const getOwnOption = (opts, p, dflt)=>{
+ const d = Object.getOwnPropertyDescriptor(opts,p);
+ return d ? d.value : dflt;
+ };
+
+
+ const checkSqlite3Rc = function(dbPtr, sqliteResultCode){
+ if(sqliteResultCode){
+ if(dbPtr instanceof DB) dbPtr = dbPtr.pointer;
+ toss3(
+ sqliteResultCode,
+ "sqlite3 result code",sqliteResultCode+":",
+ (dbPtr
+ ? capi.sqlite3_errmsg(dbPtr)
+ : capi.sqlite3_errstr(sqliteResultCode))
+ );
+ }
+ return arguments[0];
+ };
+
+
+ const __dbTraceToConsole =
+ wasm.installFunction('i(ippp)', function(t,c,p,x){
+ if(capi.SQLITE_TRACE_STMT===t){
+
+ console.log("SQL TRACE #"+(++this.counter),
+ 'via sqlite3@'+c+'['+capi.sqlite3_db_filename(c,null)+']',
+ wasm.cstrToJs(x));
+ }
+ }.bind({counter: 0}));
+
+
+ const __vfsPostOpenCallback = Object.create(null);
+
+
+
+ const dbCtorHelper = function ctor(...args){
+ const opt = ctor.normalizeArgs(...args);
+
+ let pDb;
+ if( (pDb = opt['sqlite3*']) ){
+
+
+ if( !opt['sqlite3*:takeOwnership'] ){
+
+ __doesNotOwnHandle.add(this);
+ }
+ this.filename = capi.sqlite3_db_filename(pDb,'main');
+ }else{
+ let fn = opt.filename, vfsName = opt.vfs, flagsStr = opt.flags;
+ if( ('string'!==typeof fn && !wasm.isPtr(fn))
+ || 'string'!==typeof flagsStr
+ || (vfsName && ('string'!==typeof vfsName && !wasm.isPtr(vfsName))) ){
+ sqlite3.config.error("Invalid DB ctor args",opt,arguments);
+ toss3("Invalid arguments for DB constructor:", arguments, "opts:", opt);
+ }
+ let oflags = 0;
+ if( flagsStr.indexOf('c')>=0 ){
+ oflags |= capi.SQLITE_OPEN_CREATE | capi.SQLITE_OPEN_READWRITE;
+ }
+ if( flagsStr.indexOf('w')>=0 ) oflags |= capi.SQLITE_OPEN_READWRITE;
+ if( 0===oflags ) oflags |= capi.SQLITE_OPEN_READONLY;
+ oflags |= capi.SQLITE_OPEN_EXRESCODE;
+ const stack = wasm.pstack.pointer;
+ try {
+ const pPtr = wasm.pstack.allocPtr() ;
+ let rc = capi.sqlite3_open_v2(fn, pPtr, oflags, vfsName || wasm.ptr.null);
+ pDb = wasm.peekPtr(pPtr);
+ checkSqlite3Rc(pDb, rc);
+ capi.sqlite3_extended_result_codes(pDb, 1);
+ if(flagsStr.indexOf('t')>=0){
+ capi.sqlite3_trace_v2(pDb, capi.SQLITE_TRACE_STMT,
+ __dbTraceToConsole, pDb);
+ }
+ }catch( e ){
+ if( pDb ) capi.sqlite3_close_v2(pDb);
+ throw e;
+ }finally{
+ wasm.pstack.restore(stack);
+ }
+ this.filename =
+ wasm.isPtr(fn) ? wasm.cstrToJs(fn) : fn;
+
+ }
+ __ptrMap.set(this, pDb);
+ __stmtMap.set(this, Object.create(null));
+ if( !opt['sqlite3*'] ){
+ try{
+
+ const pVfs = capi.sqlite3_js_db_vfs(pDb)
+ || toss3("Internal error: cannot get VFS for new db handle.");
+ const postInitSql = __vfsPostOpenCallback[pVfs];
+ if(postInitSql){
+
+ if(postInitSql instanceof Function){
+ postInitSql(this, sqlite3);
+ }else{
+ checkSqlite3Rc(
+ pDb, capi.sqlite3_exec(pDb, postInitSql, 0, 0, 0)
+ );
+ }
+ }
+ }catch(e){
+ this.close();
+ throw e;
+ }
+ }
+ };
+
+
+ dbCtorHelper.setVfsPostOpenCallback = function(pVfs, callback){
+ if( !(callback instanceof Function)){
+ toss3("dbCtorHelper.setVfsPostOpenCallback() should not be used with "+
+ "a non-function argument.",arguments);
+ }
+ __vfsPostOpenCallback[pVfs] = callback;
+ };
+
+
+ dbCtorHelper.normalizeArgs = function(filename=':memory:',flags = 'c',vfs = null){
+ const arg = {};
+ if(1===arguments.length && arguments[0] && 'object'===typeof arguments[0]){
+ Object.assign(arg, arguments[0]);
+ if(undefined===arg.flags) arg.flags = 'c';
+ if(undefined===arg.vfs) arg.vfs = null;
+ if(undefined===arg.filename) arg.filename = ':memory:';
+ }else{
+ arg.filename = filename;
+ arg.flags = flags;
+ arg.vfs = vfs;
+ }
+ return arg;
+ };
+
+ const DB = function(...args){
+ dbCtorHelper.apply(this, args);
+ };
+ DB.dbCtorHelper = dbCtorHelper;
+
+
+ const BindTypes = {
+ null: 1,
+ number: 2,
+ string: 3,
+ boolean: 4,
+ blob: 5
+ };
+ if(wasm.bigIntEnabled){
+ BindTypes.bigint = BindTypes.number;
+ }
+
+
+ const Stmt = function(){
+ if(BindTypes!==arguments[2]){
+ toss3(capi.SQLITE_MISUSE, "Do not call the Stmt constructor directly. Use DB.prepare().");
+ }
+ this.db = arguments[0];
+ __ptrMap.set(this, arguments[1]);
+ if( arguments.length>3 && !arguments[3] ){
+ __doesNotOwnHandle.add(this);
+ }
+ };
+
+
+ const affirmDbOpen = function(db){
+ if(!db.pointer) toss3("DB has been closed.");
+ return db;
+ };
+
+
+ const affirmColIndex = function(stmt,ndx){
+ if((ndx !== (ndx|0)) || ndx<0 || ndx>=stmt.columnCount){
+ toss3("Column index",ndx,"is out of range.");
+ }
+ return stmt;
+ };
+
+
+ const parseExecArgs = function(db, args){
+ const out = Object.create(null);
+ out.opt = Object.create(null);
+ switch(args.length){
+ case 1:
+ if('string'===typeof args[0] || util.isSQLableTypedArray(args[0])){
+ out.sql = args[0];
+ }else if(Array.isArray(args[0])){
+ out.sql = args[0];
+ }else if(args[0] && 'object'===typeof args[0]){
+ out.opt = args[0];
+ out.sql = out.opt.sql;
+ }
+ break;
+ case 2:
+ out.sql = args[0];
+ out.opt = args[1];
+ break;
+ default: toss3("Invalid argument count for exec().");
+ };
+ out.sql = util.flexibleString(out.sql);
+ if('string'!==typeof out.sql){
+ toss3("Missing SQL argument or unsupported SQL value type.");
+ }
+ const opt = out.opt;
+ switch(opt.returnValue){
+ case 'resultRows':
+ if(!opt.resultRows) opt.resultRows = [];
+ out.returnVal = ()=>opt.resultRows;
+ break;
+ case 'saveSql':
+ if(!opt.saveSql) opt.saveSql = [];
+ out.returnVal = ()=>opt.saveSql;
+ break;
+ case undefined:
+ case 'this':
+ out.returnVal = ()=>db;
+ break;
+ default:
+ toss3("Invalid returnValue value:",opt.returnValue);
+ }
+ if(!opt.callback && !opt.returnValue && undefined!==opt.rowMode){
+ if(!opt.resultRows) opt.resultRows = [];
+ out.returnVal = ()=>opt.resultRows;
+ }
+ if(opt.callback || opt.resultRows){
+ switch((undefined===opt.rowMode) ? 'array' : opt.rowMode) {
+ case 'object':
+ out.cbArg = (stmt,cache)=>{
+ if( !cache.columnNames ) cache.columnNames = stmt.getColumnNames([]);
+
+ const row = stmt.get([]);
+ const rv = Object.create(null);
+ for( const i in cache.columnNames ) rv[cache.columnNames[i]] = row[i];
+ return rv;
+ };
+ break;
+ case 'array': out.cbArg = (stmt)=>stmt.get([]); break;
+ case 'stmt':
+ if(Array.isArray(opt.resultRows)){
+ toss3("exec(): invalid rowMode for a resultRows array: must",
+ "be one of 'array', 'object',",
+ "a result column number, or column name reference.");
+ }
+ out.cbArg = (stmt)=>stmt;
+ break;
+ default:
+ if(util.isInt32(opt.rowMode)){
+ out.cbArg = (stmt)=>stmt.get(opt.rowMode);
+ break;
+ }else if('string'===typeof opt.rowMode
+ && opt.rowMode.length>1
+ && '$'===opt.rowMode[0]){
+
+ const $colName = opt.rowMode.substr(1);
+ out.cbArg = (stmt)=>{
+ const rc = stmt.get(Object.create(null))[$colName];
+ return (undefined===rc)
+ ? toss3(capi.SQLITE_NOTFOUND,
+ "exec(): unknown result column:",$colName)
+ : rc;
+ };
+ break;
+ }
+ toss3("Invalid rowMode:",opt.rowMode);
+ }
+ }
+ return out;
+ };
+
+
+ const __selectFirstRow = (db, sql, bind, ...getArgs)=>{
+ const stmt = db.prepare(sql);
+ try {
+ const rc = stmt.bind(bind).step() ? stmt.get(...getArgs) : undefined;
+ stmt.reset();
+ return rc;
+ }finally{
+ stmt.finalize();
+ }
+ };
+
+
+ const __selectAll =
+ (db, sql, bind, rowMode)=>db.exec({
+ sql, bind, rowMode, returnValue: 'resultRows'
+ });
+
+
+ DB.checkRc = (db,resultCode)=>checkSqlite3Rc(db,resultCode);
+
+ DB.prototype = {
+
+ isOpen: function(){
+ return !!this.pointer;
+ },
+
+ affirmOpen: function(){
+ return affirmDbOpen(this);
+ },
+
+ close: function(){
+ const pDb = this.pointer;
+ if(pDb){
+ if(this.onclose && (this.onclose.before instanceof Function)){
+ try{this.onclose.before(this)}
+ catch(e){}
+ }
+ Object.keys(__stmtMap.get(this)).forEach((k,s)=>{
+ if(s && s.pointer){
+ try{s.finalize()}
+ catch(e){}
+ }
+ });
+ __ptrMap.delete(this);
+ __stmtMap.delete(this);
+ if( !__doesNotOwnHandle.delete(this) ){
+ capi.sqlite3_close_v2(pDb);
+ }
+ if(this.onclose && (this.onclose.after instanceof Function)){
+ try{this.onclose.after(this)}
+ catch(e){}
+ }
+ delete this.filename;
+ }
+ },
+
+ changes: function(total=false,sixtyFour=false){
+ const p = affirmDbOpen(this).pointer;
+ if(total){
+ return sixtyFour
+ ? capi.sqlite3_total_changes64(p)
+ : capi.sqlite3_total_changes(p);
+ }else{
+ return sixtyFour
+ ? capi.sqlite3_changes64(p)
+ : capi.sqlite3_changes(p);
+ }
+ },
+
+ dbFilename: function(dbName='main'){
+ return capi.sqlite3_db_filename(affirmDbOpen(this).pointer, dbName);
+ },
+
+ dbName: function(dbNumber=0){
+ return capi.sqlite3_db_name(affirmDbOpen(this).pointer, dbNumber);
+ },
+
+ dbVfsName: function(dbName=0){
+ let rc;
+ const pVfs = capi.sqlite3_js_db_vfs(
+ affirmDbOpen(this).pointer, dbName
+ );
+ if(pVfs){
+ const v = new capi.sqlite3_vfs(pVfs);
+ try{ rc = wasm.cstrToJs(v.$zName) }
+ finally { v.dispose() }
+ }
+ return rc;
+ },
+
+ prepare: function(sql){
+ affirmDbOpen(this);
+ const stack = wasm.pstack.pointer;
+ let ppStmt, pStmt;
+ try{
+ ppStmt = wasm.pstack.alloc(8);
+ DB.checkRc(this, capi.sqlite3_prepare_v2(this.pointer, sql, -1, ppStmt, null));
+ pStmt = wasm.peekPtr(ppStmt);
+ }
+ finally {
+ wasm.pstack.restore(stack);
+ }
+ if(!pStmt) toss3("Cannot prepare empty SQL.");
+ const stmt = new Stmt(this, pStmt, BindTypes);
+ __stmtMap.get(this)[pStmt] = stmt;
+ return stmt;
+ },
+
+ exec: function(){
+ affirmDbOpen(this);
+ const arg = parseExecArgs(this, arguments);
+ if(!arg.sql){
+ return toss3("exec() requires an SQL string.");
+ }
+ const opt = arg.opt;
+ const callback = opt.callback;
+ const resultRows =
+ Array.isArray(opt.resultRows) ? opt.resultRows : undefined;
+ let stmt;
+ let bind = opt.bind;
+ let evalFirstResult = !!(
+ arg.cbArg || opt.columnNames || resultRows
+ ) ;
+ const stack = wasm.scopedAllocPush();
+ const saveSql = Array.isArray(opt.saveSql) ? opt.saveSql : undefined;
+ try{
+ const isTA = util.isSQLableTypedArray(arg.sql)
+ ;
+
+ let sqlByteLen = isTA ? arg.sql.byteLength : wasm.jstrlen(arg.sql);
+ const ppStmt = wasm.scopedAlloc(
+
+ (2 * wasm.ptr.size) + (sqlByteLen + 1)
+ );
+ const pzTail = wasm.ptr.add(ppStmt, wasm.ptr.size) ;
+ let pSql = wasm.ptr.add(pzTail, wasm.ptr.size);
+ const pSqlEnd = wasm.ptr.add(pSql, sqlByteLen);
+ if(isTA) wasm.heap8().set(arg.sql, pSql);
+ else wasm.jstrcpy(arg.sql, wasm.heap8(), pSql, sqlByteLen, false);
+ wasm.poke8(wasm.ptr.add(pSql, sqlByteLen), 0);
+ while(pSql && wasm.peek8(pSql)
+ ){
+ wasm.pokePtr([ppStmt, pzTail], 0);
+ DB.checkRc(this, capi.sqlite3_prepare_v3(
+ this.pointer, pSql, sqlByteLen, 0, ppStmt, pzTail
+ ));
+ const pStmt = wasm.peekPtr(ppStmt);
+ pSql = wasm.peekPtr(pzTail);
+ sqlByteLen = Number(wasm.ptr.add(pSqlEnd,-pSql));
+ if(!pStmt) continue;
+
+ if(saveSql) saveSql.push(capi.sqlite3_sql(pStmt).trim());
+ stmt = new Stmt(this, pStmt, BindTypes);
+ if(bind && stmt.parameterCount){
+ stmt.bind(bind);
+ bind = null;
+ }
+ if(evalFirstResult && stmt.columnCount){
+
+ let gotColNames = Array.isArray(
+ opt.columnNames
+ ) ? 0 : 1;
+ evalFirstResult = false;
+ if(arg.cbArg || resultRows){
+ const cbArgCache = Object.create(null)
+ ;
+ for( ; stmt.step(); __execLock.delete(stmt) ){
+ if(0===gotColNames++){
+ stmt.getColumnNames(cbArgCache.columnNames = (opt.columnNames || []));
+ }
+ __execLock.add(stmt);
+ const row = arg.cbArg(stmt,cbArgCache);
+ if(resultRows) resultRows.push(row);
+ if(callback && false === callback.call(opt, row, stmt)){
+ break;
+ }
+ }
+ __execLock.delete(stmt);
+ }
+ if(0===gotColNames){
+
+ stmt.getColumnNames(opt.columnNames);
+ }
+ }else{
+ stmt.step();
+ }
+ stmt.reset(
+ ).finalize();
+ stmt = null;
+ }
+ }finally{
+ if(stmt){
+ __execLock.delete(stmt);
+ stmt.finalize();
+ }
+ wasm.scopedAllocPop(stack);
+ }
+ return arg.returnVal();
+ },
+
+
+
+ createFunction: function f(name, xFunc, opt){
+ const isFunc = (f)=>(f instanceof Function);
+ switch(arguments.length){
+ case 1:
+ opt = name;
+ name = opt.name;
+ xFunc = opt.xFunc || 0;
+ break;
+ case 2:
+ if(!isFunc(xFunc)){
+ opt = xFunc;
+ xFunc = opt.xFunc || 0;
+ }
+ break;
+ case 3:
+ break;
+ default: break;
+ }
+ if(!opt) opt = {};
+ if('string' !== typeof name){
+ toss3("Invalid arguments: missing function name.");
+ }
+ let xStep = opt.xStep || 0;
+ let xFinal = opt.xFinal || 0;
+ const xValue = opt.xValue || 0;
+ const xInverse = opt.xInverse || 0;
+ let isWindow = undefined;
+ if(isFunc(xFunc)){
+ isWindow = false;
+ if(isFunc(xStep) || isFunc(xFinal)){
+ toss3("Ambiguous arguments: scalar or aggregate?");
+ }
+ xStep = xFinal = null;
+ }else if(isFunc(xStep)){
+ if(!isFunc(xFinal)){
+ toss3("Missing xFinal() callback for aggregate or window UDF.");
+ }
+ xFunc = null;
+ }else if(isFunc(xFinal)){
+ toss3("Missing xStep() callback for aggregate or window UDF.");
+ }else{
+ toss3("Missing function-type properties.");
+ }
+ if(false === isWindow){
+ if(isFunc(xValue) || isFunc(xInverse)){
+ toss3("xValue and xInverse are not permitted for non-window UDFs.");
+ }
+ }else if(isFunc(xValue)){
+ if(!isFunc(xInverse)){
+ toss3("xInverse must be provided if xValue is.");
+ }
+ isWindow = true;
+ }else if(isFunc(xInverse)){
+ toss3("xValue must be provided if xInverse is.");
+ }
+ const pApp = opt.pApp;
+ if( undefined!==pApp
+ && null!==pApp
+ && !wasm.isPtr(pApp) ){
+ toss3("Invalid value for pApp property. Must be a legal WASM pointer value.");
+ }
+ const xDestroy = opt.xDestroy || 0;
+ if(xDestroy && !isFunc(xDestroy)){
+ toss3("xDestroy property must be a function.");
+ }
+ let fFlags = 0 ;
+ if(getOwnOption(opt, 'deterministic')) fFlags |= capi.SQLITE_DETERMINISTIC;
+ if(getOwnOption(opt, 'directOnly')) fFlags |= capi.SQLITE_DIRECTONLY;
+ if(getOwnOption(opt, 'innocuous')) fFlags |= capi.SQLITE_INNOCUOUS;
+ name = name.toLowerCase();
+ const xArity = xFunc || xStep;
+ const arity = getOwnOption(opt, 'arity');
+ const arityArg = ('number'===typeof arity
+ ? arity
+ : (xArity.length ? xArity.length-1 : 0));
+ let rc;
+ if( isWindow ){
+ rc = capi.sqlite3_create_window_function(
+ this.pointer, name, arityArg,
+ capi.SQLITE_UTF8 | fFlags, pApp || 0,
+ xStep, xFinal, xValue, xInverse, xDestroy);
+ }else{
+ rc = capi.sqlite3_create_function_v2(
+ this.pointer, name, arityArg,
+ capi.SQLITE_UTF8 | fFlags, pApp || 0,
+ xFunc, xStep, xFinal, xDestroy);
+ }
+ DB.checkRc(this, rc);
+ return this;
+ },
+
+ selectValue: function(sql,bind,asType){
+ return __selectFirstRow(this, sql, bind, 0, asType);
+ },
+
+
+ selectValues: function(sql,bind,asType){
+ const stmt = this.prepare(sql), rc = [];
+ try {
+ stmt.bind(bind);
+ while(stmt.step()) rc.push(stmt.get(0,asType));
+ stmt.reset();
+ }finally{
+ stmt.finalize();
+ }
+ return rc;
+ },
+
+
+ selectArray: function(sql,bind){
+ return __selectFirstRow(this, sql, bind, []);
+ },
+
+
+ selectObject: function(sql,bind){
+ return __selectFirstRow(this, sql, bind, {});
+ },
+
+
+ selectArrays: function(sql,bind){
+ return __selectAll(this, sql, bind, 'array');
+ },
+
+
+ selectObjects: function(sql,bind){
+ return __selectAll(this, sql, bind, 'object');
+ },
+
+
+ openStatementCount: function(){
+ return this.pointer ? Object.keys(__stmtMap.get(this)).length : 0;
+ },
+
+
+ transaction: function(callback){
+ let opener = 'BEGIN';
+ if(arguments.length>1){
+ if(/[^a-zA-Z]/.test(arguments[0])){
+ toss3(capi.SQLITE_MISUSE, "Invalid argument for BEGIN qualifier.");
+ }
+ opener += ' '+arguments[0];
+ callback = arguments[1];
+ }
+ affirmDbOpen(this).exec(opener);
+ try {
+ const rc = callback(this);
+ this.exec("COMMIT");
+ return rc;
+ }catch(e){
+ this.exec("ROLLBACK");
+ throw e;
+ }
+ },
+
+
+ savepoint: function(callback){
+ affirmDbOpen(this).exec("SAVEPOINT oo1");
+ try {
+ const rc = callback(this);
+ this.exec("RELEASE oo1");
+ return rc;
+ }catch(e){
+ this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1");
+ throw e;
+ }
+ },
+
+
+ checkRc: function(resultCode){
+ return checkSqlite3Rc(this, resultCode);
+ },
+ };
+
+
+ DB.wrapHandle = function(pDb, takeOwnership=false){
+ if( !pDb || !wasm.isPtr(pDb) ){
+ throw new sqlite3.SQLite3Error(capi.SQLITE_MISUSE,
+ "Argument must be a WASM sqlite3 pointer");
+ }
+ return new DB({
+
+ "sqlite3*": pDb,
+ "sqlite3*:takeOwnership": !!takeOwnership
+ });
+ };
+
+
+ const affirmStmtOpen = function(stmt){
+ if(!stmt.pointer) toss3("Stmt has been closed.");
+ return stmt;
+ };
+
+
+ const isSupportedBindType = function(v){
+ let t = BindTypes[(null===v||undefined===v) ? 'null' : typeof v];
+ switch(t){
+ case BindTypes.boolean:
+ case BindTypes.null:
+ case BindTypes.number:
+ case BindTypes.string:
+ return t;
+ case BindTypes.bigint:
+ return wasm.bigIntEnabled ? t : undefined;
+ default:
+ return util.isBindableTypedArray(v) ? BindTypes.blob : undefined;
+ }
+ };
+
+
+ const affirmSupportedBindType = function(v){
+
+ return isSupportedBindType(v) || toss3("Unsupported bind() argument type:",typeof v);
+ };
+
+
+ const affirmParamIndex = function(stmt,key){
+ const n = ('number'===typeof key)
+ ? key : capi.sqlite3_bind_parameter_index(stmt.pointer, key);
+ if( 0===n || !util.isInt32(n) ) toss3("Invalid bind() parameter name: "+key);
+ else if( n<1 || n>stmt.parameterCount ) toss3("Bind index",key,"is out of range.");
+ return n;
+ };
+
+
+ const __execLock = new Set();
+
+ const __stmtMayGet = new Set();
+
+
+ const affirmNotLockedByExec = function(stmt,currentOpName){
+ if(__execLock.has(stmt)){
+ toss3("Operation is illegal when statement is locked:",currentOpName);
+ }
+ return stmt;
+ };
+
+
+ const bindOne = function f(stmt,ndx,bindType,val){
+ affirmNotLockedByExec(affirmStmtOpen(stmt), 'bind()');
+ if(!f._){
+ f._tooBigInt = (v)=>toss3(
+ "BigInt value is too big to store without precision loss:", v
+ );
+ f._ = {
+ string: function(stmt, ndx, val, asBlob){
+ const [pStr, n] = wasm.allocCString(val, true);
+ const f = asBlob ? capi.sqlite3_bind_blob : capi.sqlite3_bind_text;
+ return f(stmt.pointer, ndx, pStr, n, capi.SQLITE_WASM_DEALLOC);
+ }
+ };
+ }
+ affirmSupportedBindType(val);
+ ndx = affirmParamIndex(stmt,ndx);
+ let rc = 0;
+ switch((null===val || undefined===val) ? BindTypes.null : bindType){
+ case BindTypes.null:
+ rc = capi.sqlite3_bind_null(stmt.pointer, ndx);
+ break;
+ case BindTypes.string:
+ rc = f._.string(stmt, ndx, val, false);
+ break;
+ case BindTypes.number: {
+ let m;
+ if(util.isInt32(val)) m = capi.sqlite3_bind_int;
+ else if('bigint'===typeof val){
+ if(!util.bigIntFits64(val)){
+ f._tooBigInt(val);
+ }else if(wasm.bigIntEnabled){
+ m = capi.sqlite3_bind_int64;
+ }else if(util.bigIntFitsDouble(val)){
+ val = Number(val);
+ m = capi.sqlite3_bind_double;
+ }else{
+ f._tooBigInt(val);
+ }
+ }else{
+ val = Number(val);
+ if(wasm.bigIntEnabled && Number.isInteger(val)){
+ m = capi.sqlite3_bind_int64;
+ }else{
+ m = capi.sqlite3_bind_double;
+ }
+ }
+ rc = m(stmt.pointer, ndx, val);
+ break;
+ }
+ case BindTypes.boolean:
+ rc = capi.sqlite3_bind_int(stmt.pointer, ndx, val ? 1 : 0);
+ break;
+ case BindTypes.blob: {
+ if('string'===typeof val){
+ rc = f._.string(stmt, ndx, val, true);
+ break;
+ }else if(val instanceof ArrayBuffer){
+ val = new Uint8Array(val);
+ }else if(!util.isBindableTypedArray(val)){
+ toss3("Binding a value as a blob requires",
+ "that it be a string, Uint8Array, Int8Array, or ArrayBuffer.");
+ }
+ const pBlob = wasm.alloc(val.byteLength || 1);
+ wasm.heap8().set(val.byteLength ? val : [0], Number(pBlob))
+ rc = capi.sqlite3_bind_blob(stmt.pointer, ndx, pBlob, val.byteLength,
+ capi.SQLITE_WASM_DEALLOC);
+ break;
+ }
+ default:
+ sqlite3.config.warn("Unsupported bind() argument type:",val);
+ toss3("Unsupported bind() argument type: "+(typeof val));
+ }
+ if(rc) DB.checkRc(stmt.db.pointer, rc);
+ return stmt;
+ };
+
+ Stmt.prototype = {
+
+ finalize: function(){
+ const ptr = this.pointer;
+ if(ptr){
+ affirmNotLockedByExec(this,'finalize()');
+ const rc = (__doesNotOwnHandle.delete(this)
+ ? 0
+ : capi.sqlite3_finalize(ptr));
+ delete __stmtMap.get(this.db)[ptr];
+ __ptrMap.delete(this);
+ __execLock.delete(this);
+ __stmtMayGet.delete(this);
+ delete this.parameterCount;
+ delete this.db;
+ return rc;
+ }
+ },
+
+ clearBindings: function(){
+ affirmNotLockedByExec(affirmStmtOpen(this), 'clearBindings()')
+ capi.sqlite3_clear_bindings(this.pointer);
+ __stmtMayGet.delete(this);
+ return this;
+ },
+
+ reset: function(alsoClearBinds){
+ affirmNotLockedByExec(this,'reset()');
+ if(alsoClearBinds) this.clearBindings();
+ const rc = capi.sqlite3_reset(affirmStmtOpen(this).pointer);
+ __stmtMayGet.delete(this);
+ checkSqlite3Rc(this.db, rc);
+ return this;
+ },
+
+ bind: function(){
+ affirmStmtOpen(this);
+ let ndx, arg;
+ switch(arguments.length){
+ case 1: ndx = 1; arg = arguments[0]; break;
+ case 2: ndx = arguments[0]; arg = arguments[1]; break;
+ default: toss3("Invalid bind() arguments.");
+ }
+ if(undefined===arg){
+
+ return this;
+ }else if(!this.parameterCount){
+ toss3("This statement has no bindable parameters.");
+ }
+ __stmtMayGet.delete(this);
+ if(null===arg){
+
+ return bindOne(this, ndx, BindTypes.null, arg);
+ }
+ else if(Array.isArray(arg)){
+
+ if(1!==arguments.length){
+ toss3("When binding an array, an index argument is not permitted.");
+ }
+ arg.forEach((v,i)=>bindOne(this, i+1, affirmSupportedBindType(v), v));
+ return this;
+ }else if(arg instanceof ArrayBuffer){
+ arg = new Uint8Array(arg);
+ }
+ if('object'===typeof arg
+ && !util.isBindableTypedArray(arg)){
+
+ if(1!==arguments.length){
+ toss3("When binding an object, an index argument is not permitted.");
+ }
+ Object.keys(arg)
+ .forEach(k=>bindOne(this, k,
+ affirmSupportedBindType(arg[k]),
+ arg[k]));
+ return this;
+ }else{
+ return bindOne(this, ndx, affirmSupportedBindType(arg), arg);
+ }
+ toss3("Should not reach this point.");
+ },
+
+ bindAsBlob: function(ndx,arg){
+ affirmStmtOpen(this);
+ if(1===arguments.length){
+ arg = ndx;
+ ndx = 1;
+ }
+ const t = affirmSupportedBindType(arg);
+ if(BindTypes.string !== t && BindTypes.blob !== t
+ && BindTypes.null !== t){
+ toss3("Invalid value type for bindAsBlob()");
+ }
+ return bindOne(this, ndx, BindTypes.blob, arg);
+ },
+
+ step: function(){
+ affirmNotLockedByExec(this, 'step()');
+ const rc = capi.sqlite3_step(affirmStmtOpen(this).pointer);
+ switch(rc){
+ case capi.SQLITE_DONE:
+ __stmtMayGet.delete(this);
+ return false;
+ case capi.SQLITE_ROW:
+ __stmtMayGet.add(this);
+ return true;
+ default:
+ __stmtMayGet.delete(this);
+ sqlite3.config.warn("sqlite3_step() rc=",rc,
+ capi.sqlite3_js_rc_str(rc),
+ "SQL =", capi.sqlite3_sql(this.pointer));
+ DB.checkRc(this.db.pointer, rc);
+ }
+ },
+
+ stepReset: function(){
+ this.step();
+ return this.reset();
+ },
+
+ stepFinalize: function(){
+ try{
+ const rc = this.step();
+ this.reset();
+ return rc;
+ }finally{
+ try{this.finalize()}
+ catch(e){}
+ }
+ },
+
+
+ get: function(ndx,asType){
+ if(!__stmtMayGet.has(affirmStmtOpen(this))){
+ toss3("Stmt.step() has not (recently) returned true.");
+ }
+ if(Array.isArray(ndx)){
+ let i = 0;
+ const n = this.columnCount;
+ while(i<n){
+ ndx[i] = this.get(i++);
+ }
+ return ndx;
+ }else if(ndx && 'object'===typeof ndx){
+ let i = 0;
+ const n = this.columnCount;
+ while(i<n){
+ ndx[capi.sqlite3_column_name(this.pointer,i)] = this.get(i++);
+ }
+ return ndx;
+ }
+ affirmColIndex(this, ndx);
+ switch(undefined===asType
+ ? capi.sqlite3_column_type(this.pointer, ndx)
+ : asType){
+ case capi.SQLITE_NULL: return null;
+ case capi.SQLITE_INTEGER:{
+ if(wasm.bigIntEnabled){
+ const rc = capi.sqlite3_column_int64(this.pointer, ndx);
+ if(rc>=Number.MIN_SAFE_INTEGER && rc<=Number.MAX_SAFE_INTEGER){
+
+ return Number(rc).valueOf();
+ }
+ return rc;
+ }else{
+ const rc = capi.sqlite3_column_double(this.pointer, ndx);
+ if(rc>Number.MAX_SAFE_INTEGER || rc<Number.MIN_SAFE_INTEGER){
+
+ toss3("Integer is out of range for JS integer range: "+rc);
+ }
+
+ return util.isInt32(rc) ? (rc | 0) : rc;
+ }
+ }
+ case capi.SQLITE_FLOAT:
+ return capi.sqlite3_column_double(this.pointer, ndx);
+ case capi.SQLITE_TEXT:
+ return capi.sqlite3_column_text(this.pointer, ndx);
+ case capi.SQLITE_BLOB: {
+ const n = capi.sqlite3_column_bytes(this.pointer, ndx),
+ ptr = capi.sqlite3_column_blob(this.pointer, ndx),
+ rc = new Uint8Array(n);
+ if(n){
+ rc.set(wasm.heap8u().slice(Number(ptr), Number(ptr)+n), 0);
+ if(this.db._blobXfer instanceof Array){
+
+ this.db._blobXfer.push(rc.buffer);
+ }
+ }
+ return rc;
+ }
+ default: toss3("Don't know how to translate",
+ "type of result column #"+ndx+".");
+ }
+ toss3("Not reached.");
+ },
+
+ getInt: function(ndx){return this.get(ndx,capi.SQLITE_INTEGER)},
+
+ getFloat: function(ndx){return this.get(ndx,capi.SQLITE_FLOAT)},
+
+ getString: function(ndx){return this.get(ndx,capi.SQLITE_TEXT)},
+
+ getBlob: function(ndx){return this.get(ndx,capi.SQLITE_BLOB)},
+
+ getJSON: function(ndx){
+ const s = this.get(ndx, capi.SQLITE_STRING);
+ return null===s ? s : JSON.parse(s);
+ },
+
+
+
+
+
+ getColumnName: function(ndx){
+ return capi.sqlite3_column_name(
+ affirmColIndex(affirmStmtOpen(this),ndx).pointer, ndx
+ );
+ },
+
+ getColumnNames: function(tgt=[]){
+ affirmColIndex(affirmStmtOpen(this),0);
+ const n = this.columnCount;
+ for(let i = 0; i < n; ++i){
+ tgt.push(capi.sqlite3_column_name(this.pointer, i));
+ }
+ return tgt;
+ },
+
+ getParamIndex: function(name){
+ return (affirmStmtOpen(this).parameterCount
+ ? capi.sqlite3_bind_parameter_index(this.pointer, name)
+ : undefined);
+ },
+
+ getParamName: function(ndx){
+ return (affirmStmtOpen(this).parameterCount
+ ? capi.sqlite3_bind_parameter_name(this.pointer, ndx)
+ : undefined);
+ },
+
+
+ isBusy: function(){
+ return 0!==capi.sqlite3_stmt_busy(affirmStmtOpen(this));
+ },
+
+
+ isReadOnly: function(){
+ return 0!==capi.sqlite3_stmt_readonly(affirmStmtOpen(this));
+ }
+ };
+
+ {
+ const prop = {
+ enumerable: true,
+ get: function(){return __ptrMap.get(this)},
+ set: ()=>toss3("The pointer property is read-only.")
+ }
+ Object.defineProperty(Stmt.prototype, 'pointer', prop);
+ Object.defineProperty(DB.prototype, 'pointer', prop);
+ }
+
+ Object.defineProperty(Stmt.prototype, 'columnCount', {
+ enumerable: false,
+ get: function(){return capi.sqlite3_column_count(this.pointer)},
+ set: ()=>toss3("The columnCount property is read-only.")
+ });
+
+ Object.defineProperty(Stmt.prototype, 'parameterCount', {
+ enumerable: false,
+ get: function(){return capi.sqlite3_bind_parameter_count(this.pointer)},
+ set: ()=>toss3("The parameterCount property is read-only.")
+ });
+
+
+ Stmt.wrapHandle = function(oo1db, pStmt, takeOwnership=false){
+ let ctor = Stmt;
+ if( !(oo1db instanceof DB) || !oo1db.pointer ){
+ throw new sqlite3.SQLite3Error(sqlite3.SQLITE_MISUSE,
+ "First argument must be an opened "+
+ "sqlite3.oo1.DB instance");
+ }
+ if( !pStmt || !wasm.isPtr(pStmt) ){
+ throw new sqlite3.SQLite3Error(sqlite3.SQLITE_MISUSE,
+ "Second argument must be a WASM "+
+ "sqlite3_stmt pointer");
+ }
+ return new Stmt(oo1db, pStmt, BindTypes, !!takeOwnership);
+ }
+
+
+ sqlite3.oo1 = {
+ DB,
+ Stmt
+ };
+
+});
+
+
+
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+const util = sqlite3.util;
+sqlite3.initWorker1API = function(){
+ 'use strict';
+ const toss = (...args)=>{throw new Error(args.join(' '))};
+ if(!(globalThis.WorkerGlobalScope instanceof Function)){
+ toss("initWorker1API() must be run from a Worker thread.");
+ }
+ const sqlite3 = this.sqlite3 || toss("Missing this.sqlite3 object.");
+ const DB = sqlite3.oo1.DB;
+
+
+ const getDbId = function(db){
+ let id = wState.idMap.get(db);
+ if(id) return id;
+ id = 'db#'+(++wState.idSeq)+':'+
+ Math.floor(Math.random() * 100000000)+':'+
+ Math.floor(Math.random() * 100000000);
+
+ wState.idMap.set(db, id);
+ return id;
+ };
+
+
+ const wState = {
+
+ dbList: [],
+
+ idSeq: 0,
+
+ idMap: new WeakMap,
+
+ xfer: [],
+ open: function(opt){
+ const db = new DB(opt);
+ this.dbs[getDbId(db)] = db;
+ if(this.dbList.indexOf(db)<0) this.dbList.push(db);
+ return db;
+ },
+ close: function(db,alsoUnlink){
+ if(db){
+ delete this.dbs[getDbId(db)];
+ const filename = db.filename;
+ const pVfs = util.sqlite3__wasm_db_vfs(db.pointer, 0);
+ db.close();
+ const ddNdx = this.dbList.indexOf(db);
+ if(ddNdx>=0) this.dbList.splice(ddNdx, 1);
+ if(alsoUnlink && filename && pVfs){
+ util.sqlite3__wasm_vfs_unlink(pVfs, filename);
+ }
+ }
+ },
+
+ post: function(msg,xferList){
+ if(xferList && xferList.length){
+ globalThis.postMessage( msg, Array.from(xferList) );
+ xferList.length = 0;
+ }else{
+ globalThis.postMessage(msg);
+ }
+ },
+
+ dbs: Object.create(null),
+
+ getDb: function(id,require=true){
+ return this.dbs[id]
+ || (require ? toss("Unknown (or closed) DB ID:",id) : undefined);
+ }
+ };
+
+
+ const affirmDbOpen = function(db = wState.dbList[0]){
+ return (db && db.pointer) ? db : toss("DB is not opened.");
+ };
+
+
+ const getMsgDb = function(msgData,affirmExists=true){
+ const db = wState.getDb(msgData.dbId,false) || wState.dbList[0];
+ return affirmExists ? affirmDbOpen(db) : db;
+ };
+
+ const getDefaultDbId = function(){
+ return wState.dbList[0] && getDbId(wState.dbList[0]);
+ };
+
+ const isSpecialDbFilename = (n)=>{
+ return ""===n || ':'===n[0];
+ };
+
+
+ const wMsgHandler = {
+ open: function(ev){
+ const oargs = Object.create(null), args = (ev.args || Object.create(null));
+ if(args.simulateError){
+ toss("Throwing because of simulateError flag.");
+ }
+ const rc = Object.create(null);
+ oargs.vfs = args.vfs;
+ oargs.filename = args.filename || "";
+ const db = wState.open(oargs);
+ rc.filename = db.filename;
+ rc.persistent = !!sqlite3.capi.sqlite3_js_db_uses_vfs(db.pointer, "opfs");
+ rc.dbId = getDbId(db);
+ rc.vfs = db.dbVfsName();
+ return rc;
+ },
+
+ close: function(ev){
+ const db = getMsgDb(ev,false);
+ const response = {
+ filename: db && db.filename
+ };
+ if(db){
+ const doUnlink = ((ev.args && 'object'===typeof ev.args)
+ ? !!ev.args.unlink : false);
+ wState.close(db, doUnlink);
+ }
+ return response;
+ },
+
+ exec: function(ev){
+ const rc = (
+ 'string'===typeof ev.args
+ ) ? {sql: ev.args} : (ev.args || Object.create(null));
+ if('stmt'===rc.rowMode){
+ toss("Invalid rowMode for 'exec': stmt mode",
+ "does not work in the Worker API.");
+ }else if(!rc.sql){
+ toss("'exec' requires input SQL.");
+ }
+ const db = getMsgDb(ev);
+ if(rc.callback || Array.isArray(rc.resultRows)){
+
+ db._blobXfer = wState.xfer;
+ }
+ const theCallback = rc.callback;
+ let rowNumber = 0;
+ const hadColNames = !!rc.columnNames;
+ if('string' === typeof theCallback){
+ if(!hadColNames) rc.columnNames = [];
+
+ rc.callback = function(row,stmt){
+ wState.post({
+ type: theCallback,
+ columnNames: rc.columnNames,
+ rowNumber: ++rowNumber,
+ row: row
+ }, wState.xfer);
+ }
+ }
+ try {
+ const changeCount = !!rc.countChanges
+ ? db.changes(true,(64===rc.countChanges))
+ : undefined;
+ db.exec(rc);
+ if(undefined !== changeCount){
+ rc.changeCount = db.changes(true,64===rc.countChanges) - changeCount;
+ }
+ const lastInsertRowId = !!rc.lastInsertRowId
+ ? sqlite3.capi.sqlite3_last_insert_rowid(db)
+ : undefined;
+ if( undefined!==lastInsertRowId ){
+ rc.lastInsertRowId = lastInsertRowId;
+ }
+ if(rc.callback instanceof Function){
+ rc.callback = theCallback;
+
+ wState.post({
+ type: theCallback,
+ columnNames: rc.columnNames,
+ rowNumber: null ,
+ row: undefined
+ });
+ }
+ }finally{
+ delete db._blobXfer;
+ if(rc.callback) rc.callback = theCallback;
+ }
+ return rc;
+ },
+
+ 'config-get': function(){
+ const rc = Object.create(null), src = sqlite3.config;
+ [
+ 'bigIntEnabled'
+ ].forEach(function(k){
+ if(Object.getOwnPropertyDescriptor(src, k)) rc[k] = src[k];
+ });
+ rc.version = sqlite3.version;
+ rc.vfsList = sqlite3.capi.sqlite3_js_vfs_list();
+ return rc;
+ },
+
+
+ export: function(ev){
+ const db = getMsgDb(ev);
+ const response = {
+ byteArray: sqlite3.capi.sqlite3_js_db_export(db.pointer),
+ filename: db.filename,
+ mimetype: 'application/x-sqlite3'
+ };
+ wState.xfer.push(response.byteArray.buffer);
+ return response;
+ },
+
+ toss: function(ev){
+ toss("Testing worker exception");
+ }
+ };
+
+ globalThis.onmessage = async function(ev){
+ ev = ev.data;
+ let result, dbId = ev.dbId, evType = ev.type;
+ const arrivalTime = performance.now();
+ try {
+ if(wMsgHandler.hasOwnProperty(evType) &&
+ wMsgHandler[evType] instanceof Function){
+ result = await wMsgHandler[evType](ev);
+ }else{
+ toss("Unknown db worker message type:",ev.type);
+ }
+ }catch(err){
+ evType = 'error';
+ result = {
+ operation: ev.type,
+ message: err.message,
+ errorClass: err.name,
+ input: ev
+ };
+ if(err.stack){
+ result.stack = ('string'===typeof err.stack)
+ ? err.stack.split(/\n\s*/) : err.stack;
+ }
+ if(0) sqlite3.config.warn("Worker is propagating an exception to main thread.",
+ "Reporting it _here_ for the stack trace:",err,result);
+ }
+ if(!dbId){
+ dbId = result.dbId
+ || getDefaultDbId();
+ }
+
+
+ wState.post({
+ type: evType,
+ dbId: dbId,
+ messageId: ev.messageId,
+ workerReceivedTime: arrivalTime,
+ workerRespondTime: performance.now(),
+ departureTime: ev.departureTime,
+
+
+
+
+
+
+ result: result
+ }, wState.xfer);
+ };
+ globalThis.postMessage({type:'sqlite3-api',result:'worker1-ready'});
+}.bind({sqlite3});
+});
+
+
+
+'use strict';
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+ const wasm = sqlite3.wasm, capi = sqlite3.capi, toss = sqlite3.util.toss3;
+ const vfs = Object.create(null);
+ sqlite3.vfs = vfs;
+
+
+ capi.sqlite3_vfs.prototype.registerVfs = function(asDefault=false){
+ if(!(this instanceof sqlite3.capi.sqlite3_vfs)){
+ toss("Expecting a sqlite3_vfs-type argument.");
+ }
+ const rc = capi.sqlite3_vfs_register(this, asDefault ? 1 : 0);
+ if(rc){
+ toss("sqlite3_vfs_register(",this,") failed with rc",rc);
+ }
+ if(this.pointer !== capi.sqlite3_vfs_find(this.$zName)){
+ toss("BUG: sqlite3_vfs_find(vfs.$zName) failed for just-installed VFS",
+ this);
+ }
+ return this;
+ };
+
+
+ vfs.installVfs = function(opt){
+ let count = 0;
+ const propList = ['io','vfs'];
+ for(const key of propList){
+ const o = opt[key];
+ if(o){
+ ++count;
+ o.struct.installMethods(o.methods, !!o.applyArgcCheck);
+ if('vfs'===key){
+ if(!o.struct.$zName && 'string'===typeof o.name){
+ o.struct.addOnDispose(
+ o.struct.$zName = wasm.allocCString(o.name)
+ );
+ }
+ o.struct.registerVfs(!!o.asDefault);
+ }
+ }
+ }
+ if(!count) toss("Misuse: installVfs() options object requires at least",
+ "one of:", propList);
+ return this;
+ };
+});
+
+
+
+'use strict';
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+ if( !sqlite3.wasm.exports.sqlite3_declare_vtab ){
+ return;
+ }
+ const wasm = sqlite3.wasm, capi = sqlite3.capi, toss = sqlite3.util.toss3;
+ const vtab = Object.create(null);
+ sqlite3.vtab = vtab;
+
+ const sii = capi.sqlite3_index_info;
+
+ sii.prototype.nthConstraint = function(n, asPtr=false){
+ if(n<0 || n>=this.$nConstraint) return false;
+ const ptr = wasm.ptr.add(
+ this.$aConstraint,
+ sii.sqlite3_index_constraint.structInfo.sizeof * n
+ );
+ return asPtr ? ptr : new sii.sqlite3_index_constraint(ptr);
+ };
+
+
+ sii.prototype.nthConstraintUsage = function(n, asPtr=false){
+ if(n<0 || n>=this.$nConstraint) return false;
+ const ptr = wasm.ptr.add(
+ this.$aConstraintUsage,
+ sii.sqlite3_index_constraint_usage.structInfo.sizeof * n
+ );
+ return asPtr ? ptr : new sii.sqlite3_index_constraint_usage(ptr);
+ };
+
+
+ sii.prototype.nthOrderBy = function(n, asPtr=false){
+ if(n<0 || n>=this.$nOrderBy) return false;
+ const ptr = wasm.ptr.add(
+ this.$aOrderBy,
+ sii.sqlite3_index_orderby.structInfo.sizeof * n
+ );
+ return asPtr ? ptr : new sii.sqlite3_index_orderby(ptr);
+ };
+
+
+ const __xWrapFactory = function(methodName,StructType){
+ return function(ptr,removeMapping=false){
+ if(0===arguments.length) ptr = new StructType;
+ if(ptr instanceof StructType){
+
+ this.set(ptr.pointer, ptr);
+ return ptr;
+ }else if(!wasm.isPtr(ptr)){
+ sqlite3.SQLite3Error.toss("Invalid argument to",methodName+"()");
+ }
+ let rc = this.get(ptr);
+ if(removeMapping) this.delete(ptr);
+ return rc;
+ }.bind(new Map);
+ };
+
+
+ const StructPtrMapper = function(name, StructType){
+ const __xWrap = __xWrapFactory(name,StructType);
+
+ return Object.assign(Object.create(null),{
+
+ StructType,
+
+ create: (ppOut)=>{
+ const rc = __xWrap();
+ wasm.pokePtr(ppOut, rc.pointer);
+ return rc;
+ },
+
+ get: (pCObj)=>__xWrap(pCObj),
+
+ unget: (pCObj)=>__xWrap(pCObj,true),
+
+ dispose: (pCObj)=>__xWrap(pCObj,true)?.dispose?.()
+ });
+ };
+
+
+ vtab.xVtab = StructPtrMapper('xVtab', capi.sqlite3_vtab);
+
+
+ vtab.xCursor = StructPtrMapper('xCursor', capi.sqlite3_vtab_cursor);
+
+
+ vtab.xIndexInfo = (pIdxInfo)=>new capi.sqlite3_index_info(pIdxInfo);
+
+
+ vtab.xError = function f(methodName, err, defaultRc){
+ if(f.errorReporter instanceof Function){
+ try{f.errorReporter("sqlite3_module::"+methodName+"(): "+err.message);}
+ catch(e){}
+ }
+ let rc;
+ if(err instanceof sqlite3.WasmAllocError) rc = capi.SQLITE_NOMEM;
+ else if(arguments.length>2) rc = defaultRc;
+ else if(err instanceof sqlite3.SQLite3Error) rc = err.resultCode;
+ return rc || capi.SQLITE_ERROR;
+ };
+ vtab.xError.errorReporter = 1 ? sqlite3.config.error.bind(sqlite3.config) : false;
+
+
+ vtab.xRowid = (ppRowid64, value)=>wasm.poke(ppRowid64, value, 'i64');
+
+
+ vtab.setupModule = function(opt){
+ let createdMod = false;
+ const mod = (this instanceof capi.sqlite3_module)
+ ? this : (opt.struct || (createdMod = new capi.sqlite3_module()));
+ try{
+ const methods = opt.methods || toss("Missing 'methods' object.");
+ for(const e of Object.entries({
+
+
+ xConnect: 'xCreate', xDisconnect: 'xDestroy'
+ })){
+
+ const k = e[0], v = e[1];
+ if(true === methods[k]) methods[k] = methods[v];
+ else if(true === methods[v]) methods[v] = methods[k];
+ }
+ if(opt.catchExceptions){
+ const fwrap = function(methodName, func){
+ if(['xConnect','xCreate'].indexOf(methodName) >= 0){
+ return function(pDb, pAux, argc, argv, ppVtab, pzErr){
+ try{return func(...arguments) || 0}
+ catch(e){
+ if(!(e instanceof sqlite3.WasmAllocError)){
+ wasm.dealloc(wasm.peekPtr(pzErr));
+ wasm.pokePtr(pzErr, wasm.allocCString(e.message));
+ }
+ return vtab.xError(methodName, e);
+ }
+ };
+ }else{
+ return function(...args){
+ try{return func(...args) || 0}
+ catch(e){
+ return vtab.xError(methodName, e);
+ }
+ };
+ }
+ };
+ const mnames = [
+ 'xCreate', 'xConnect', 'xBestIndex', 'xDisconnect',
+ 'xDestroy', 'xOpen', 'xClose', 'xFilter', 'xNext',
+ 'xEof', 'xColumn', 'xRowid', 'xUpdate',
+ 'xBegin', 'xSync', 'xCommit', 'xRollback',
+ 'xFindFunction', 'xRename', 'xSavepoint', 'xRelease',
+ 'xRollbackTo', 'xShadowName'
+ ];
+ const remethods = Object.create(null);
+ for(const k of mnames){
+ const m = methods[k];
+ if(!(m instanceof Function)) continue;
+ else if('xConnect'===k && methods.xCreate===m){
+ remethods[k] = methods.xCreate;
+ }else if('xCreate'===k && methods.xConnect===m){
+ remethods[k] = methods.xConnect;
+ }else{
+ remethods[k] = fwrap(k, m);
+ }
+ }
+ mod.installMethods(remethods, false);
+ }else{
+
+
+ mod.installMethods(
+ methods, !!opt.applyArgcCheck
+ );
+ }
+ if(0===mod.$iVersion){
+ let v;
+ if('number'===typeof opt.iVersion) v = opt.iVersion;
+ else if(mod.$xIntegrity) v = 4;
+ else if(mod.$xShadowName) v = 3;
+ else if(mod.$xSavePoint || mod.$xRelease || mod.$xRollbackTo) v = 2;
+ else v = 1;
+ mod.$iVersion = v;
+ }
+ }catch(e){
+ if(createdMod) createdMod.dispose();
+ throw e;
+ }
+ return mod;
+ };
+
+
+ capi.sqlite3_module.prototype.setupModule = function(opt){
+ return vtab.setupModule.call(this, opt);
+ };
+});
+
+
+
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+ if( sqlite3.config.disable?.vfs?.kvvfs ){
+ return;
+ }
+ 'use strict';
+ const capi = sqlite3.capi,
+ sqlite3_kvvfs_methods = capi.sqlite3_kvvfs_methods,
+ KVVfsFile = capi.KVVfsFile,
+ pKvvfs = sqlite3.capi.sqlite3_vfs_find("kvvfs")
+
+
+ delete capi.sqlite3_kvvfs_methods;
+ delete capi.KVVfsFile;
+
+ if( !pKvvfs ) return ;
+ if( 0 ){
+
+ capi.sqlite3_vfs_register(pKvvfs, 1);
+ }
+
+ const util = sqlite3.util,
+ wasm = sqlite3.wasm,
+ toss3 = util.toss3,
+ hop = (o,k)=>Object.prototype.hasOwnProperty.call(o,k);
+
+ const kvvfsMethods = new sqlite3_kvvfs_methods(
+
+ wasm.exports.sqlite3__wasm_kvvfs_methods()
+ );
+ util.assert( 32<=kvvfsMethods.$nKeySize, "unexpected kvvfsMethods.$nKeySize: "+kvvfsMethods.$nKeySize);
+
+
+ const cache = Object.assign(Object.create(null),{
+
+ rxJournalSuffix: /-journal$/,
+
+ zKeyJrnl: wasm.allocCString("jrnl"),
+
+ zKeySz: wasm.allocCString("sz"),
+
+ keySize: kvvfsMethods.$nKeySize,
+
+ buffer: Object.assign(Object.create(null),{
+
+ n: kvvfsMethods.$nBufferSize,
+
+ pool: Object.create(null)
+ })
+ });
+
+
+ cache.memBuffer = (id=0)=>cache.buffer.pool[id] ??= wasm.alloc(cache.buffer.n);
+
+
+ cache.memBufferFree = (id)=>{
+ const b = cache.buffer.pool[id];
+ if( b ){
+ wasm.dealloc(b);
+ delete cache.buffer.pool[id];
+ }
+ };
+
+ const noop = ()=>{};
+ const debug = sqlite3.__isUnderTest
+ ? (...args)=>sqlite3.config.debug?.("kvvfs:", ...args)
+ : noop;
+ const warn = (...args)=>sqlite3.config.warn?.("kvvfs:", ...args);
+ const error = (...args)=>sqlite3.config.error?.("kvvfs:", ...args);
+
+
+ class KVVfsStorage {
+ #map = Object.create(null);
+ #keys = null;
+ #size = 0;
+
+ constructor(){
+ this.clear();
+ }
+
+ #getKeys(){
+ return this.#keys ??= Object.keys(this.#map);
+ }
+
+ key(n){
+ if(n < 0 || n >= this.#size) return null;
+ return this.#getKeys()[n];
+ }
+
+ getItem(k){
+ return this.#map[k] ?? null;
+ }
+
+ setItem(k,v){
+ if( !(k in this.#map) ){
+ ++this.#size;
+ this.#keys = null;
+ }
+ this.#map[k] = ''+v;
+ }
+
+ removeItem(k){
+ if( k in this.#map ){
+ delete this.#map[k];
+ --this.#size;
+ this.#keys = null;
+ }
+ }
+
+ clear(){
+ this.#map = Object.create(null);
+ this.#keys = null;
+ this.#size = 0;
+ }
+
+ get length() {
+ return this.#size;
+ }
+ };
+
+
+ const kvvfsIsPersistentName = (v)=>'local'===v || 'session'===v;
+
+
+ const kvvfsKeyPrefix = (v)=>kvvfsIsPersistentName(v) ? 'kvvfs-'+v+'-' : '';
+
+
+ const validateStorageName = function(n,mayBeJournal=false){
+ if( kvvfsIsPersistentName(n) ) return;
+ const len = (new Blob([n])).size;
+ if( !len ) toss3(capi.SQLITE_MISUSE, "Empty name is not permitted.");
+ let maxLen = cache.keySize - 1;
+ if( cache.rxJournalSuffix.test(n) ){
+ if( !mayBeJournal ){
+ toss3(capi.SQLITE_MISUSE,
+ "Storage names may not have a '-journal' suffix.");
+ }
+ }else if( ['-wal','-shm'].filter(v=>n.endsWith(v)).length ){
+ toss3(capi.SQLITE_MISUSE,
+ "Storage names may not have a -wal or -shm suffix.");
+ }else{
+ maxLen -= 8 ;
+ }
+ if( len > maxLen ){
+ toss3(capi.SQLITE_RANGE, "Storage name is too long. Limit =", maxLen);
+ }
+ let i;
+ for( i = 0; i < len; ++i ){
+ const ch = n.codePointAt(i);
+ if( ch<32 ){
+ toss3(capi.SQLITE_RANGE,
+ "Illegal character ("+ch+"d) in storage name:",n);
+ }
+ }
+ };
+
+
+ const newStorageObj = (name,storage=undefined)=>Object.assign(Object.create(null),{
+
+ jzClass: name,
+
+ refc: 1,
+
+ deleteAtRefc0: false,
+
+ storage: storage || new KVVfsStorage,
+
+ keyPrefix: kvvfsKeyPrefix(name),
+
+ files: [],
+
+ listeners: undefined
+ });
+
+
+ const kvvfs = sqlite3.kvvfs = Object.create(null);
+ if( sqlite3.__isUnderTest ){
+
+ kvvfs.log = Object.assign(Object.create(null),{
+ xOpen: false,
+ xClose: false,
+ xWrite: false,
+ xRead: false,
+ xSync: false,
+ xAccess: false,
+ xFileControl: false,
+ xRcrdRead: false,
+ xRcrdWrite: false,
+ xRcrdDelete: false,
+ });
+ }
+
+
+ const deleteStorage = function(store){
+ const other = cache.rxJournalSuffix.test(store.jzClass)
+ ? store.jzClass.replace(cache.rxJournalSuffix,'')
+ : store.jzClass+'-journal';
+ kvvfs?.log?.xClose
+ && debug("cleaning up storage handles [", store.jzClass, other,"]",store);
+ delete cache.storagePool[store.jzClass];
+ delete cache.storagePool[other];
+ if( !sqlite3.__isUnderTest ){
+
+ delete store.storage;
+ delete store.refc;
+ }
+ };
+
+
+ const installStorageAndJournal = (store)=>
+ cache.storagePool[store.jzClass] =
+ cache.storagePool[store.jzClass+'-journal'] = store;
+
+
+ const nameOfThisThreadStorage = '.';
+
+
+ cache.storagePool = Object.assign(Object.create(null),{
+
+ [nameOfThisThreadStorage]: newStorageObj(nameOfThisThreadStorage)
+ });
+
+ if( globalThis.Storage ){
+
+ if( globalThis.localStorage instanceof globalThis.Storage ){
+ cache.storagePool.local = newStorageObj('local', globalThis.localStorage);
+ }
+ if( globalThis.sessionStorage instanceof globalThis.Storage ){
+ cache.storagePool.session = newStorageObj('session', globalThis.sessionStorage);
+ }
+ }
+
+ cache.builtinStorageNames = Object.keys(cache.storagePool);
+
+ const isBuiltinName = (n)=>cache.builtinStorageNames.indexOf(n)>-1;
+
+
+ for(const k of Object.keys(cache.storagePool)){
+
+ const orig = cache.storagePool[k];
+ cache.storagePool[k+'-journal'] = orig;
+ }
+
+ cache.setError = (e=undefined, dfltErrCode=capi.SQLITE_ERROR)=>{
+ if( e ){
+ cache.lastError = e;
+ return (e.resultCode | 0) || dfltErrCode;
+ }
+ delete cache.lastError;
+ return 0;
+ };
+
+ cache.popError = ()=>{
+ const e = cache.lastError;
+ delete cache.lastError;
+ return e;
+ };
+
+
+ const catchForNotify = (e)=>{
+ warn("kvvfs.listener handler threw:",e);
+ };
+
+ const kvvfsDecode = wasm.exports.sqlite3__wasm_kvvfs_decode;
+ const kvvfsEncode = wasm.exports.sqlite3__wasm_kvvfs_encode;
+
+
+ const notifyListeners = async function(eventName,store,...args){
+ try{
+
+ if( store.keyPrefix && args[0] ){
+ args[0] = args[0].replace(store.keyPrefix,'');
+ }
+ let u8enc, z0, z1, wcache;
+ for(const ear of store.listeners){
+ const ev = Object.create(null);
+ ev.storageName = store.jzClass;
+ ev.type = eventName;
+ const decodePages = ear.decodePages;
+ const f = ear.events[eventName];
+ if( f ){
+ if( !ear.includeJournal && args[0]==='jrnl' ){
+ continue;
+ }
+ if( 'write'===eventName && ear.decodePages && +args[0]>0 ){
+
+ ev.data = [args[0]];
+ if( wcache?.[args[0]] ){
+ ev.data[1] = wcache[args[0]];
+ continue;
+ }
+ u8enc ??= new TextEncoder('utf-8');
+ z0 ??= cache.memBuffer(10);
+ z1 ??= cache.memBuffer(11);
+ const u = u8enc.encode(args[1]);
+ const heap = wasm.heap8u();
+ heap.set(u, Number(z0));
+ heap[wasm.ptr.addn(z0, u.length)] = 0;
+ const rc = kvvfsDecode(z0, z1, cache.buffer.n);
+ if( rc>0 ){
+ wcache ??= Object.create(null);
+ wcache[args[0]]
+ = ev.data[1]
+ = heap.slice(Number(z1), wasm.ptr.addn(z1,rc));
+ }else{
+ continue;
+ }
+ }else{
+ ev.data = args.length
+ ? ((args.length===1) ? args[0] : args)
+ : undefined;
+ }
+ try{f(ev)?.catch?.(catchForNotify)}
+ catch(e){
+ warn("notifyListeners [",store.jzClass,"]",eventName,e);
+ }
+ }
+ }
+ }catch(e){
+ catchForNotify(e);
+ }
+ };
+
+
+ const storageForZClass = (zClass)=>
+ 'string'===typeof zClass
+ ? cache.storagePool[zClass]
+ : cache.storagePool[wasm.cstrToJs(zClass)];
+
+
+ const kvvfsMakeKey = wasm.exports.sqlite3__wasm_kvvfsMakeKey;
+
+ const zKeyForStorage = (store, zClass, zKey)=>{
+
+ return (zClass && store.keyPrefix) ? kvvfsMakeKey(zClass, zKey) : zKey;
+ };
+
+ const jsKeyForStorage = (store,zClass,zKey)=>
+ wasm.cstrToJs(zKeyForStorage(store, zClass, zKey));
+
+ const storageGetDbSize = (store)=>+store.storage.getItem(store.keyPrefix + "sz");
+
+
+ const pFileHandles = new Map();
+
+
+ const originalMethods = {
+ vfs: Object.create(null),
+ ioDb: Object.create(null),
+ ioJrnl: Object.create(null)
+ };
+
+
+ const originalIoMethods = (kvvfsFile)=>
+ originalMethods[kvvfsFile.$isJournal ? 'ioJrnl' : 'ioDb'];
+
+ const pVfs = new capi.sqlite3_vfs(kvvfsMethods.$pVfs);
+ const pIoDb = new capi.sqlite3_io_methods(kvvfsMethods.$pIoDb);
+ const pIoJrnl = new capi.sqlite3_io_methods(kvvfsMethods.$pIoJrnl);
+ const recordHandler =
+ Object.create(null);
+ const kvvfsInternal = Object.assign(Object.create(null),{
+ pFileHandles,
+ cache,
+ storageForZClass,
+ KVVfsStorage,
+
+ disablePageSizeChange: true
+ });
+ if( kvvfs.log ){
+
+ kvvfs.internal = kvvfsInternal;
+ }
+
+
+ const methodOverrides = {
+
+
+ recordHandler: {
+ xRcrdRead: (zClass, zKey, zBuf, nBuf)=>{
+ try{
+ const jzClass = wasm.cstrToJs(zClass);
+ const store = storageForZClass(jzClass);
+ if( !store ) return -1;
+ const jXKey = jsKeyForStorage(store, zClass, zKey);
+ kvvfs?.log?.xRcrdRead && warn("xRcrdRead", jzClass, jXKey, nBuf, store );
+ const jV = store.storage.getItem(jXKey);
+ if(null===jV) return -1;
+ const nV = jV.length ;
+ if( 0 ){
+ debug("xRcrdRead", jXKey, store, jV);
+ }
+ if(nBuf<=0) return nV;
+ else if(1===nBuf){
+ wasm.poke(zBuf, 0);
+ return nV;
+ }
+ if( nBuf+1<nV ){
+ toss3(capi.SQLITE_RANGE,
+ "xRcrdRead()",jzClass,jXKey,
+ "input buffer is too small: need",
+ nV,"but have",nBuf);
+ }
+ if( 0 ){
+ debug("xRcrdRead", nBuf, zClass, wasm.cstrToJs(zClass),
+ wasm.cstrToJs(zKey), nV, jV, store);
+ }
+ const zV = cache.memBuffer(0);
+
+ const heap = wasm.heap8();
+ let i;
+ for(i = 0; i < nV; ++i){
+ heap[wasm.ptr.add(zV,i)] = jV.codePointAt(i) & 0xFF;
+ }
+ heap.copyWithin(
+ Number(zBuf), Number(zV), wasm.ptr.addn(zV, i)
+ );
+ heap[wasm.ptr.add(zBuf, nV)] = 0;
+ return nBuf;
+ }catch(e){
+ error("kvrecordRead()",e);
+ cache.setError(e);
+ return -2;
+ }
+ },
+
+ xRcrdWrite: (zClass, zKey, zData)=>{
+ try {
+ const store = storageForZClass(zClass);
+ const jxKey = jsKeyForStorage(store, zClass, zKey);
+ const jData = wasm.cstrToJs(zData);
+ kvvfs?.log?.xRcrdWrite && warn("xRcrdWrite",jxKey, store);
+ store.storage.setItem(jxKey, jData);
+ store.listeners && notifyListeners('write', store, jxKey, jData);
+ return 0;
+ }catch(e){
+ error("kvrecordWrite()",e);
+ return cache.setError(e, capi.SQLITE_IOERR);
+ }
+ },
+
+ xRcrdDelete: (zClass, zKey)=>{
+ try {
+ const store = storageForZClass(zClass);
+ const jxKey = jsKeyForStorage(store, zClass, zKey);
+ kvvfs?.log?.xRcrdDelete && warn("xRcrdDelete",jxKey, store);
+ store.storage.removeItem(jxKey);
+ store.listeners && notifyListeners('delete', store, jxKey);
+ return 0;
+ }catch(e){
+ error("kvrecordDelete()",e);
+ return cache.setError(e, capi.SQLITE_IOERR);
+ }
+ }
+ },
+
+
+ vfs:{
+
+ xOpen: function(pProtoVfs,zName,pProtoFile,flags,pOutFlags){
+ cache.popError();
+ let zToFree ;
+ try{
+ if( !zName ){
+ zToFree = wasm.allocCString(""+pProtoFile+"."
+ +(Math.random() * 100000 | 0));
+ zName = zToFree;
+ }
+ const jzClass = wasm.cstrToJs(zName);
+ kvvfs?.log?.xOpen && debug("xOpen",jzClass,"flags =",flags);
+ validateStorageName(jzClass, true);
+ if( (flags & (capi.SQLITE_OPEN_MAIN_DB
+ | capi.SQLITE_OPEN_TEMP_DB
+ | capi.SQLITE_OPEN_TRANSIENT_DB))
+ && cache.rxJournalSuffix.test(jzClass) ){
+ toss3(capi.SQLITE_ERROR,
+ "DB files may not have a '-journal' suffix.");
+ }
+ let s = storageForZClass(jzClass);
+ if( !s && !(flags & capi.SQLITE_OPEN_CREATE) ){
+ toss3(capi.SQLITE_ERROR, "Storage not found:", jzClass);
+ }
+ const rc = originalMethods.vfs.xOpen(pProtoVfs, zName, pProtoFile,
+ flags, pOutFlags);
+ if( rc ) return rc;
+ let deleteAt0 = !!(capi.SQLITE_OPEN_DELETEONCLOSE & flags);
+ if(wasm.isPtr(arguments[1])){
+ if(capi.sqlite3_uri_boolean(zName, "delete-on-close", 0)){
+ deleteAt0 = true;
+ }
+ }
+ const f = new KVVfsFile(pProtoFile);
+ util.assert(f.$zClass, "Missing f.$zClass");
+ f.addOnDispose(zToFree);
+ zToFree = undefined;
+
+ if( s ){
+ ++s.refc;
+
+ s.files.push(f);
+ wasm.poke32(pOutFlags, flags);
+ }else{
+ wasm.poke32(pOutFlags, flags | capi.SQLITE_OPEN_CREATE);
+ util.assert( !f.$isJournal, "Opening a journal before its db? "+jzClass );
+
+ const nm = jzClass.replace(cache.rxJournalSuffix,'');
+ s = newStorageObj(nm);
+ installStorageAndJournal(s);
+ s.files.push(f);
+ s.deleteAtRefc0 = deleteAt0;
+ kvvfs?.log?.xOpen
+ && debug("xOpen installed storage handle [",nm, nm+"-journal","]", s);
+ }
+ pFileHandles.set(pProtoFile, {store: s, file: f, jzClass});
+ s.listeners && notifyListeners('open', s, s.files.length);
+ return 0;
+ }catch(e){
+ warn("xOpen:",e);
+ return cache.setError(e);
+ }finally{
+ zToFree && wasm.dealloc(zToFree);
+ }
+ },
+
+ xDelete: function(pVfs, zName, iSyncFlag){
+ cache.popError();
+ try{
+ const jzName = wasm.cstrToJs(zName);
+ if( cache.rxJournalSuffix.test(jzName) ){
+ recordHandler.xRcrdDelete(zName, cache.zKeyJrnl);
+ }
+ return 0;
+ }catch(e){
+ warn("xDelete",e);
+ return cache.setError(e);
+ }
+ },
+
+ xAccess: function(pProtoVfs, zPath, flags, pResOut){
+ cache.popError();
+ try{
+ const s = storageForZClass(zPath);
+ const jzPath = s?.jzClass || wasm.cstrToJs(zPath);
+ if( kvvfs?.log?.xAccess ){
+ debug("xAccess",jzPath,"flags =",
+ flags,"*pResOut =",wasm.peek32(pResOut),
+ "store =",s);
+ }
+ if( !s ){
+
+
+
+ try{validateStorageName(jzPath)}
+ catch(e){
+
+ wasm.poke32(pResOut, 0);
+ return 0;
+ }
+ }
+ if( s ){
+ const key = s.keyPrefix+
+ (cache.rxJournalSuffix.test(jzPath) ? "jrnl" : "1");
+ const res = s.storage.getItem(key) ? 0 : 1;
+
+
+ wasm.poke32(pResOut, res);
+ }else{
+ wasm.poke32(pResOut, 0);
+ }
+ return 0;
+ }catch(e){
+ error('xAccess',e);
+ return cache.setError(e);
+ }
+ },
+
+ xRandomness: function(pVfs, nOut, pOut){
+ const heap = wasm.heap8u();
+ let i = 0;
+ const npOut = Number(pOut);
+ for(; i < nOut; ++i) heap[npOut + i] = (Math.random()*255000) & 0xFF;
+ return nOut;
+ },
+
+ xGetLastError: function(pVfs,nOut,pOut){
+ const e = cache.popError();
+ debug('xGetLastError',e);
+ if(e){
+ const scope = wasm.scopedAllocPush();
+ try{
+ const [cMsg, n] = wasm.scopedAllocCString(e.message, true);
+ wasm.cstrncpy(pOut, cMsg, nOut);
+ if(n > nOut) wasm.poke8(wasm.ptr.add(pOut,nOut,-1), 0);
+ debug("set xGetLastError",e.message);
+ return (e.resultCode | 0) || capi.SQLITE_IOERR;
+ }catch(e){
+ return capi.SQLITE_NOMEM;
+ }finally{
+ wasm.scopedAllocPop(scope);
+ }
+ }
+ return 0;
+ }
+
+ },
+
+
+ ioDb:{
+
+ xClose: function(pFile){
+ cache.popError();
+ try{
+ const h = pFileHandles.get(pFile);
+ kvvfs?.log?.xClose && debug("xClose", pFile, h);
+ if( h ){
+ pFileHandles.delete(pFile);
+ const s = h.store;
+ s.files = s.files.filter((v)=>v!==h.file);
+ if( --s.refc<=0 && s.deleteAtRefc0 ){
+ deleteStorage(s);
+ }
+ originalMethods.ioDb.xClose(pFile);
+ h.file.dispose();
+ s.listeners && notifyListeners('close', s, s.files.length);
+ }else{
+
+ }
+ return 0;
+ }catch(e){
+ error("xClose",e);
+ return cache.setError(e);
+ }
+ },
+
+ xFileControl: function(pFile, opId, pArg){
+ cache.popError();
+ try{
+ const h = pFileHandles.get(pFile);
+ util.assert(h, "Missing KVVfsFile handle");
+ kvvfs?.log?.xFileControl && debug("xFileControl",h,'op =',opId);
+ if( opId===capi.SQLITE_FCNTL_PRAGMA
+ && kvvfsInternal.disablePageSizeChange ){
+
+
+ const zName = wasm.peekPtr(wasm.ptr.add(pArg, wasm.ptr.size));
+ if( "page_size"===wasm.cstrToJs(zName) ){
+ kvvfs?.log?.xFileControl
+ && debug("xFileControl pragma",wasm.cstrToJs(zName));
+ const zVal = wasm.peekPtr(wasm.ptr.add(pArg, 2*wasm.ptr.size));
+ if( zVal ){
+
+ kvvfs?.log?.xFileControl
+ && warn("xFileControl pragma", h,
+ "NOT setting page size to", wasm.cstrToJs(zVal));
+ h.file.$szPage = -1;
+ return 0;
+ }else if( h.file.$szPage>0 ){
+ kvvfs?.log?.xFileControl &&
+ warn("xFileControl", h, "getting page size",h.file.$szPage);
+ wasm.pokePtr(pArg, wasm.allocCString(""+h.file.$szPage)
+ );
+ return 0;
+ }
+ }
+ }
+ const rc = originalMethods.ioDb.xFileControl(pFile, opId, pArg);
+ if( 0==rc && capi.SQLITE_FCNTL_SYNC===opId ){
+ h.store.listeners && notifyListeners('sync', h.store, false);
+ }
+ return rc;
+ }catch(e){
+ error("xFileControl",e);
+ return cache.setError(e);
+ }
+ },
+
+ xSync: function(pFile,flags){
+ cache.popError();
+ try{
+ const h = pFileHandles.get(pFile);
+ kvvfs?.log?.xSync && debug("xSync", h);
+ util.assert(h, "Missing KVVfsFile handle");
+ const rc = originalMethods.ioDb.xSync(pFile, flags);
+ if( 0==rc && h.store.listeners ) notifyListeners('sync', h.store, true);
+ return rc;
+ }catch(e){
+ error("xSync",e);
+ return cache.setError(e);
+ }
+ },
+
+
+ },
+
+ ioJrnl:{
+
+ xClose: true,
+ }
+ };
+
+
+ try {
+ util.assert( cache.buffer.n>1024*129, "Heap buffer is not large enough"
+ );
+ for(const e of Object.entries(methodOverrides.recordHandler)){
+
+ const k = e[0], f = e[1];
+ recordHandler[k] = f;
+ if( 0 ){
+
+ kvvfsMethods.installMethod(k, f);
+ }else{
+ kvvfsMethods[kvvfsMethods.memberKey(k)] =
+ wasm.installFunction(kvvfsMethods.memberSignature(k), f);
+ }
+ }
+ for(const e of Object.entries(methodOverrides.vfs)){
+
+ const k = e[0], f = e[1], km = pVfs.memberKey(k),
+ member = pVfs.structInfo.members[k]
+ || util.toss("Missing pVfs.structInfo[",k,"]");
+ originalMethods.vfs[k] = wasm.functionEntry(pVfs[km]);
+ pVfs[km] = wasm.installFunction(member.signature, f);
+ }
+ for(const e of Object.entries(methodOverrides.ioDb)){
+
+ const k = e[0], f = e[1], km = pIoDb.memberKey(k);
+ originalMethods.ioDb[k] = wasm.functionEntry(pIoDb[km])
+ || util.toss("Missing native pIoDb[",km,"]");
+ pIoDb[km] = wasm.installFunction(pIoDb.memberSignature(k), f);
+ }
+ for(const e of Object.entries(methodOverrides.ioJrnl)){
+
+ const k = e[0], f = e[1], km = pIoJrnl.memberKey(k);
+ originalMethods.ioJrnl[k] = wasm.functionEntry(pIoJrnl[km])
+ || util.toss("Missing native pIoJrnl[",km,"]");
+ if( true===f ){
+
+ pIoJrnl[km] = pIoDb[km] || util.toss("Missing copied pIoDb[",km,"]");
+ }else{
+ pIoJrnl[km] = wasm.installFunction(pIoJrnl.memberSignature(k), f);
+ }
+ }
+ }finally{
+ kvvfsMethods.dispose();
+ pVfs.dispose();
+ pIoDb.dispose();
+ pIoJrnl.dispose();
+ }
+
+
+
+
+ const sqlite3_js_kvvfs_clear = function callee(which){
+ if( ''===which ){
+ return callee('local') + callee('session');
+ }
+ const store = storageForZClass(which);
+ if( !store ) return 0;
+ if( store.files.length ){
+ if( globalThis.localStorage===store.storage
+ || globalThis.sessionStorage===store.storage ){
+
+ }else{
+
+ toss3(capi.SQLITE_ACCESS,
+ "Cannot clear in-use database storage.");
+ }
+ }
+ const s = store.storage;
+ const toRm = [] ;
+ let i, n = s.length;
+
+ for( i = 0; i < n; ++i ){
+ const k = s.key(i);
+
+ if(!store.keyPrefix || k.startsWith(store.keyPrefix)) toRm.push(k);
+ }
+ toRm.forEach((kk)=>s.removeItem(kk));
+
+ return toRm.length;
+ };
+
+
+ const sqlite3_js_kvvfs_size = function callee(which){
+ if( ''===which ){
+ return callee('local') + callee('session');
+ }
+ const store = storageForZClass(which);
+ if( !store ) return 0;
+ const s = store.storage;
+ let i, sz = 0;
+ for(i = 0; i < s.length; ++i){
+ const k = s.key(i);
+ if(!store.keyPrefix || k.startsWith(store.keyPrefix)){
+ sz += k.length;
+ sz += s.getItem(k).length;
+ }
+ }
+ return sz * 2 ;
+ };
+
+
+ const sqlite3_js_kvvfs_export = function callee(...args){
+ let opt;
+ if( 1===args.length && 'object'===typeof args[0] ){
+ opt = args[0];
+ }else if(args.length){
+ opt = Object.assign(Object.create(null),{
+ name: args[0],
+
+ });
+ }
+ const store = opt ? storageForZClass(opt.name) : null;
+ if( !store ){
+ toss3(capi.SQLITE_NOTFOUND,
+ "There is no kvvfs storage named",opt?.name);
+ }
+
+ const s = store.storage;
+ const rc = Object.assign(Object.create(null),{
+ name: store.jzClass,
+ timestamp: Date.now(),
+ pages: []
+ });
+ const pages = Object.create(null);
+ let xpages;
+ const keyPrefix = store.keyPrefix;
+ const rxTail = keyPrefix
+ ? /^kvvfs-[^-]+-(\w+)/
+ : undefined;
+ let i = 0, n = s.length;
+ for( ; i < n; ++i ){
+ const k = s.key(i);
+ if( !keyPrefix || k.startsWith(keyPrefix) ){
+ let kk = (keyPrefix ? rxTail.exec(k) : undefined)?.[1] ?? k;
+ switch( kk ){
+ case 'jrnl':
+ if( opt.includeJournal ) rc.journal = s.getItem(k);
+ break;
+ case 'sz':
+ rc.size = +s.getItem(k);
+ break;
+ default:
+ kk = +kk ;
+ if( !util.isInt32(kk) || kk<=0 ){
+ toss3(capi.SQLITE_RANGE, "Malformed kvvfs key: "+k);
+ }
+ if( opt.decodePages ){
+ const spg = s.getItem(k),
+ n = spg.length,
+ z = cache.memBuffer(0),
+ zDec = cache.memBuffer(1),
+ heap = wasm.heap8u();
+ let i = 0;
+ for( ; i < n; ++i ){
+ heap[wasm.ptr.add(z, i)] = spg.codePointAt(i) & 0xff;
+ }
+ heap[wasm.ptr.add(z, i)] = 0;
+
+ const nDec = kvvfsDecode(
+ z, zDec, cache.buffer.n
+ );
+
+ pages[kk] = heap.slice(Number(zDec), wasm.ptr.addn(zDec, nDec));
+ }else{
+ pages[kk] = s.getItem(k);
+ }
+ break;
+ }
+ }
+ }
+ if( opt.decodePages ) cache.memBufferFree(1);
+
+ Object.keys(pages).map((v)=>+v).sort().forEach(
+ (v)=>rc.pages.push(pages[v])
+ );
+ return rc;
+ };
+
+
+ const sqlite3_js_kvvfs_import = function(exp, overwrite=false){
+ if( !exp?.timestamp
+ || !exp.name
+ || undefined===exp.size
+ || !Array.isArray(exp.pages) ){
+ toss3(capi.SQLITE_MISUSE, "Malformed export object.");
+ }else if( !exp.size
+ || (exp.size !== (exp.size | 0))
+
+ || exp.size>=0x7fffffff ){
+ toss3(capi.SQLITE_RANGE, "Invalid db size: "+exp.size);
+ }
+
+ validateStorageName(exp.name);
+ let store = storageForZClass(exp.name);
+ const isNew = !store;
+ if( store ){
+ if( !overwrite ){
+
+ toss3(capi.SQLITE_ACCESS,
+ "Storage '"+exp.name+"' already exists and",
+ "overwrite was not specified.");
+ }else if( !store.files || !store.jzClass ){
+ toss3(capi.SQLITE_ERROR,
+ "Internal storage object", exp.name,"seems to be malformed.");
+ }else if( store.files.length ){
+ toss3(capi.SQLITE_IOERR_ACCESS,
+ "Cannot import db storage while it is in use.");
+ }
+ sqlite3_js_kvvfs_clear(exp.name);
+ }else{
+ store = newStorageObj(exp.name);
+
+ }
+
+
+ const keyPrefix = kvvfsKeyPrefix(exp.name);
+ let zEnc;
+ try{
+ ;
+ const s = store.storage;
+ s.setItem(keyPrefix+'sz', exp.size);
+ if( exp.journal ) s.setItem(keyPrefix+'jrnl', exp.journal);
+ if( exp.pages[0] instanceof Uint8Array ){
+
+
+ exp.pages.forEach((u,ndx)=>{
+ const n = u.length;
+ if( 0 && cache.fixedPageSize !== n ){
+ util.toss3(capi.SQLITE_RANGE,"Unexpected page size:", n);
+ }
+ zEnc ??= cache.memBuffer(1);
+ const zBin = cache.memBuffer(0),
+ heap = wasm.heap8u();
+
+ heap.set(u, Number(zBin));
+ heap[wasm.ptr.addn(zBin,n)] = 0;
+ const rc = kvvfsEncode(zBin, n, zEnc);
+ util.assert( rc < cache.buffer.n,
+ "Impossibly long output - possibly smashed the heap" );
+ util.assert( 0===wasm.peek8(wasm.ptr.add(zEnc,rc)),
+ "Expecting NUL-terminated encoded output" );
+ const jenc = wasm.cstrToJs(zEnc);
+
+ s.setItem(keyPrefix+(ndx+1), jenc);
+ });
+ }else if( exp.pages[0] ){
+
+ exp.pages.forEach((v,ndx)=>s.setItem(keyPrefix+(ndx+1), v));
+ }
+ if( isNew ) installStorageAndJournal(store);
+ }catch{
+ if( !isNew ){
+ try{sqlite3_js_kvvfs_clear(exp.name);}catch(ee){}
+ }
+ }finally{
+ if( zEnc ) cache.memBufferFree(1);
+ }
+ return this;
+ };
+
+
+ const sqlite3_js_kvvfs_reserve = function(name){
+ let store = storageForZClass(name);
+ if( store ){
+ ++store.refc;
+ return;
+ }
+ validateStorageName(name);
+ installStorageAndJournal(newStorageObj(name));
+ };
+
+
+ const sqlite3_js_kvvfs_unlink = function(name){
+ const store = storageForZClass(name);
+ if( !store
+ || kvvfsIsPersistentName(store.jzClass)
+ || isBuiltinName(store.jzClass)
+ || cache.rxJournalSuffix.test(name) ) return false;
+ if( store.refc > store.files.length || 0===store.files.length ){
+ if( --store.refc<=0 ){
+
+ deleteStorage(store);
+ }
+ return true;
+ }
+ return false;
+ };
+
+
+ const sqlite3_js_kvvfs_listen = function(opt){
+ if( !opt || 'object'!==typeof opt ){
+ toss3(capi.SQLITE_MISUSE, "Expecting a listener object.");
+ }
+ let store = storageForZClass(opt.storage);
+ if( !store ){
+ if( opt.storage && opt.reserve ){
+ sqlite3_js_kvvfs_reserve(opt.storage);
+ store = storageForZClass(opt.storage);
+ util.assert(store,
+ "Unexpectedly cannot fetch reserved storage "
+ +opt.storage);
+ }else{
+ toss3(capi.SQLITE_NOTFOUND,"No such storage:",opt.storage);
+ }
+ }
+ if( opt.events ){
+ (store.listeners ??= []).push(opt);
+ }
+ };
+
+
+ const sqlite3_js_kvvfs_unlisten = function(opt){
+ const store = storageForZClass(opt?.storage);
+ if( store?.listeners && opt.events ){
+ const n = store.listeners.length;
+ store.listeners = store.listeners.filter((v)=>v!==opt);
+ const rc = n>store.listeners.length;
+ if( !store.listeners.length ){
+
+ store.listeners = undefined;
+ }
+ return rc;
+ }
+ return false;
+ };
+
+ sqlite3.kvvfs.reserve = sqlite3_js_kvvfs_reserve;
+ sqlite3.kvvfs.import = sqlite3_js_kvvfs_import;
+ sqlite3.kvvfs.export = sqlite3_js_kvvfs_export;
+ sqlite3.kvvfs.unlink = sqlite3_js_kvvfs_unlink;
+ sqlite3.kvvfs.listen = sqlite3_js_kvvfs_listen;
+ sqlite3.kvvfs.unlisten = sqlite3_js_kvvfs_unlisten;
+ sqlite3.kvvfs.exists = (name)=>!!storageForZClass(name);
+ sqlite3.kvvfs.estimateSize = sqlite3_js_kvvfs_size;
+ sqlite3.kvvfs.clear = sqlite3_js_kvvfs_clear;
+
+
+ if( globalThis.Storage ){
+
+ capi.sqlite3_js_kvvfs_size = (which="")=>sqlite3_js_kvvfs_size(which);
+ capi.sqlite3_js_kvvfs_clear = (which="")=>sqlite3_js_kvvfs_clear(which);
+ }
+
+ if(sqlite3.oo1?.DB){
+
+ const DB = sqlite3.oo1.DB;
+ sqlite3.oo1.JsStorageDb = function(
+ storageName = sqlite3.oo1.JsStorageDb.defaultStorageName
+ ){
+ const opt = DB.dbCtorHelper.normalizeArgs(...arguments);
+ opt.vfs = 'kvvfs';
+ if( 0 ){
+
+ if( opt.flags ) opt.flags = 'cw'+opt.flags;
+ else opt.flags = 'cw';
+ }
+ switch( opt.filename ){
+
+ case ":sessionStorage:": opt.filename = 'session'; break;
+ case ":localStorage:": opt.filename = 'local'; break;
+ }
+ const m = /(file:(\/\/)?)([^?]+)/.exec(opt.filename);
+ validateStorageName( m ? m[3] : opt.filename);
+ DB.dbCtorHelper.call(this, opt);
+ };
+ sqlite3.oo1.JsStorageDb.defaultStorageName
+ = cache.storagePool.session ? 'session' : nameOfThisThreadStorage;
+ const jdb = sqlite3.oo1.JsStorageDb;
+ jdb.prototype = Object.create(DB.prototype);
+ jdb.clearStorage = sqlite3_js_kvvfs_clear;
+
+ jdb.prototype.clearStorage = function(){
+ return jdb.clearStorage(this.affirmOpen().dbFilename(), true);
+ };
+
+ jdb.storageSize = sqlite3_js_kvvfs_size;
+
+ jdb.prototype.storageSize = function(){
+ return jdb.storageSize(this.affirmOpen().dbFilename(), true);
+ };
+ }
+
+ if( sqlite3.__isUnderTest && sqlite3.vtab ){
+
+ const cols = Object.assign(Object.create(null),{
+ rowid: {type: 'INTEGER'},
+ name: {type: 'TEXT'},
+ nRef: {type: 'INTEGER'},
+ nOpen: {type: 'INTEGER'},
+ isTransient: {type: 'INTEGER'},
+ dbSize: {type: 'INTEGER'}
+ });
+ Object.keys(cols).forEach((v,i)=>cols[v].colId = i);
+
+ const VT = sqlite3.vtab;
+ const ProtoCursor = Object.assign(Object.create(null),{
+ row: function(){
+ return cache.storagePool[this.names[this.rowid]];
+ }
+ });
+ Object.assign(Object.create(ProtoCursor),{
+ rowid: 0,
+ names: Object.keys(cache.storagePool)
+ .filter(v=>!cache.rxJournalSuffix.test(v))
+ });
+ const cursorState = function(cursor, reset){
+ const o = (cursor instanceof capi.sqlite3_vtab_cursor)
+ ? cursor
+ : VT.xCursor.get(cursor);
+ if( reset || !o.vTabState ){
+ o.vTabState = Object.assign(Object.create(ProtoCursor),{
+ rowid: 0,
+ names: Object.keys(cache.storagePool)
+ .filter(v=>!cache.rxJournalSuffix.test(v))
+ });
+ }
+ return o.vTabState;
+ };
+
+ const dbg = 1 ? ()=>{} : (...args)=>debug("vtab",...args);
+
+ const theModule = function f(){
+ return f.mod ??= new sqlite3.capi.sqlite3_module().setupModule({
+ catchExceptions: true,
+ methods: {
+ xConnect: function(pDb, pAux, argc, argv, ppVtab, pzErr){
+ dbg("xConnect");
+ try{
+ const xcol = [];
+ Object.keys(cols).forEach((k)=>{
+ xcol.push(k+" "+cols[k].type);
+ });
+ const rc = capi.sqlite3_declare_vtab(
+ pDb, "CREATE TABLE ignored("+xcol.join(',')+")"
+ );
+ if(0===rc){
+ const t = VT.xVtab.create(ppVtab);
+ util.assert(
+ (t === VT.xVtab.get(wasm.peekPtr(ppVtab))),
+ "output pointer check failed"
+ );
+ }
+ return rc;
+ }catch(e){
+ return VT.xError('xConnect', e, capi.SQLITE_ERROR);
+ }
+ },
+ xCreate: wasm.ptr.null,
+
+ xDisconnect: function(pVtab){
+ dbg("xDisconnect",...arguments);
+ VT.xVtab.dispose(pVtab);
+ return 0;
+ },
+ xOpen: function(pVtab, ppCursor){
+ dbg("xOpen",...arguments);
+ VT.xCursor.create(ppCursor);
+ return 0;
+ },
+ xClose: function(pCursor){
+ dbg("xClose",...arguments);
+ const c = VT.xCursor.unget(pCursor);
+ delete c.vTabState;
+ c.dispose();
+ return 0;
+ },
+ xNext: function(pCursor){
+ dbg("xNext",...arguments);
+ const c = VT.xCursor.get(pCursor);
+ ++cursorState(c).rowid;
+ return 0;
+ },
+ xColumn: function(pCursor, pCtx, iCol){
+ dbg("xColumn",...arguments);
+
+ const st = cursorState(pCursor);
+ const store = st.row();
+ util.assert(store, "Unexpected xColumn call");
+ switch(iCol){
+ case cols.rowid.colId:
+ capi.sqlite3_result_int(pCtx, st.rowid);
+ break;
+ case cols.name.colId:
+ capi.sqlite3_result_text(pCtx, store.jzClass, -1, capi.SQLITE_TRANSIENT);
+ break;
+ case cols.nRef.colId:
+ capi.sqlite3_result_int(pCtx, store.refc);
+ break;
+ case cols.nOpen.colId:
+ capi.sqlite3_result_int(pCtx, store.files.length);
+ break;
+ case cols.isTransient.colId:
+ capi.sqlite3_result_int(pCtx, !!store.deleteAtRefc0);
+ break;
+ case cols.dbSize.colId:
+ capi.sqlite3_result_int(pCtx, storageGetDbSize(store));
+ break;
+ default:
+ capi.sqlite3_result_error(pCtx, "Invalid column id: "+iCol);
+ return capi.SQLITE_RANGE;
+ }
+ return 0;
+ },
+ xRowid: function(pCursor, ppRowid64){
+ dbg("xRowid",...arguments);
+ const st = cursorState(pCursor);
+ VT.xRowid(ppRowid64, st.rowid);
+ return 0;
+ },
+ xEof: function(pCursor){
+ const st = cursorState(pCursor);
+ dbg("xEof?="+(!st.row()),...arguments);
+ return !st.row();
+ },
+ xFilter: function(pCursor, idxNum, idxCStr,
+ argc, argv){
+ dbg("xFilter",...arguments);
+ const st = cursorState(pCursor, true);
+ return 0;
+ },
+ xBestIndex: function(pVtab, pIdxInfo){
+ dbg("xBestIndex",...arguments);
+
+ const pii = new capi.sqlite3_index_info(pIdxInfo);
+ pii.$estimatedRows = cache.storagePool.size;
+ pii.$estimatedCost = 1.0;
+ pii.dispose();
+ return 0;
+ }
+ }
+ });
+ };
+
+ sqlite3.kvvfs.create_module = function(pDb, name="sqlite_kvvfs"){
+ return capi.sqlite3_create_module(pDb, name, theModule(),
+ wasm.ptr.null);
+ };
+
+ }
+
+
+});
+
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+ 'use strict';
+ if( sqlite3.config.disable?.vfs?.opfs &&
+ sqlite3.config.disable.vfs['opfs-vfs'] ){
+ return;
+ }
+ const toss = sqlite3.util.toss,
+ capi = sqlite3.capi,
+ util = sqlite3.util,
+ wasm = sqlite3.wasm;
+
+
+ const opfsUtil = sqlite3.opfs = Object.create(null);
+
+
+ opfsUtil.thisThreadHasOPFS = ()=>{
+ return globalThis.FileSystemHandle &&
+ globalThis.FileSystemDirectoryHandle &&
+ globalThis.FileSystemFileHandle &&
+ globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle &&
+ navigator?.storage?.getDirectory;
+ };
+
+
+ opfsUtil.getRootDir = async function f(){
+ return f.promise ??= navigator.storage.getDirectory().then(d=>{
+ opfsUtil.rootDirectory = d;
+ return d;
+ }).catch(e=>{
+ delete f.promise;
+ throw e;
+ });
+ };
+
+
+ opfsUtil.getResolvedPath = function(filename,splitIt){
+ const p = new URL(filename, "file://irrelevant").pathname;
+ return splitIt ? p.split('/').filter((v)=>!!v) : p;
+ };
+
+
+ opfsUtil.getDirForFilename = async function f(absFilename, createDirs = false){
+ const path = opfsUtil.getResolvedPath(absFilename, true);
+ const filename = path.pop();
+ let dh = await opfsUtil.getRootDir();
+ for(const dirName of path){
+ if(dirName){
+ dh = await dh.getDirectoryHandle(dirName, {create: !!createDirs});
+ }
+ }
+ return [dh, filename];
+ };
+
+
+ opfsUtil.mkdir = async function(absDirName){
+ try {
+ await opfsUtil.getDirForFilename(absDirName+"/filepart", true);
+ return true;
+ }catch(e){
+
+ return false;
+ }
+ };
+
+
+ opfsUtil.entryExists = async function(fsEntryName){
+ try {
+ const [dh, fn] = await opfsUtil.getDirForFilename(fsEntryName);
+ await dh.getFileHandle(fn);
+ return true;
+ }catch(e){
+ return false;
+ }
+ };
+
+
+ opfsUtil.randomFilename = function f(len=16){
+ if(!f._chars){
+ f._chars = "abcdefghijklmnopqrstuvwxyz"+
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
+ "012346789";
+ f._n = f._chars.length;
+ }
+ const a = [];
+ let i = 0;
+ for( ; i < len; ++i){
+ const ndx = Math.random() * (f._n * 64) % f._n | 0;
+ a[i] = f._chars[ndx];
+ }
+ return a.join("");
+
+ };
+
+
+ opfsUtil.treeList = async function(){
+ const doDir = async function callee(dirHandle,tgt){
+ tgt.name = dirHandle.name;
+ tgt.dirs = [];
+ tgt.files = [];
+ for await (const handle of dirHandle.values()){
+ if('directory' === handle.kind){
+ const subDir = Object.create(null);
+ tgt.dirs.push(subDir);
+ await callee(handle, subDir);
+ }else{
+ tgt.files.push(handle.name);
+ }
+ }
+ };
+ const root = Object.create(null);
+ const dir = await opfsUtil.getRootDir();
+ await doDir(dir, root);
+ return root;
+ };
+
+
+ opfsUtil.rmfr = async function(){
+ const rd = await opfsUtil.getRootDir();
+ const dir = rd, opt = {recurse: true};
+ for await (const handle of dir.values()){
+ dir.removeEntry(handle.name, opt);
+ }
+ };
+
+
+ opfsUtil.unlink = async function(fsEntryName, recursive = false,
+ throwOnError = false){
+ try {
+ const [hDir, filenamePart] =
+ await opfsUtil.getDirForFilename(fsEntryName, false);
+ await hDir.removeEntry(filenamePart, {recursive});
+ return true;
+ }catch(e){
+ if(throwOnError){
+ throw new Error("unlink(",arguments[0],") failed: "+e.message,{
+ cause: e
+ });
+ }
+ return false;
+ }
+ };
+
+
+ opfsUtil.traverse = async function(opt){
+ const defaultOpt = {
+ recursive: true,
+ directory: await opfsUtil.getRootDir()
+ };
+ if('function'===typeof opt){
+ opt = {callback:opt};
+ }
+ opt = Object.assign(defaultOpt, opt||{});
+ const doDir = async function callee(dirHandle, depth){
+ for await (const handle of dirHandle.values()){
+ if(false === opt.callback(handle, dirHandle, depth)) return false;
+ else if(opt.recursive && 'directory' === handle.kind){
+ if(false === await callee(handle, depth + 1)) break;
+ }
+ }
+ };
+ doDir(opt.directory, 0);
+ };
+
+
+ const importDbChunked = async function(filename, callback){
+ const [hDir, fnamePart] = await opfsUtil.getDirForFilename(filename, true);
+ const hFile = await hDir.getFileHandle(fnamePart, {create:true});
+ let sah = await hFile.createSyncAccessHandle();
+ let nWrote = 0, chunk, checkedHeader = false, err = false;
+ try{
+ sah.truncate(0);
+ while( undefined !== (chunk = await callback()) ){
+ if(chunk instanceof ArrayBuffer) chunk = new Uint8Array(chunk);
+ if( !checkedHeader && 0===nWrote && chunk.byteLength>=15 ){
+ util.affirmDbHeader(chunk);
+ checkedHeader = true;
+ }
+ sah.write(chunk, {at: nWrote});
+ nWrote += chunk.byteLength;
+ }
+ if( nWrote < 512 || 0!==nWrote % 512 ){
+ toss("Input size",nWrote,"is not correct for an SQLite database.");
+ }
+ if( !checkedHeader ){
+ const header = new Uint8Array(20);
+ sah.read( header, {at: 0} );
+ util.affirmDbHeader( header );
+ }
+ sah.write(new Uint8Array([1,1]), {at: 18});
+ return nWrote;
+ }catch(e){
+ await sah.close();
+ sah = undefined;
+ await hDir.removeEntry( fnamePart ).catch(()=>{});
+ throw e;
+ }finally {
+ if( sah ) await sah.close();
+ }
+ };
+
+
+ opfsUtil.importDb = async function(filename, bytes){
+ if( bytes instanceof Function ){
+ return importDbChunked(filename, bytes);
+ }
+ if(bytes instanceof ArrayBuffer) bytes = new Uint8Array(bytes);
+ util.affirmIsDb(bytes);
+ const n = bytes.byteLength;
+ const [hDir, fnamePart] = await opfsUtil.getDirForFilename(filename, true);
+ let sah, err, nWrote = 0;
+ try {
+ const hFile = await hDir.getFileHandle(fnamePart, {create:true});
+ sah = await hFile.createSyncAccessHandle();
+ sah.truncate(0);
+ nWrote = sah.write(bytes, {at: 0});
+ if(nWrote != n){
+ toss("Expected to write "+n+" bytes but wrote "+nWrote+".");
+ }
+ sah.write(new Uint8Array([1,1]), {at: 18}) ;
+ return nWrote;
+ }catch(e){
+ if( sah ){ await sah.close(); sah = undefined; }
+ await hDir.removeEntry( fnamePart ).catch(()=>{});
+ throw e;
+ }finally{
+ if( sah ) await sah.close();
+ }
+ };
+
+
+ opfsUtil.vfsInstallationFeatureCheck = function(vfsName){
+ if( !globalThis.SharedArrayBuffer || !globalThis.Atomics ){
+ toss("Cannot install OPFS: Missing SharedArrayBuffer and/or Atomics.",
+ "The server must emit the COOP/COEP response headers to enable those.",
+ "See https://sqlite.org/wasm/doc/trunk/persistence.md#coop-coep");
+ }else if( 'undefined'===typeof WorkerGlobalScope ){
+ toss("The OPFS sqlite3_vfs cannot run in the main thread",
+ "because it requires Atomics.wait().");
+ }else if( !globalThis.FileSystemHandle ||
+ !globalThis.FileSystemDirectoryHandle ||
+ !globalThis.FileSystemFileHandle?.prototype?.createSyncAccessHandle ||
+ !navigator?.storage?.getDirectory ){
+ toss("Missing required OPFS APIs.");
+ }else if( 'opfs-wl'===vfsName && !globalThis.Atomics.waitAsync ){
+ toss('The',vfsName,'VFS requires Atomics.waitAsync(), which is not available.');
+ }
+ };
+
+
+ opfsUtil.initOptions = function callee(vfsName, options){
+ const urlParams = new URL(globalThis.location.href).searchParams;
+ if( urlParams.has(vfsName+'-disable') ){
+
+ return;
+ }
+ try{
+ opfsUtil.vfsInstallationFeatureCheck(vfsName);
+ }catch(e){
+ return;
+ }
+ options = util.nu(options);
+ options.vfsName = vfsName;
+ options.verbose ??= urlParams.has('opfs-verbose')
+ ? +urlParams.get('opfs-verbose') : 1;
+ options.sanityChecks ??= urlParams.has('opfs-sanity-check');
+
+ if( !opfsUtil.proxyUri ){
+ opfsUtil.proxyUri = "sqlite3-opfs-async-proxy.js";
+ if( sqlite3.scriptInfo?.sqlite3Dir ){
+
+ opfsUtil.proxyUri = (
+ sqlite3.scriptInfo.sqlite3Dir + opfsUtil.proxyUri
+ );
+ }
+ }
+ options.proxyUri ??= opfsUtil.proxyUri;
+ if('function' === typeof options.proxyUri){
+ options.proxyUri = options.proxyUri();
+ }
+
+ return opfsUtil.options = options;
+ };
+
+
+ opfsUtil.createVfsState = function(){
+ const state = util.nu();
+ const options = opfsUtil.options;
+ state.verbose = options.verbose;
+
+ const loggers = [
+ sqlite3.config.error,
+ sqlite3.config.warn,
+ sqlite3.config.log
+ ];
+ const vfsName = options.vfsName
+ || toss("Maintenance required: missing VFS name");
+ const logImpl = (level,...args)=>{
+ if(state.verbose>level) loggers[level](vfsName+":",...args);
+ };
+ const log = (...args)=>logImpl(2, ...args),
+ warn = (...args)=>logImpl(1, ...args),
+ error = (...args)=>logImpl(0, ...args),
+ capi = sqlite3.capi,
+ wasm = sqlite3.wasm;
+
+ const opfsVfs = state.vfs = new capi.sqlite3_vfs();
+ const opfsIoMethods = opfsVfs.ioMethods = new capi.sqlite3_io_methods();
+
+ opfsIoMethods.$iVersion = 1;
+ opfsVfs.$iVersion = 2;
+ opfsVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof;
+ opfsVfs.$mxPathname = 1024;
+ opfsVfs.$zName = wasm.allocCString(vfsName);
+ opfsVfs.addOnDispose(
+ '$zName', opfsVfs.$zName, opfsIoMethods
+
+ );
+
+ opfsVfs.metrics = util.nu({
+ counters: util.nu(),
+ dump: function(){
+ let k, n = 0, t = 0, w = 0;
+ for(k in state.opIds){
+ const m = metrics[k];
+ n += m.count;
+ t += m.time;
+ w += m.wait;
+ m.avgTime = (m.count && m.time) ? (m.time / m.count) : 0;
+ m.avgWait = (m.count && m.wait) ? (m.wait / m.count) : 0;
+ }
+ sqlite3.config.log(globalThis.location.href,
+ "metrics for",globalThis.location.href,":",metrics,
+ "\nTotal of",n,"op(s) for",t,
+ "ms (incl. "+w+" ms of waiting on the async side)");
+ sqlite3.config.log("Serialization metrics:",opfsVfs.metrics.counters.s11n);
+ opfsVfs.worker?.postMessage?.({type:'opfs-async-metrics'});
+ },
+ reset: function(){
+ let k;
+ const r = (m)=>(m.count = m.time = m.wait = 0);
+ const m = opfsVfs.metrics.counters;
+ for(k in state.opIds){
+ r(m[k] = Object.create(null));
+ }
+ let s = m.s11n = Object.create(null);
+ s = s.serialize = Object.create(null);
+ s.count = s.time = 0;
+ s = m.s11n.deserialize = Object.create(null);
+ s.count = s.time = 0;
+ }
+ });
+
+
+ state.asyncIdleWaitTime = 150;
+
+
+ state.asyncS11nExceptions = 1;
+
+ state.fileBufferSize = 1024 * 64;
+ state.sabS11nOffset = state.fileBufferSize;
+
+ state.sabS11nSize = opfsVfs.$mxPathname * 2;
+
+ state.sabIO = new SharedArrayBuffer(
+ state.fileBufferSize
+ + state.sabS11nSize
+ );
+
+
+ state.opIds = Object.create(null);
+ {
+
+ let i = 0;
+
+ state.opIds.whichOp = i++;
+
+ state.opIds.rc = i++;
+
+ state.opIds.xAccess = i++;
+ state.opIds.xClose = i++;
+ state.opIds.xDelete = i++;
+ state.opIds.xDeleteNoWait = i++;
+ state.opIds.xFileSize = i++;
+ state.opIds.xLock = i++;
+ state.opIds.xOpen = i++;
+ state.opIds.xRead = i++;
+ state.opIds.xSleep = i++;
+ state.opIds.xSync = i++;
+ state.opIds.xTruncate = i++;
+ state.opIds.xUnlock = i++;
+ state.opIds.xWrite = i++;
+ state.opIds.mkdir = i++ ;
+
+ state.opIds['opfs-async-metrics'] = i++;
+ state.opIds['opfs-async-shutdown'] = i++;
+
+ state.opIds.retry = i++;
+ state.sabOP = new SharedArrayBuffer(
+ i * 4);
+ }
+
+ state.sq3Codes = Object.create(null);
+ for(const k of [
+ 'SQLITE_ACCESS_EXISTS',
+ 'SQLITE_ACCESS_READWRITE',
+ 'SQLITE_BUSY',
+ 'SQLITE_CANTOPEN',
+ 'SQLITE_ERROR',
+ 'SQLITE_IOERR',
+ 'SQLITE_IOERR_ACCESS',
+ 'SQLITE_IOERR_CLOSE',
+ 'SQLITE_IOERR_DELETE',
+ 'SQLITE_IOERR_FSYNC',
+ 'SQLITE_IOERR_LOCK',
+ 'SQLITE_IOERR_READ',
+ 'SQLITE_IOERR_SHORT_READ',
+ 'SQLITE_IOERR_TRUNCATE',
+ 'SQLITE_IOERR_UNLOCK',
+ 'SQLITE_IOERR_WRITE',
+ 'SQLITE_LOCK_EXCLUSIVE',
+ 'SQLITE_LOCK_NONE',
+ 'SQLITE_LOCK_PENDING',
+ 'SQLITE_LOCK_RESERVED',
+ 'SQLITE_LOCK_SHARED',
+ 'SQLITE_LOCKED',
+ 'SQLITE_MISUSE',
+ 'SQLITE_NOTFOUND',
+ 'SQLITE_OPEN_CREATE',
+ 'SQLITE_OPEN_DELETEONCLOSE',
+ 'SQLITE_OPEN_MAIN_DB',
+ 'SQLITE_OPEN_READONLY',
+ 'SQLITE_LOCK_NONE',
+ 'SQLITE_LOCK_SHARED',
+ 'SQLITE_LOCK_RESERVED',
+ 'SQLITE_LOCK_PENDING',
+ 'SQLITE_LOCK_EXCLUSIVE'
+ ]){
+ state.sq3Codes[k] =
+ capi[k] ?? toss("Maintenance required: not found:",k);
+ }
+
+ state.opfsFlags = Object.assign(Object.create(null),{
+
+ OPFS_UNLOCK_ASAP: 0x01,
+
+ OPFS_UNLINK_BEFORE_OPEN: 0x02,
+
+ defaultUnlockAsap: false
+ });
+
+ opfsVfs.metrics.reset();
+ const metrics = opfsVfs.metrics.counters;
+
+
+ const opRun = opfsVfs.opRun = (op,...args)=>{
+ const opNdx = state.opIds[op] || toss(opfsVfs.vfsName+": Invalid op ID:",op);
+ state.s11n.serialize(...args);
+ Atomics.store(state.sabOPView, state.opIds.rc, -1);
+ Atomics.store(state.sabOPView, state.opIds.whichOp, opNdx);
+ Atomics.notify(state.sabOPView, state.opIds.whichOp)
+ ;
+ const t = performance.now();
+ while('not-equal'!==Atomics.wait(state.sabOPView, state.opIds.rc, -1)){
+
+ }
+
+ const rc = Atomics.load(state.sabOPView, state.opIds.rc);
+ metrics[op].wait += performance.now() - t;
+ if(rc && state.asyncS11nExceptions){
+ const err = state.s11n.deserialize();
+ if(err) error(op+"() async error:",...err);
+ }
+ return rc;
+ };
+
+ const opTimer = Object.create(null);
+ opTimer.op = undefined;
+ opTimer.start = undefined;
+ const mTimeStart = opfsVfs.mTimeStart = (op)=>{
+ opTimer.start = performance.now();
+ opTimer.op = op;
+ ++metrics[op].count;
+ };
+ const mTimeEnd = opfsVfs.mTimeEnd = ()=>(
+ metrics[opTimer.op].time += performance.now() - opTimer.start
+ );
+
+
+ const __openFiles = opfsVfs.__openFiles = Object.create(null);
+
+
+ const ioSyncWrappers = opfsVfs.ioSyncWrappers = util.nu({
+ xCheckReservedLock: function(pFile,pOut){
+
+ wasm.poke(pOut, 0, 'i32');
+ return 0;
+ },
+ xClose: function(pFile){
+ mTimeStart('xClose');
+ let rc = 0;
+ const f = __openFiles[pFile];
+ if(f){
+ delete __openFiles[pFile];
+ rc = opRun('xClose', pFile);
+ if(f.sq3File) f.sq3File.dispose();
+ }
+ mTimeEnd();
+ return rc;
+ },
+ xDeviceCharacteristics: function(pFile){
+ return capi.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
+ },
+ xFileControl: function(pFile, opId, pArg){
+
+ return capi.SQLITE_NOTFOUND;
+ },
+ xFileSize: function(pFile,pSz64){
+ mTimeStart('xFileSize');
+ let rc = opRun('xFileSize', pFile);
+ if(0==rc){
+ try {
+ const sz = state.s11n.deserialize()[0];
+ wasm.poke(pSz64, sz, 'i64');
+ }catch(e){
+ error("Unexpected error reading xFileSize() result:",e);
+ rc = state.sq3Codes.SQLITE_IOERR;
+ }
+ }
+ mTimeEnd();
+ return rc;
+ },
+ xRead: function(pFile,pDest,n,offset64){
+ mTimeStart('xRead');
+ const f = __openFiles[pFile];
+ let rc;
+ try {
+ rc = opRun('xRead',pFile, n, Number(offset64));
+ if(0===rc || capi.SQLITE_IOERR_SHORT_READ===rc){
+
+ wasm.heap8u().set(f.sabView.subarray(0, n), Number(pDest));
+ }
+ }catch(e){
+ error("xRead(",arguments,") failed:",e,f);
+ rc = capi.SQLITE_IOERR_READ;
+ }
+ mTimeEnd();
+ return rc;
+ },
+ xSync: function(pFile,flags){
+ mTimeStart('xSync');
+ const rc = opRun('xSync', pFile, flags);
+ mTimeEnd();
+ return rc;
+ },
+ xTruncate: function(pFile,sz64){
+ mTimeStart('xTruncate');
+ const rc = opRun('xTruncate', pFile, Number(sz64));
+ mTimeEnd();
+ return rc;
+ },
+ xWrite: function(pFile,pSrc,n,offset64){
+ mTimeStart('xWrite');
+ const f = __openFiles[pFile];
+ let rc;
+ try {
+ f.sabView.set(wasm.heap8u().subarray(
+ Number(pSrc), Number(pSrc) + n
+ ));
+ rc = opRun('xWrite', pFile, n, Number(offset64));
+ }catch(e){
+ error("xWrite(",arguments,") failed:",e,f);
+ rc = capi.SQLITE_IOERR_WRITE;
+ }
+ mTimeEnd();
+ return rc;
+ }
+ });
+
+
+ const vfsSyncWrappers = opfsVfs.vfsSyncWrappers = {
+ xAccess: function(pVfs,zName,flags,pOut){
+ mTimeStart('xAccess');
+ const rc = opRun('xAccess', wasm.cstrToJs(zName));
+ wasm.poke( pOut, (rc ? 0 : 1), 'i32' );
+ mTimeEnd();
+ return 0;
+ },
+ xCurrentTime: function(pVfs,pOut){
+ wasm.poke(pOut, 2440587.5 + (new Date().getTime()/86400000),
+ 'double');
+ return 0;
+ },
+ xCurrentTimeInt64: function(pVfs,pOut){
+ wasm.poke(pOut, (2440587.5 * 86400000) + new Date().getTime(),
+ 'i64');
+ return 0;
+ },
+ xDelete: function(pVfs, zName, doSyncDir){
+ mTimeStart('xDelete');
+ const rc = opRun('xDelete', wasm.cstrToJs(zName), doSyncDir, false);
+ mTimeEnd();
+ return rc;
+ },
+ xFullPathname: function(pVfs,zName,nOut,pOut){
+
+ const i = wasm.cstrncpy(pOut, zName, nOut);
+ return i<nOut ? 0 : capi.SQLITE_CANTOPEN
+ ;
+ },
+ xGetLastError: function(pVfs,nOut,pOut){
+
+ sqlite3.config.warn("OPFS xGetLastError() has nothing sensible to return.");
+ return 0;
+ },
+
+ xOpen: function f(pVfs, zName, pFile, flags, pOutFlags){
+ mTimeStart('xOpen');
+ let opfsFlags = 0;
+ let jzName, zToFree;
+ if( !zName ){
+ jzName = opfsUtil.randomFilename();
+ zName = zToFree = wasm.allocCString(jzName);
+ }else if(wasm.isPtr(zName)){
+ if(capi.sqlite3_uri_boolean(zName, "opfs-unlock-asap", 0)){
+
+ opfsFlags |= state.opfsFlags.OPFS_UNLOCK_ASAP;
+ }
+ if(capi.sqlite3_uri_boolean(zName, "delete-before-open", 0)){
+ opfsFlags |= state.opfsFlags.OPFS_UNLINK_BEFORE_OPEN;
+ }
+ jzName = wasm.cstrToJs(zName);
+
+ }else{
+ sqlite3.config.error("Impossible zName value in xOpen?", zName);
+ return capi.SQLITE_CANTOPEN;
+ }
+ const fh = util.nu({
+ fid: pFile,
+ filename: jzName,
+ sab: new SharedArrayBuffer(state.fileBufferSize),
+ flags: flags,
+ readOnly: !(capi.SQLITE_OPEN_CREATE & flags)
+ && !!(flags & capi.SQLITE_OPEN_READONLY)
+ });
+ const rc = opRun('xOpen', pFile, jzName, flags, opfsFlags);
+ if(rc){
+ if( zToFree ) wasm.dealloc(zToFree);
+ }else{
+
+ if(fh.readOnly){
+ wasm.poke(pOutFlags, capi.SQLITE_OPEN_READONLY, 'i32');
+ }
+ __openFiles[pFile] = fh;
+ fh.sabView = state.sabFileBufView;
+ fh.sq3File = new capi.sqlite3_file(pFile);
+ if( zToFree ) fh.sq3File.addOnDispose(zToFree);
+ fh.sq3File.$pMethods = opfsIoMethods.pointer;
+ fh.lockType = capi.SQLITE_LOCK_NONE;
+ }
+ mTimeEnd();
+ return rc;
+ }
+ };
+
+ const pDVfs = capi.sqlite3_vfs_find(null);
+ if(pDVfs){
+ const dVfs = new capi.sqlite3_vfs(pDVfs);
+ opfsVfs.$xRandomness = dVfs.$xRandomness;
+ opfsVfs.$xSleep = dVfs.$xSleep;
+ dVfs.dispose();
+ }
+ if(!opfsVfs.$xRandomness){
+
+ opfsVfs.vfsSyncWrappers.xRandomness = function(pVfs, nOut, pOut){
+ const heap = wasm.heap8u();
+ let i = 0;
+ const npOut = Number(pOut);
+ for(; i < nOut; ++i) heap[npOut + i] = (Math.random()*255000) & 0xFF;
+ return i;
+ };
+ }
+ if(!opfsVfs.$xSleep){
+
+ opfsVfs.vfsSyncWrappers.xSleep = function(pVfs,ms){
+ mTimeStart('xSleep');
+ Atomics.wait(state.sabOPView, state.opIds.xSleep, 0, ms);
+ mTimeEnd();
+ return 0;
+ };
+ }
+
+const initS11n = function(){
+
+ if(state.s11n) return state.s11n;
+ const textDecoder = new TextDecoder(),
+ textEncoder = new TextEncoder('utf-8'),
+ viewU8 = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize),
+ viewDV = new DataView(state.sabIO, state.sabS11nOffset, state.sabS11nSize);
+ state.s11n = Object.create(null);
+
+ const TypeIds = Object.create(null);
+ TypeIds.number = { id: 1, size: 8, getter: 'getFloat64', setter: 'setFloat64' };
+ TypeIds.bigint = { id: 2, size: 8, getter: 'getBigInt64', setter: 'setBigInt64' };
+ TypeIds.boolean = { id: 3, size: 4, getter: 'getInt32', setter: 'setInt32' };
+ TypeIds.string = { id: 4 };
+
+ const getTypeId = (v)=>(
+ TypeIds[typeof v]
+ || toss("Maintenance required: this value type cannot be serialized.",v)
+ );
+ const getTypeIdById = (tid)=>{
+ switch(tid){
+ case TypeIds.number.id: return TypeIds.number;
+ case TypeIds.bigint.id: return TypeIds.bigint;
+ case TypeIds.boolean.id: return TypeIds.boolean;
+ case TypeIds.string.id: return TypeIds.string;
+ default: toss("Invalid type ID:",tid);
+ }
+ };
+
+
+ state.s11n.deserialize = function(clear=false){
+ const t = performance.now();
+ const argc = viewU8[0];
+ const rc = argc ? [] : null;
+ if(argc){
+ const typeIds = [];
+ let offset = 1, i, n, v;
+ for(i = 0; i < argc; ++i, ++offset){
+ typeIds.push(getTypeIdById(viewU8[offset]));
+ }
+ for(i = 0; i < argc; ++i){
+ const t = typeIds[i];
+ if(t.getter){
+ v = viewDV[t.getter](offset, state.littleEndian);
+ offset += t.size;
+ }else{
+ n = viewDV.getInt32(offset, state.littleEndian);
+ offset += 4;
+ v = textDecoder.decode(viewU8.slice(offset, offset+n));
+ offset += n;
+ }
+ rc.push(v);
+ }
+ }
+ if(clear) viewU8[0] = 0;
+
+ return rc;
+ };
+
+
+ state.s11n.serialize = function(...args){
+ const t = performance.now();
+ if(args.length){
+
+ const typeIds = [];
+ let i = 0, offset = 1;
+ viewU8[0] = args.length & 0xff ;
+ for(; i < args.length; ++i, ++offset){
+
+ typeIds.push(getTypeId(args[i]));
+ viewU8[offset] = typeIds[i].id;
+ }
+ for(i = 0; i < args.length; ++i) {
+
+ const t = typeIds[i];
+ if(t.setter){
+ viewDV[t.setter](offset, args[i], state.littleEndian);
+ offset += t.size;
+ }else{
+ const s = textEncoder.encode(args[i]);
+ viewDV.setInt32(offset, s.byteLength, state.littleEndian);
+ offset += 4;
+ viewU8.set(s, offset);
+ offset += s.byteLength;
+ }
+ }
+
+ }else{
+ viewU8[0] = 0;
+ }
+ };
+
+
+ return state.s11n;
+};
+ opfsVfs.initS11n = initS11n;
+
+
+ opfsVfs.bindVfs = function(ioMethods, callback){
+ Object.assign(opfsVfs.ioSyncWrappers, ioMethods);
+ const thePromise = new Promise(function(promiseResolve_, promiseReject_){
+ let promiseWasRejected = undefined;
+ const promiseReject = (err)=>{
+ promiseWasRejected = true;
+ opfsVfs.dispose();
+ return promiseReject_(err);
+ };
+ const promiseResolve = ()=>{
+ try{
+ callback(sqlite3, opfsVfs);
+ }catch(e){
+ return promiseReject(e);
+ }
+ promiseWasRejected = false;
+ return promiseResolve_(sqlite3);
+ };
+ const options = opfsUtil.options;
+ const proxyUri = options.proxyUri +(
+ (options.proxyUri.indexOf('?')<0) ? '?' : '&'
+ )+'vfs='+vfsName;
+
+ const W = opfsVfs.worker =
+ new Worker(proxyUri);
+ let zombieTimer = setTimeout(()=>{
+
+ if(undefined===promiseWasRejected){
+ promiseReject(
+ new Error("Timeout while waiting for OPFS async proxy worker.")
+ );
+ }
+ }, 4000);
+ W._originalOnError = W.onerror ;
+ W.onerror = function(err){
+
+
+ error("Error initializing OPFS asyncer:",err);
+ promiseReject(new Error("Loading OPFS async Worker failed for unknown reasons."));
+ };
+
+ const opRun = opfsVfs.opRun;
+
+ const sanityCheck = function(){
+ const scope = wasm.scopedAllocPush();
+ const sq3File = new capi.sqlite3_file();
+ try{
+ const fid = sq3File.pointer;
+ const openFlags = capi.SQLITE_OPEN_CREATE
+ | capi.SQLITE_OPEN_READWRITE
+
+ | capi.SQLITE_OPEN_MAIN_DB;
+ const pOut = wasm.scopedAlloc(8);
+ const dbFile = "/sanity/check/file"+randomFilename(8);
+ const zDbFile = wasm.scopedAllocCString(dbFile);
+ let rc;
+ state.s11n.serialize("This is ä string.");
+ rc = state.s11n.deserialize();
+ log("deserialize() says:",rc);
+ if("This is ä string."!==rc[0]) toss("String d13n error.");
+ opfsVfs.vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut);
+ rc = wasm.peek(pOut,'i32');
+ log("xAccess(",dbFile,") exists ?=",rc);
+ rc = opfsVfs.vfsSyncWrappers.xOpen(opfsVfs.pointer, zDbFile,
+ fid, openFlags, pOut);
+ log("open rc =",rc,"state.sabOPView[xOpen] =",
+ state.sabOPView[state.opIds.xOpen]);
+ if(0!==rc){
+ error("open failed with code",rc);
+ return;
+ }
+ opfsVfs.vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut);
+ rc = wasm.peek(pOut,'i32');
+ if(!rc) toss("xAccess() failed to detect file.");
+ rc = opfsVfs.ioSyncWrappers.xSync(sq3File.pointer, 0);
+ if(rc) toss('sync failed w/ rc',rc);
+ rc = opfsVfs.ioSyncWrappers.xTruncate(sq3File.pointer, 1024);
+ if(rc) toss('truncate failed w/ rc',rc);
+ wasm.poke(pOut,0,'i64');
+ rc = opfsVfs.ioSyncWrappers.xFileSize(sq3File.pointer, pOut);
+ if(rc) toss('xFileSize failed w/ rc',rc);
+ log("xFileSize says:",wasm.peek(pOut, 'i64'));
+ rc = opfsVfs.ioSyncWrappers.xWrite(sq3File.pointer, zDbFile, 10, 1);
+ if(rc) toss("xWrite() failed!");
+ const readBuf = wasm.scopedAlloc(16);
+ rc = opfsVfs.ioSyncWrappers.xRead(sq3File.pointer, readBuf, 6, 2);
+ wasm.poke(readBuf+6,0);
+ let jRead = wasm.cstrToJs(readBuf);
+ log("xRead() got:",jRead);
+ if("sanity"!==jRead) toss("Unexpected xRead() value.");
+ if(opfsVfs.vfsSyncWrappers.xSleep){
+ log("xSleep()ing before close()ing...");
+ opfsVfs.vfsSyncWrappers.xSleep(opfsVfs.pointer,2000);
+ log("waking up from xSleep()");
+ }
+ rc = opfsVfs.ioSyncWrappers.xClose(fid);
+ log("xClose rc =",rc,"sabOPView =",state.sabOPView);
+ log("Deleting file:",dbFile);
+ opfsVfs.vfsSyncWrappers.xDelete(opfsVfs.pointer, zDbFile, 0x1234);
+ opfsVfs.vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut);
+ rc = wasm.peek(pOut,'i32');
+ if(rc) toss("Expecting 0 from xAccess(",dbFile,") after xDelete().");
+ warn("End of OPFS sanity checks.");
+ }finally{
+ sq3File.dispose();
+ wasm.scopedAllocPop(scope);
+ }
+ };
+
+ W.onmessage = function({data}){
+
+ switch(data.type){
+ case 'opfs-unavailable':
+
+ promiseReject(new Error(data.payload.join(' ')));
+ break;
+ case 'opfs-async-loaded':
+
+ delete state.vfs;
+ W.postMessage({type: 'opfs-async-init', args: util.nu(state)});
+ break;
+ case 'opfs-async-inited': {
+
+ if(true===promiseWasRejected){
+ break ;
+ }
+ clearTimeout(zombieTimer);
+ zombieTimer = null;
+ try {
+ sqlite3.vfs.installVfs({
+ io: {struct: opfsVfs.ioMethods, methods: opfsVfs.ioSyncWrappers},
+ vfs: {struct: opfsVfs, methods: opfsVfs.vfsSyncWrappers}
+ });
+ state.sabOPView = new Int32Array(state.sabOP);
+ state.sabFileBufView = new Uint8Array(state.sabIO, 0, state.fileBufferSize);
+ state.sabS11nView = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize);
+ opfsVfs.initS11n();
+ delete opfsVfs.initS11n;
+ if(options.sanityChecks){
+ warn("Running sanity checks because of opfs-sanity-check URL arg...");
+ sanityCheck();
+ }
+ if(opfsUtil.thisThreadHasOPFS()){
+ opfsUtil.getRootDir().then((d)=>{
+ W.onerror = W._originalOnError;
+ delete W._originalOnError;
+ log("End of OPFS sqlite3_vfs setup.", opfsVfs);
+ promiseResolve();
+ }).catch(promiseReject);
+ }else{
+ promiseResolve();
+ }
+ }catch(e){
+ error(e);
+ promiseReject(e);
+ }
+ break;
+ }
+ case 'debug':
+ warn("debug message from worker:",data);
+ break;
+ default: {
+ const errMsg = (
+ "Unexpected message from the OPFS async worker: " +
+ JSON.stringify(data)
+ );
+ error(errMsg);
+ promiseReject(new Error(errMsg));
+ break;
+ }
+ }
+ };
+ });
+ return thePromise;
+ };
+
+ return state;
+ };
+
+});
+
+'use strict';
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+ if( !sqlite3.opfs || sqlite3.config.disable?.vfs?.opfs ){
+ return;
+ }
+ const util = sqlite3.util,
+ opfsUtil = sqlite3.opfs || sqlite3.util.toss("Missing sqlite3.opfs");
+
+const installOpfsVfs = async function(options){
+ options = opfsUtil.initOptions('opfs',options);
+ if( !options ) return sqlite3;
+ const capi = sqlite3.capi,
+ state = opfsUtil.createVfsState(),
+ opfsVfs = state.vfs,
+ metrics = opfsVfs.metrics.counters,
+ mTimeStart = opfsVfs.mTimeStart,
+ mTimeEnd = opfsVfs.mTimeEnd,
+ opRun = opfsVfs.opRun,
+ debug = (...args)=>sqlite3.config.debug("opfs:",...args),
+ warn = (...args)=>sqlite3.config.warn("opfs:",...args),
+ __openFiles = opfsVfs.__openFiles;
+
+
+
+ return opfsVfs.bindVfs(util.nu({
+ xLock: function(pFile,lockType){
+ mTimeStart('xLock');
+ ++metrics.xLock.count;
+ const f = __openFiles[pFile];
+ let rc = 0;
+
+ if( f.lockType ) {
+ f.lockType = lockType;
+ }else{
+ rc = opRun('xLock', pFile, lockType);
+ if( 0===rc ) f.lockType = lockType;
+ }
+ mTimeEnd();
+ return rc;
+ },
+ xUnlock: function(pFile,lockType){
+ mTimeStart('xUnlock');
+ ++metrics.xUnlock.count;
+ const f = __openFiles[pFile];
+ let rc = 0;
+ if( capi.SQLITE_LOCK_NONE === lockType
+ && f.lockType ){
+ rc = opRun('xUnlock', pFile, lockType);
+ }
+ if( 0===rc ) f.lockType = lockType;
+ mTimeEnd();
+ return rc;
+ }
+ }), function(sqlite3, vfs){
+
+ if(sqlite3.oo1){
+ const OpfsDb = function(...args){
+ const opt = sqlite3.oo1.DB.dbCtorHelper.normalizeArgs(...args);
+ opt.vfs = vfs.$zName;
+ sqlite3.oo1.DB.dbCtorHelper.call(this, opt);
+ };
+ OpfsDb.prototype = Object.create(sqlite3.oo1.DB.prototype);
+ sqlite3.oo1.OpfsDb = OpfsDb;
+ OpfsDb.importDb = opfsUtil.importDb;
+ if( true ){
+
+ sqlite3.oo1.DB.dbCtorHelper.setVfsPostOpenCallback(
+ opfsVfs.pointer,
+ function(oo1Db, sqlite3){
+
+ sqlite3.capi.sqlite3_busy_timeout(oo1Db, 10000);
+ }
+ );
+ }
+ }
+ });
+};
+globalThis.sqlite3ApiBootstrap.initializersAsync.push(async (sqlite3)=>{
+ return installOpfsVfs().catch((e)=>{
+ sqlite3.config.warn("Ignoring inability to install 'opfs' sqlite3_vfs:",e);
+ })
+});
+});
+
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+ 'use strict';
+ if( sqlite3.config.disable?.vfs?.['opfs-sahpool'] ){
+ return;
+ }
+
+ const toss = sqlite3.util.toss;
+ const toss3 = sqlite3.util.toss3;
+ const initPromises = Object.create(null) ;
+ const capi = sqlite3.capi;
+ const util = sqlite3.util;
+ const wasm = sqlite3.wasm;
+
+ const SECTOR_SIZE = 4096;
+ const HEADER_MAX_PATH_SIZE = 512;
+ const HEADER_FLAGS_SIZE = 4;
+ const HEADER_DIGEST_SIZE = 8;
+ const HEADER_CORPUS_SIZE = HEADER_MAX_PATH_SIZE + HEADER_FLAGS_SIZE;
+ const HEADER_OFFSET_FLAGS = HEADER_MAX_PATH_SIZE;
+ const HEADER_OFFSET_DIGEST = HEADER_CORPUS_SIZE;
+ const HEADER_OFFSET_DATA = SECTOR_SIZE;
+
+ const PERSISTENT_FILE_TYPES =
+ capi.SQLITE_OPEN_MAIN_DB |
+ capi.SQLITE_OPEN_MAIN_JOURNAL |
+ capi.SQLITE_OPEN_SUPER_JOURNAL |
+ capi.SQLITE_OPEN_WAL;
+ const FLAG_COMPUTE_DIGEST_V2 = capi.SQLITE_OPEN_MEMORY
+ ;
+
+
+ const OPAQUE_DIR_NAME = ".opaque";
+
+
+ const getRandomName = ()=>Math.random().toString(36).slice(2);
+
+ const textDecoder = new TextDecoder();
+ const textEncoder = new TextEncoder();
+
+ const optionDefaults = Object.assign(Object.create(null),{
+ name: 'opfs-sahpool',
+ directory: undefined ,
+ initialCapacity: 6,
+ clearOnInit: false,
+
+ verbosity: 2,
+ forceReinitIfPreviouslyFailed: false
+ });
+
+
+ const loggers = [
+ sqlite3.config.error,
+ sqlite3.config.warn,
+ sqlite3.config.log
+ ];
+ const log = sqlite3.config.log;
+ const warn = sqlite3.config.warn;
+ const error = sqlite3.config.error;
+
+
+ const __mapVfsToPool = new Map();
+ const getPoolForVfs = (pVfs)=>__mapVfsToPool.get(pVfs);
+ const setPoolForVfs = (pVfs,pool)=>{
+ if(pool) __mapVfsToPool.set(pVfs, pool);
+ else __mapVfsToPool.delete(pVfs);
+ };
+
+ const __mapSqlite3File = new Map();
+ const getPoolForPFile = (pFile)=>__mapSqlite3File.get(pFile);
+ const setPoolForPFile = (pFile,pool)=>{
+ if(pool) __mapSqlite3File.set(pFile, pool);
+ else __mapSqlite3File.delete(pFile);
+ };
+
+
+ const ioMethods = {
+ xCheckReservedLock: function(pFile,pOut){
+ const pool = getPoolForPFile(pFile);
+ pool.log('xCheckReservedLock');
+ pool.storeErr();
+ wasm.poke32(pOut, 1);
+ return 0;
+ },
+ xClose: function(pFile){
+ const pool = getPoolForPFile(pFile);
+ pool.storeErr();
+ const file = pool.getOFileForS3File(pFile);
+ if(file) {
+ try{
+ pool.log(`xClose ${file.path}`);
+ pool.mapS3FileToOFile(pFile, false);
+ file.sah.flush();
+ if(file.flags & capi.SQLITE_OPEN_DELETEONCLOSE){
+ pool.deletePath(file.path);
+ }
+ }catch(e){
+ return pool.storeErr(e, capi.SQLITE_IOERR);
+ }
+ }
+ return 0;
+ },
+ xDeviceCharacteristics: function(pFile){
+ return capi.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
+ },
+ xFileControl: function(pFile, opId, pArg){
+ return capi.SQLITE_NOTFOUND;
+ },
+ xFileSize: function(pFile,pSz64){
+ const pool = getPoolForPFile(pFile);
+ pool.log(`xFileSize`);
+ const file = pool.getOFileForS3File(pFile);
+ const size = file.sah.getSize() - HEADER_OFFSET_DATA;
+
+ wasm.poke64(pSz64, BigInt(size));
+ return 0;
+ },
+ xLock: function(pFile,lockType){
+ const pool = getPoolForPFile(pFile);
+ pool.log(`xLock ${lockType}`);
+ pool.storeErr();
+ const file = pool.getOFileForS3File(pFile);
+ file.lockType = lockType;
+ return 0;
+ },
+ xRead: function(pFile,pDest,n,offset64){
+ const pool = getPoolForPFile(pFile);
+ pool.storeErr();
+ const file = pool.getOFileForS3File(pFile);
+ pool.log(`xRead ${file.path} ${n} @ ${offset64}`);
+ try {
+ const nRead = file.sah.read(
+ wasm.heap8u().subarray(Number(pDest), Number(pDest)+n),
+ {at: HEADER_OFFSET_DATA + Number(offset64)}
+ );
+ if(nRead < n){
+ wasm.heap8u().fill(0, Number(pDest) + nRead, Number(pDest) + n);
+ return capi.SQLITE_IOERR_SHORT_READ;
+ }
+ return 0;
+ }catch(e){
+ return pool.storeErr(e, capi.SQLITE_IOERR);
+ }
+ },
+ xSectorSize: function(pFile){
+ return SECTOR_SIZE;
+ },
+ xSync: function(pFile,flags){
+ const pool = getPoolForPFile(pFile);
+ pool.log(`xSync ${flags}`);
+ pool.storeErr();
+ const file = pool.getOFileForS3File(pFile);
+
+ try{
+ file.sah.flush();
+ return 0;
+ }catch(e){
+ return pool.storeErr(e, capi.SQLITE_IOERR);
+ }
+ },
+ xTruncate: function(pFile,sz64){
+ const pool = getPoolForPFile(pFile);
+ pool.log(`xTruncate ${sz64}`);
+ pool.storeErr();
+ const file = pool.getOFileForS3File(pFile);
+
+ try{
+ file.sah.truncate(HEADER_OFFSET_DATA + Number(sz64));
+ return 0;
+ }catch(e){
+ return pool.storeErr(e, capi.SQLITE_IOERR);
+ }
+ },
+ xUnlock: function(pFile,lockType){
+ const pool = getPoolForPFile(pFile);
+ pool.log('xUnlock');
+ const file = pool.getOFileForS3File(pFile);
+ file.lockType = lockType;
+ return 0;
+ },
+ xWrite: function(pFile,pSrc,n,offset64){
+ const pool = getPoolForPFile(pFile);
+ pool.storeErr();
+ const file = pool.getOFileForS3File(pFile);
+ pool.log(`xWrite ${file.path} ${n} ${offset64}`);
+ try{
+ const nBytes = file.sah.write(
+ wasm.heap8u().subarray(Number(pSrc), Number(pSrc)+n),
+ { at: HEADER_OFFSET_DATA + Number(offset64) }
+ );
+ return n===nBytes ? 0 : toss("Unknown write() failure.");
+ }catch(e){
+ return pool.storeErr(e, capi.SQLITE_IOERR);
+ }
+ }
+ };
+
+ const opfsIoMethods = new capi.sqlite3_io_methods();
+ opfsIoMethods.$iVersion = 1;
+ sqlite3.vfs.installVfs({
+ io: {struct: opfsIoMethods, methods: ioMethods}
+ });
+
+
+ const vfsMethods = {
+ xAccess: function(pVfs,zName,flags,pOut){
+
+ const pool = getPoolForVfs(pVfs);
+ pool.storeErr();
+ try{
+ const name = pool.getPath(zName);
+ wasm.poke32(pOut, pool.hasFilename(name) ? 1 : 0);
+ }catch(e){
+
+ wasm.poke32(pOut, 0);
+ }
+ return 0;
+ },
+ xCurrentTime: function(pVfs,pOut){
+ wasm.poke(pOut, 2440587.5 + (new Date().getTime()/86400000),
+ 'double');
+ return 0;
+ },
+ xCurrentTimeInt64: function(pVfs,pOut){
+ wasm.poke(pOut, (2440587.5 * 86400000) + new Date().getTime(),
+ 'i64');
+ return 0;
+ },
+ xDelete: function(pVfs, zName, doSyncDir){
+ const pool = getPoolForVfs(pVfs);
+ pool.log(`xDelete ${wasm.cstrToJs(zName)}`);
+ pool.storeErr();
+ try{
+ pool.deletePath(pool.getPath(zName));
+ return 0;
+ }catch(e){
+ pool.storeErr(e);
+ return capi.SQLITE_IOERR_DELETE;
+ }
+ },
+ xFullPathname: function(pVfs,zName,nOut,pOut){
+
+
+ const i = wasm.cstrncpy(pOut, zName, nOut);
+ return i<nOut ? 0 : capi.SQLITE_CANTOPEN;
+ },
+ xGetLastError: function(pVfs,nOut,pOut){
+ const pool = getPoolForVfs(pVfs);
+ const e = pool.popErr();
+ pool.log(`xGetLastError ${nOut} e =`,e);
+ if(e){
+ const scope = wasm.scopedAllocPush();
+ try{
+ const [cMsg, n] = wasm.scopedAllocCString(e.message, true);
+ wasm.cstrncpy(pOut, cMsg, nOut);
+ if(n > nOut) wasm.poke8(wasm.ptr.add(pOut,nOut,-1), 0);
+ }catch(e){
+ return capi.SQLITE_NOMEM;
+ }finally{
+ wasm.scopedAllocPop(scope);
+ }
+ }
+ return e ? (e.sqlite3Rc || capi.SQLITE_IOERR) : 0;
+ },
+
+ xOpen: function f(pVfs, zName, pFile, flags, pOutFlags){
+ const pool = getPoolForVfs(pVfs);
+ try{
+ flags &= ~FLAG_COMPUTE_DIGEST_V2;
+ pool.log(`xOpen ${wasm.cstrToJs(zName)} ${flags}`);
+
+ const path = (zName && wasm.peek8(zName))
+ ? pool.getPath(zName)
+ : getRandomName();
+ let sah = pool.getSAHForPath(path);
+ if(!sah && (flags & capi.SQLITE_OPEN_CREATE)) {
+
+ if(pool.getFileCount() < pool.getCapacity()) {
+
+ sah = pool.nextAvailableSAH();
+ pool.setAssociatedPath(sah, path, flags);
+ }else{
+
+ toss('SAH pool is full. Cannot create file',path);
+ }
+ }
+ if(!sah){
+ toss('file not found:',path);
+ }
+
+
+ const file = {path, flags, sah};
+ pool.mapS3FileToOFile(pFile, file);
+ file.lockType = capi.SQLITE_LOCK_NONE;
+ const sq3File = new capi.sqlite3_file(pFile);
+ sq3File.$pMethods = opfsIoMethods.pointer;
+ sq3File.dispose();
+ wasm.poke32(pOutFlags, flags);
+ return 0;
+ }catch(e){
+ pool.storeErr(e);
+ return capi.SQLITE_CANTOPEN;
+ }
+ }
+ };
+
+
+ const createOpfsVfs = function(vfsName){
+ if( sqlite3.capi.sqlite3_vfs_find(vfsName)){
+ toss3("VFS name is already registered:", vfsName);
+ }
+ const opfsVfs = new capi.sqlite3_vfs();
+
+ const pDVfs = capi.sqlite3_vfs_find(null);
+ const dVfs = pDVfs
+ ? new capi.sqlite3_vfs(pDVfs)
+ : null ;
+ opfsVfs.$iVersion = 2;
+ opfsVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof;
+ opfsVfs.$mxPathname = HEADER_MAX_PATH_SIZE;
+ opfsVfs.addOnDispose(
+ opfsVfs.$zName = wasm.allocCString(vfsName),
+ ()=>setPoolForVfs(opfsVfs.pointer, 0)
+ );
+
+ if(dVfs){
+
+ opfsVfs.$xRandomness = dVfs.$xRandomness;
+ opfsVfs.$xSleep = dVfs.$xSleep;
+ dVfs.dispose();
+ }
+ if(!opfsVfs.$xRandomness && !vfsMethods.xRandomness){
+
+ vfsMethods.xRandomness = function(pVfs, nOut, pOut){
+ const heap = wasm.heap8u();
+ let i = 0;
+ const npOut = Number(pOut);
+ for(; i < nOut; ++i) heap[npOut + i] = (Math.random()*255000) & 0xFF;
+ return i;
+ };
+ }
+ if(!opfsVfs.$xSleep && !vfsMethods.xSleep){
+ vfsMethods.xSleep = (pVfs,ms)=>0;
+ }
+ sqlite3.vfs.installVfs({
+ vfs: {struct: opfsVfs, methods: vfsMethods}
+ });
+ return opfsVfs;
+ };
+
+
+ class OpfsSAHPool {
+
+ vfsDir;
+
+ #dhVfsRoot;
+
+ #dhOpaque;
+
+ #dhVfsParent;
+
+ #mapSAHToName = new Map();
+
+ #mapFilenameToSAH = new Map();
+
+ #availableSAH = new Set();
+
+ #mapS3FileToOFile_ = new Map();
+
+
+
+
+ #apBody = new Uint8Array(HEADER_CORPUS_SIZE);
+
+ #dvBody;
+
+
+ #cVfs;
+
+
+ #verbosity;
+
+ constructor(options = Object.create(null)){
+ this.#verbosity = options.verbosity ?? optionDefaults.verbosity;
+ this.vfsName = options.name || optionDefaults.name;
+ this.#cVfs = createOpfsVfs(this.vfsName);
+ setPoolForVfs(this.#cVfs.pointer, this);
+ this.vfsDir = options.directory || ("."+this.vfsName);
+ this.#dvBody =
+ new DataView(this.#apBody.buffer, this.#apBody.byteOffset);
+ this.isReady = this
+ .reset(!!(options.clearOnInit ?? optionDefaults.clearOnInit))
+ .then(()=>{
+ if(this.$error) throw this.$error;
+ return this.getCapacity()
+ ? Promise.resolve(undefined)
+ : this.addCapacity(options.initialCapacity
+ || optionDefaults.initialCapacity);
+ });
+ }
+
+ #logImpl(level,...args){
+ if(this.#verbosity>level) loggers[level](this.vfsName+":",...args);
+ };
+ log(...args){this.#logImpl(2, ...args)};
+ warn(...args){this.#logImpl(1, ...args)};
+ error(...args){this.#logImpl(0, ...args)};
+
+ getVfs(){return this.#cVfs}
+
+
+ getCapacity(){return this.#mapSAHToName.size}
+
+
+ getFileCount(){return this.#mapFilenameToSAH.size}
+
+
+ getFileNames(){
+ const rc = [];
+ for(const n of this.#mapFilenameToSAH.keys()) rc.push(n);
+ return rc;
+ }
+
+
+ async addCapacity(n){
+ for(let i = 0; i < n; ++i){
+ const name = getRandomName();
+ const h = await this.#dhOpaque.getFileHandle(name, {create:true});
+ const ah = await h.createSyncAccessHandle();
+ this.#mapSAHToName.set(ah,name);
+ this.setAssociatedPath(ah, '', 0);
+
+ }
+ return this.getCapacity();
+ }
+
+
+ async reduceCapacity(n){
+ let nRm = 0;
+ for(const ah of Array.from(this.#availableSAH)){
+ if(nRm === n || this.getFileCount() === this.getCapacity()){
+ break;
+ }
+ const name = this.#mapSAHToName.get(ah);
+
+ ah.close();
+ await this.#dhOpaque.removeEntry(name);
+ this.#mapSAHToName.delete(ah);
+ this.#availableSAH.delete(ah);
+ ++nRm;
+ }
+ return nRm;
+ }
+
+
+ releaseAccessHandles(){
+ for(const ah of this.#mapSAHToName.keys()) ah.close();
+ this.#mapSAHToName.clear();
+ this.#mapFilenameToSAH.clear();
+ this.#availableSAH.clear();
+ }
+
+
+ async acquireAccessHandles(clearFiles=false){
+ const files = [];
+ for await (const [name,h] of this.#dhOpaque){
+ if('file'===h.kind){
+ files.push([name,h]);
+ }
+ }
+ return Promise.all(files.map(async([name,h])=>{
+ try{
+ const ah = await h.createSyncAccessHandle()
+ this.#mapSAHToName.set(ah, name);
+ if(clearFiles){
+ ah.truncate(HEADER_OFFSET_DATA);
+ this.setAssociatedPath(ah, '', 0);
+ }else{
+ const path = this.getAssociatedPath(ah);
+ if(path){
+ this.#mapFilenameToSAH.set(path, ah);
+ }else{
+ this.#availableSAH.add(ah);
+ }
+ }
+ }catch(e){
+ this.storeErr(e);
+ this.releaseAccessHandles();
+ throw e;
+ }
+ }));
+ }
+
+
+ getAssociatedPath(sah){
+ sah.read(this.#apBody, {at: 0});
+
+
+ const flags = this.#dvBody.getUint32(HEADER_OFFSET_FLAGS);
+ if(this.#apBody[0] &&
+ ((flags & capi.SQLITE_OPEN_DELETEONCLOSE) ||
+ (flags & PERSISTENT_FILE_TYPES)===0)){
+ warn(`Removing file with unexpected flags ${flags.toString(16)}`,
+ this.#apBody);
+ this.setAssociatedPath(sah, '', 0);
+ return '';
+ }
+
+ const fileDigest = new Uint32Array(HEADER_DIGEST_SIZE / 4);
+ sah.read(fileDigest, {at: HEADER_OFFSET_DIGEST});
+ const compDigest = this.computeDigest(this.#apBody, flags);
+
+ if(fileDigest.every((v,i) => v===compDigest[i])){
+
+ const pathBytes = this.#apBody.findIndex((v)=>0===v);
+ if(0===pathBytes){
+
+
+ sah.truncate(HEADER_OFFSET_DATA);
+ }
+
+ return pathBytes
+ ? textDecoder.decode(this.#apBody.subarray(0,pathBytes))
+ : '';
+ }else{
+
+ warn('Disassociating file with bad digest.');
+ this.setAssociatedPath(sah, '', 0);
+ return '';
+ }
+ }
+
+
+ setAssociatedPath(sah, path, flags){
+ const enc = textEncoder.encodeInto(path, this.#apBody);
+ if(HEADER_MAX_PATH_SIZE <= enc.written + 1){
+ toss("Path too long:",path);
+ }
+ if(path && flags){
+
+ flags |= FLAG_COMPUTE_DIGEST_V2;
+ }
+ this.#apBody.fill(0, enc.written, HEADER_MAX_PATH_SIZE);
+ this.#dvBody.setUint32(HEADER_OFFSET_FLAGS, flags);
+ const digest = this.computeDigest(this.#apBody, flags);
+
+ sah.write(this.#apBody, {at: 0});
+ sah.write(digest, {at: HEADER_OFFSET_DIGEST});
+ sah.flush();
+
+ if(path){
+ this.#mapFilenameToSAH.set(path, sah);
+ this.#availableSAH.delete(sah);
+ }else{
+
+ sah.truncate(HEADER_OFFSET_DATA);
+ this.#availableSAH.add(sah);
+ }
+ }
+
+
+ computeDigest(byteArray, fileFlags){
+ if( fileFlags & FLAG_COMPUTE_DIGEST_V2 ){
+ let h1 = 0xdeadbeef;
+ let h2 = 0x41c6ce57;
+ for(const v of byteArray){
+ h1 = Math.imul(h1 ^ v, 2654435761);
+ h2 = Math.imul(h2 ^ v, 104729);
+ }
+ return new Uint32Array([h1>>>0, h2>>>0]);
+ }else{
+
+ return new Uint32Array([0,0]);
+ }
+ }
+
+
+ async reset(clearFiles){
+ await this.isReady;
+ let h = await navigator.storage.getDirectory();
+ let prev, prevName;
+ for(const d of this.vfsDir.split('/')){
+ if(d){
+ prev = h;
+ h = await h.getDirectoryHandle(d,{create:true});
+ }
+ }
+ this.#dhVfsRoot = h;
+ this.#dhVfsParent = prev;
+ this.#dhOpaque = await this.#dhVfsRoot.getDirectoryHandle(
+ OPAQUE_DIR_NAME,{create:true}
+ );
+ this.releaseAccessHandles();
+ return this.acquireAccessHandles(clearFiles);
+ }
+
+
+ getPath(arg) {
+ if(wasm.isPtr(arg)) arg = wasm.cstrToJs(arg);
+ return ((arg instanceof URL)
+ ? arg
+ : new URL(arg, 'file://localhost/')).pathname;
+ }
+
+
+ deletePath(path) {
+ const sah = this.#mapFilenameToSAH.get(path);
+ if(sah) {
+
+ this.#mapFilenameToSAH.delete(path);
+ this.setAssociatedPath(sah, '', 0);
+ }
+ return !!sah;
+ }
+
+
+ storeErr(e,code){
+ if(e){
+ e.sqlite3Rc = code || capi.SQLITE_IOERR;
+ this.error(e);
+ }
+ this.$error = e;
+ return code;
+ }
+
+ popErr(){
+ const rc = this.$error;
+ this.$error = undefined;
+ return rc;
+ }
+
+
+ nextAvailableSAH(){
+ const [rc] = this.#availableSAH.keys();
+ return rc;
+ }
+
+
+ getOFileForS3File(pFile){
+ return this.#mapS3FileToOFile_.get(pFile);
+ }
+
+ mapS3FileToOFile(pFile,file){
+ if(file){
+ this.#mapS3FileToOFile_.set(pFile, file);
+ setPoolForPFile(pFile, this);
+ }else{
+ this.#mapS3FileToOFile_.delete(pFile);
+ setPoolForPFile(pFile, false);
+ }
+ }
+
+
+ hasFilename(name){
+ return this.#mapFilenameToSAH.has(name)
+ }
+
+
+ getSAHForPath(path){
+ return this.#mapFilenameToSAH.get(path);
+ }
+
+
+ async removeVfs(){
+ if(!this.#cVfs.pointer || !this.#dhOpaque) return false;
+ capi.sqlite3_vfs_unregister(this.#cVfs.pointer);
+ this.#cVfs.dispose();
+ delete initPromises[this.vfsName];
+ try{
+ this.releaseAccessHandles();
+ await this.#dhVfsRoot.removeEntry(OPAQUE_DIR_NAME, {recursive: true});
+ this.#dhOpaque = undefined;
+ await this.#dhVfsParent.removeEntry(
+ this.#dhVfsRoot.name, {recursive: true}
+ );
+ this.#dhVfsRoot = this.#dhVfsParent = undefined;
+ }catch(e){
+ sqlite3.config.error(this.vfsName,"removeVfs() failed with no recovery strategy:",e);
+
+ }
+ return true;
+ }
+
+
+
+ pauseVfs(){
+ if(this.#mapS3FileToOFile_.size>0){
+ sqlite3.SQLite3Error.toss(
+ capi.SQLITE_MISUSE, "Cannot pause VFS",
+ this.vfsName,"because it has opened files."
+ );
+ }
+ if(this.#mapSAHToName.size>0){
+ capi.sqlite3_vfs_unregister(this.vfsName);
+ this.releaseAccessHandles();
+ }
+ return this;
+ }
+
+
+ isPaused(){
+ return 0===this.#mapSAHToName.size;
+ }
+
+
+ async unpauseVfs(){
+ if(0===this.#mapSAHToName.size){
+ return this.acquireAccessHandles(false).
+ then(()=>capi.sqlite3_vfs_register(this.#cVfs, 0),this);
+ }
+ return this;
+ }
+
+
+ exportFile(name){
+ const sah = this.#mapFilenameToSAH.get(name) || toss("File not found:",name);
+ const n = sah.getSize() - HEADER_OFFSET_DATA;
+ const b = new Uint8Array(n>0 ? n : 0);
+ if(n>0){
+ const nRead = sah.read(b, {at: HEADER_OFFSET_DATA});
+ if(nRead != n){
+ toss("Expected to read "+n+" bytes but read "+nRead+".");
+ }
+ }
+ return b;
+ }
+
+
+ async importDbChunked(name, callback){
+ const sah = this.#mapFilenameToSAH.get(name)
+ || this.nextAvailableSAH()
+ || toss("No available handles to import to.");
+ sah.truncate(0);
+ let nWrote = 0, chunk, checkedHeader = false, err = false;
+ try{
+ while( undefined !== (chunk = await callback()) ){
+ if(chunk instanceof ArrayBuffer) chunk = new Uint8Array(chunk);
+ if( !checkedHeader && 0===nWrote && chunk.byteLength>=15 ){
+ util.affirmDbHeader(chunk);
+ checkedHeader = true;
+ }
+ sah.write(chunk, {at: HEADER_OFFSET_DATA + nWrote});
+ nWrote += chunk.byteLength;
+ }
+ if( nWrote < 512 || 0!==nWrote % 512 ){
+ toss("Input size",nWrote,"is not correct for an SQLite database.");
+ }
+ if( !checkedHeader ){
+ const header = new Uint8Array(20);
+ sah.read( header, {at: 0} );
+ util.affirmDbHeader( header );
+ }
+ sah.write(new Uint8Array([1,1]), {
+ at: HEADER_OFFSET_DATA + 18
+ });
+ }catch(e){
+ this.setAssociatedPath(sah, '', 0);
+ throw e;
+ }
+ this.setAssociatedPath(sah, name, capi.SQLITE_OPEN_MAIN_DB);
+ return nWrote;
+ }
+
+
+ importDb(name, bytes){
+ if( bytes instanceof ArrayBuffer ) bytes = new Uint8Array(bytes);
+ else if( bytes instanceof Function ) return this.importDbChunked(name, bytes);
+ const sah = this.#mapFilenameToSAH.get(name)
+ || this.nextAvailableSAH()
+ || toss("No available handles to import to.");
+ const n = bytes.byteLength;
+ if(n<512 || n%512!=0){
+ toss("Byte array size is invalid for an SQLite db.");
+ }
+ const header = "SQLite format 3";
+ for(let i = 0; i < header.length; ++i){
+ if( header.charCodeAt(i) !== bytes[i] ){
+ toss("Input does not contain an SQLite database header.");
+ }
+ }
+ const nWrote = sah.write(bytes, {at: HEADER_OFFSET_DATA});
+ if(nWrote != n){
+ this.setAssociatedPath(sah, '', 0);
+ toss("Expected to write "+n+" bytes but wrote "+nWrote+".");
+ }else{
+ sah.write(new Uint8Array([1,1]), {at: HEADER_OFFSET_DATA+18}
+ );
+ this.setAssociatedPath(sah, name, capi.SQLITE_OPEN_MAIN_DB);
+ }
+ return nWrote;
+ }
+
+ };
+
+
+
+ class OpfsSAHPoolUtil {
+
+ #p;
+
+ constructor(sahPool){
+ this.#p = sahPool;
+ this.vfsName = sahPool.vfsName;
+ }
+
+ async addCapacity(n){ return this.#p.addCapacity(n) }
+
+ async reduceCapacity(n){ return this.#p.reduceCapacity(n) }
+
+ getCapacity(){ return this.#p.getCapacity(this.#p) }
+
+ getFileCount(){ return this.#p.getFileCount() }
+ getFileNames(){ return this.#p.getFileNames() }
+
+ async reserveMinimumCapacity(min){
+ const c = this.#p.getCapacity();
+ return (c < min) ? this.#p.addCapacity(min - c) : c;
+ }
+
+ exportFile(name){ return this.#p.exportFile(name) }
+
+ importDb(name, bytes){ return this.#p.importDb(name,bytes) }
+
+ async wipeFiles(){ return this.#p.reset(true) }
+
+ unlink(filename){ return this.#p.deletePath(filename) }
+
+ async removeVfs(){ return this.#p.removeVfs() }
+
+ pauseVfs(){ this.#p.pauseVfs(); return this; }
+ async unpauseVfs(){ return this.#p.unpauseVfs().then(()=>this); }
+ isPaused(){ return this.#p.isPaused() }
+
+ };
+
+
+ const apiVersionCheck = async ()=>{
+ const dh = await navigator.storage.getDirectory();
+ const fn = '.opfs-sahpool-sync-check-'+getRandomName();
+ const fh = await dh.getFileHandle(fn, { create: true });
+ const ah = await fh.createSyncAccessHandle();
+ const close = ah.close();
+ await close;
+ await dh.removeEntry(fn);
+ if(close?.then){
+ toss("The local OPFS API is too old for opfs-sahpool:",
+ "it has an async FileSystemSyncAccessHandle.close() method.");
+ }
+ return true;
+ };
+
+
+ sqlite3.installOpfsSAHPoolVfs = async function(options=Object.create(null)){
+ options = Object.assign(Object.create(null), optionDefaults, (options||{}));
+ const vfsName = options.name;
+ if(options.$testThrowPhase1){
+ throw options.$testThrowPhase1;
+ }
+ if(initPromises[vfsName]){
+ try {
+ const p = await initPromises[vfsName];
+
+ return p;
+ }catch(e){
+
+ if( options.forceReinitIfPreviouslyFailed ){
+ delete initPromises[vfsName];
+
+ }else{
+ throw e;
+ }
+ }
+ }
+ if(!globalThis.FileSystemHandle ||
+ !globalThis.FileSystemDirectoryHandle ||
+ !globalThis.FileSystemFileHandle ||
+ !globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle ||
+ !navigator?.storage?.getDirectory){
+ return (initPromises[vfsName] = Promise.reject(new Error("Missing required OPFS APIs.")));
+ }
+
+
+ return initPromises[vfsName] = apiVersionCheck().then(async function(){
+ if(options.$testThrowPhase2){
+ throw options.$testThrowPhase2;
+ }
+ const thePool = new OpfsSAHPool(options);
+ return thePool.isReady.then(async()=>{
+
+ const poolUtil = new OpfsSAHPoolUtil(thePool);
+ if(sqlite3.oo1){
+ const oo1 = sqlite3.oo1;
+ const theVfs = thePool.getVfs();
+ const OpfsSAHPoolDb = function(...args){
+ const opt = oo1.DB.dbCtorHelper.normalizeArgs(...args);
+ opt.vfs = theVfs.$zName;
+ oo1.DB.dbCtorHelper.call(this, opt);
+ };
+ OpfsSAHPoolDb.prototype = Object.create(oo1.DB.prototype);
+ poolUtil.OpfsSAHPoolDb = OpfsSAHPoolDb;
+ }
+ thePool.log("VFS initialized.");
+ return poolUtil;
+ }).catch(async (e)=>{
+ await thePool.removeVfs().catch(()=>{});
+ throw e;
+ });
+ }).catch((err)=>{
+
+ return initPromises[vfsName] = Promise.reject(err);
+ });
+ };
+});
+
+'use strict';
+globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
+ if( !sqlite3.opfs || sqlite3.config.disable?.vfs?.['opfs-wl'] ){
+ return;
+ }
+ const util = sqlite3.util,
+ toss = sqlite3.util.toss;
+ const opfsUtil = sqlite3.opfs;
+ const vfsName = 'opfs-wl';
+
+const installOpfsWlVfs = async function(options){
+ options = opfsUtil.initOptions(vfsName,options);
+ if( !options ) return sqlite3;
+ const capi = sqlite3.capi,
+ state = opfsUtil.createVfsState(),
+ opfsVfs = state.vfs,
+ metrics = opfsVfs.metrics.counters,
+ mTimeStart = opfsVfs.mTimeStart,
+ mTimeEnd = opfsVfs.mTimeEnd,
+ opRun = opfsVfs.opRun,
+ debug = (...args)=>sqlite3.config.debug(vfsName+":",...args),
+ warn = (...args)=>sqlite3.config.warn(vfsName+":",...args),
+ __openFiles = opfsVfs.__openFiles;
+
+
+
+ return opfsVfs.bindVfs(util.nu({
+ xLock: function(pFile,lockType){
+ mTimeStart('xLock');
+
+ const f = __openFiles[pFile];
+ const rc = opRun('xLock', pFile, lockType);
+ if( !rc ) f.lockType = lockType;
+ mTimeEnd();
+ return rc;
+ },
+ xUnlock: function(pFile,lockType){
+ mTimeStart('xUnlock');
+ const f = __openFiles[pFile];
+ const rc = opRun('xUnlock', pFile, lockType);
+ if( !rc ) f.lockType = lockType;
+ mTimeEnd();
+ return rc;
+ }
+ }), function(sqlite3, vfs){
+
+ if(sqlite3.oo1){
+ const OpfsWlDb = function(...args){
+ const opt = sqlite3.oo1.DB.dbCtorHelper.normalizeArgs(...args);
+ opt.vfs = vfs.$zName;
+ sqlite3.oo1.DB.dbCtorHelper.call(this, opt);
+ };
+ OpfsWlDb.prototype = Object.create(sqlite3.oo1.DB.prototype);
+ sqlite3.oo1.OpfsWlDb = OpfsWlDb;
+ OpfsWlDb.importDb = opfsUtil.importDb;
+
+ }
+ });
+};
+globalThis.sqlite3ApiBootstrap.initializersAsync.push(async (sqlite3)=>{
+ return installOpfsWlVfs().catch((e)=>{
+ sqlite3.config.warn("Ignoring inability to install the",vfsName,"sqlite3_vfs:",e);
+ });
+});
+});
+
+try{
+
+
+
+ const bootstrapConfig = Object.assign(
+ Object.create(null),
+
+ {
+ memory: ('undefined'!==typeof wasmMemory)
+ ? wasmMemory
+ : EmscriptenModule['wasmMemory'],
+ exports: ('undefined'!==typeof wasmExports)
+ ? wasmExports
+ : (Object.prototype.hasOwnProperty.call(EmscriptenModule,'wasmExports')
+ ? EmscriptenModule['wasmExports']
+ : EmscriptenModule['asm'])
+ },
+ globalThis.sqlite3ApiBootstrap.defaultConfig,
+ globalThis.sqlite3ApiConfig || {}
+ );
+
+ sqlite3InitScriptInfo.debugModule("Bootstrapping lib config", bootstrapConfig);
+
+
+ const p = globalThis.sqlite3ApiBootstrap(bootstrapConfig);
+ delete globalThis.sqlite3ApiBootstrap;
+ return p ;
+}catch(e){
+ console.error("sqlite3ApiBootstrap() error:",e);
+ throw e;
+}
+
+
+};
+
+
+
+
+
+
+
+
+
+
+if (runtimeInitialized) {
+ moduleRtn = Module;
+} else {
+
+ moduleRtn = new Promise((resolve, reject) => {
+ readyPromiseResolve = resolve;
+ readyPromiseReject = reject;
+ });
+}
+
+
+
+
+
+ return moduleRtn;
+ };
+})();
+
+
+if (typeof exports === 'object' && typeof module === 'object') {
+ module.exports = sqlite3InitModule;
+
+
+ module.exports.default = sqlite3InitModule;
+} else if (typeof define === 'function' && define['amd'])
+ define([], () => sqlite3InitModule);
+
+
+
+(function(){
+
+
+ const originalInit = sqlite3InitModule;
+ if(!originalInit){
+ throw new Error("Expecting sqlite3InitModule to be defined by the Emscripten build.");
+ }
+
+ const sIMS = globalThis.sqlite3InitModuleState = Object.assign(Object.create(null),{
+ moduleScript: globalThis?.document?.currentScript,
+ isWorker: ('undefined' !== typeof WorkerGlobalScope),
+ location: globalThis.location,
+ urlParams: globalThis?.location?.href
+ ? new URL(globalThis.location.href).searchParams
+ : new URLSearchParams(),
+
+ wasmFilename: 'sqlite3.wasm'
+ });
+ sIMS.debugModule =
+ sIMS.urlParams.has('sqlite3.debugModule')
+ ? (...args)=>console.warn('sqlite3.debugModule:',...args)
+ : ()=>{};
+
+ if(sIMS.urlParams.has('sqlite3.dir')){
+ sIMS.sqlite3Dir = sIMS.urlParams.get('sqlite3.dir') +'/';
+ }else if(sIMS.moduleScript){
+ const li = sIMS.moduleScript.src.split('/');
+ li.pop();
+ sIMS.sqlite3Dir = li.join('/') + '/';
+ }
+
+ const sIM = globalThis.sqlite3InitModule = function ff(...args){
+
+ sIMS.emscriptenLocateFile = args[0]?.locateFile ;
+ sIMS.emscriptenInstantiateWasm = args[0]?.instantiateWasm ;
+ return originalInit(...args).then((EmscriptenModule)=>{
+ sIMS.debugModule("sqlite3InitModule() sIMS =",sIMS);
+ sIMS.debugModule("sqlite3InitModule() EmscriptenModule =",EmscriptenModule);
+ const s = EmscriptenModule.runSQLite3PostLoadInit(
+ sIMS,
+ EmscriptenModule ,
+ !!ff.__isUnderTest
+ );
+ sIMS.debugModule("sqlite3InitModule() sqlite3 =",s);
+
+
+ return s;
+ }).catch((e)=>{
+ console.error("Exception loading sqlite3 module:",e);
+ throw e;
+ });
+ };
+ sIM.ready = originalInit.ready;
+
+ if(sIMS.moduleScript){
+ let src = sIMS.moduleScript.src.split('/');
+ src.pop();
+ sIMS.scriptDir = src.join('/') + '/';
+ }
+ sIMS.debugModule('extern-post-js.c-pp.js sqlite3InitModuleState =',sIMS);
+
+
+
+
+ if (typeof exports === 'object' && typeof module === 'object'){
+ module.exports = sIM;
+ module.exports.default = sIM;
+ }else if( 'function'===typeof define && define.amd ){
+ define([], ()=>sIM);
+ }else if (typeof exports === 'object'){
+ exports["sqlite3InitModule"] = sIM;
+ }
+
+ return sIM;
+})();
diff --git a/store/agents/data-studio/template/vendor/sqlite3.wasm b/store/agents/data-studio/template/vendor/sqlite3.wasm
new file mode 100644
index 000000000..7670f326f
Binary files /dev/null and b/store/agents/data-studio/template/vendor/sqlite3.wasm differ
diff --git a/store/agents/data-studio/template/worker.js b/store/agents/data-studio/template/worker.js
new file mode 100644
index 000000000..9a8d4ba53
--- /dev/null
+++ b/store/agents/data-studio/template/worker.js
@@ -0,0 +1,136 @@
+// Executed after the pinned SQLite and core scripts in a dedicated classic Blob worker.
+// No filesystem, OPFS, origin storage, imports, extension loading, or remote query service.
+self.onmessage = async ({ data }) => {
+ let db;
+ try {
+ const C = globalThis.DataStudioCore,
+ prepared = C.prepare(data.bundle),
+ values = C.parameters(prepared.config, data.parameters),
+ qname = (s) => '"' + s.replaceAll('"', '""') + '"';
+ const sqlite = await sqlite3InitModule({
+ instantiateWasm(imports, ready) {
+ WebAssembly.instantiate(data.wasm, imports)
+ .then(({ instance, module }) => ready(instance, module))
+ .catch((error) => self.postMessage({ error: error.message }));
+ return {};
+ },
+ });
+ db = new sqlite.oo1.DB();
+ db.exec(
+ "PRAGMA hard_heap_limit=134217728; PRAGMA trusted_schema=OFF; PRAGMA temp_store=MEMORY; BEGIN",
+ );
+ for (const t of prepared.tables) {
+ db.exec(
+ "CREATE TABLE " +
+ qname(t.id) +
+ " (_record INTEGER PRIMARY KEY," +
+ t.columns
+ .map(
+ (c) =>
+ qname(c.name) +
+ " " +
+ (["text", "date"].includes(c.type)
+ ? "TEXT"
+ : c.type === "real"
+ ? "REAL"
+ : "INTEGER") +
+ (c.nullable ? "" : " NOT NULL"),
+ )
+ .join(",") +
+ (t.key ? ", UNIQUE (" + t.key.map(qname).join(",") + ")" : "") +
+ ") STRICT",
+ );
+ const stmt = db.prepare(
+ "INSERT INTO " +
+ qname(t.id) +
+ " VALUES (" +
+ Array(t.columns.length + 1)
+ .fill("?")
+ .join(",") +
+ ")",
+ );
+ try {
+ for (const row of t.rows) {
+ stmt.bind(row).stepReset();
+ }
+ } finally {
+ stmt.finalize();
+ }
+ }
+ db.exec("COMMIT; PRAGMA query_only=ON");
+ const execute = (q) => {
+ const names = C.validateSQL(data.bundle.sql[q.file], prepared.config),
+ stmt = db.prepare(data.bundle.sql[q.file]);
+ try {
+ if (!stmt.isReadOnly()) throw new Error("Query is not read-only.");
+ const columns = stmt.getColumnNames(),
+ rows = [];
+ if (names.length)
+ stmt.bind(Object.fromEntries(names.map((n) => [":" + n, values[n]])));
+ let size = 0;
+ while (stmt.step()) {
+ const row = stmt.get([]).map(C.scalar);
+ rows.push(row);
+ size += JSON.stringify(row).length;
+ if (rows.length > C.LIMITS.resultRows || size > C.LIMITS.resultBytes)
+ throw new Error(q.id + ": query result limit exceeded.");
+ }
+ return C.result(columns, rows, q);
+ } finally {
+ stmt.finalize();
+ }
+ };
+ let resultBytes = 0;
+ const results = prepared.config.queries.map((q) => {
+ const r = execute(q);
+ resultBytes += new TextEncoder().encode(JSON.stringify(r)).length;
+ if (resultBytes > C.LIMITS.totalResultBytes)
+ throw new Error("Combined results exceed 8 MiB.");
+ return r;
+ }),
+ checks = [...prepared.checks];
+ for (const q of prepared.config.checks) {
+ const r = execute(q);
+ if (
+ r.columns.length !== 1 ||
+ r.columns[0] !== "violations" ||
+ r.rows.length !== 1 ||
+ r.rows[0][0] !== 0
+ )
+ throw new Error(
+ q.description + ": expected exactly one violations=0 result.",
+ );
+ checks.push({ id: q.id, description: q.description, passed: true });
+ }
+ if (db.selectValue("PRAGMA integrity_check") !== "ok")
+ throw new Error("SQLite integrity check failed.");
+ checks.push({
+ id: "integrity",
+ description: "Browser SQLite integrity_check: ok",
+ passed: true,
+ });
+ const database = sqlite.capi.sqlite3_js_db_export(db);
+ self.postMessage(
+ {
+ report: {
+ spec: 1,
+ engine:
+ "SQLite " +
+ db.selectValue("SELECT sqlite_version()") +
+ " (browser)",
+ parameters: values,
+ results,
+ checks,
+ records: prepared.rowCount,
+ sourceBytes: prepared.sourceBytes,
+ },
+ database,
+ },
+ [database.buffer],
+ );
+ } catch (error) {
+ self.postMessage({ error: error.message });
+ } finally {
+ db?.close();
+ }
+};
diff --git a/store/agents/data-studio/test/ACCEPTANCE.md b/store/agents/data-studio/test/ACCEPTANCE.md
new file mode 100644
index 000000000..3c2c964c6
--- /dev/null
+++ b/store/agents/data-studio/test/ACCEPTANCE.md
@@ -0,0 +1,163 @@
+# Data Studio real-workflow acceptance
+
+Completed locally on 2026-09-20. Fifth package in the sequential twelve-harness
+rebuild. Both datasets are clearly labelled synthetic; no private user dataset
+was requested, uploaded or substituted. This replaces the fixed two-dimension
+dashboard with saved, typed, joined SQLite analyses and independently usable
+exports. Listing is conditional on the normal PR/CI/catalog publication gate.
+
+## Tested runtimes and commands
+
+- Node 22.23.2, native SQLite 3.51.3 (node:sqlite is experimental in Node 22).
+- Official SQLite WebAssembly 3.53.4, unmodified, archive and asset hashes checked.
+- Actual Chromium through Playwright, both the shared opaque-origin iframe and
+ the extracted project's own tokenized, restrictive-CSP loopback server.
+- Independent Python 3.12.14, stdlib CSV + Decimal + SQLite 3.53.1. Apple's older
+ Python SQLite cannot read STRICT tables: the reader reports the SQLite 3.37+
+ requirement, rather than disabling schema checks.
+
+From the repository root (Node 22.16+):
+
+```sh
+node --test store/agents/data-studio/test/*.test.mjs
+PLAYWRIGHT_MODULE=/absolute/path/to/playwright/index.mjs \
+DATA_EVIDENCE_DIR=/absolute/path/to/NEW_EVIDENCE_DIRECTORY \
+node store/agents/data-studio/test/browser.mjs
+python3 store/agents/data-studio/test/verify-exports.py /absolute/path/to/EVIDENCE_DIRECTORY
+```
+
+19 Node tests passed, including real SQLite builds/reopening, source mutation
+during a real calculation, ZIP extraction/rebuild, saved JSON restoration,
+timeout/last-good preservation, packaged initialization, missing runtime/browser
+failure, HTML escaping, data limits and actual HTTP security tests. No native
+suite is skipped. Registry/catalog/publisher checks: 433 passed before rebasing
+onto the latest main. Skill validation, package conformance, generated artifact
+and branding checks, runtime-copy consistency and diff checks passed.
+
+The package's one-stop update-verdict.sh was run through its real entry point:
+native build followed by the actual isolated browser recipe. It wrote ready=true
+only after interactions and assertions passed. Browser absence and malformed
+input tests explicitly clear readiness and retain good outputs.
+
+## Sales question, source trace and substantive revisions
+
+26 transaction lines joined to 6 uniquely keyed products. Leading-zero line and
+product IDs remain text. Dates, status, region, quantities and USD decimal
+storage are explicit. Original source strings and CSV record numbers survive.
+Net sales = quantity × unit price − discount − refund; cancelled lines excluded.
+The method states sale-date attribution, no profit/tax/currency-conversion
+claim, and the explicit no-recorded-sales-as-zero rule for month comparisons.
+
+The default January/February analysis produced:
+
+| Result | January | February | Change |
+| --- | ---: | ---: | ---: |
+| Net sales, USD | 4,604.50 | 4,366.50 | -238.00 |
+| Creative | 1,232.00 | 1,968.00 | +736.00 |
+| Home | 1,653.50 | 1,275.50 | -378.00 |
+| Outdoor | 1,719.00 | 1,123.00 | -596.00 |
+
+Category changes sum to -238.00. Growth is -5.168856553…%, displayed as -5.2%.
+24 completed lines are in the selected months; this is not an order count.
+Outdoor drilldown has 8 actual joined source lines. Keyboard activation, raw
+record opening and filtering West (January 2,583.50 USD) were exercised.
+
+Two independent browser revisions were made and retained through saving:
+
+1. Monthly SQL was changed to include only lines with quantity >= 15. January
+ becomes 2,229.50 USD / 6 lines and February 2,445.50 USD / 6 lines. March has no
+ matching lines and is absent, not imputed to zero. The edited explanation is
+ visibly marked for review.
+2. The first line's unit price changed from 38.00 to 40.00 USD, quantity 12.
+ Default January becomes 4,628.50 and the change becomes -262.00 USD. This line
+ is outside the revised monthly query, so that query's values stay unchanged.
+
+Saved JSON preserved source data, SQL revision, applied controls and review
+notes. The browser-produced SQLite file was opened independently in Node and
+Python, including the actual line_id='00001' / price=4000 stored cents. Python
+CSV/Decimal calculations independently reproduced the totals and exported CSV.
+The JSON was restored to new source files and rebuilt; its standalone viewer
+reproduced the browser revision. The original built ZIP was also extracted,
+rebuilt and opened independently; it correctly retained the original -238.00
+result rather than pretending to contain later browser edits.
+
+Original built source revision:
+b6c6205a20863dae8b548ba3c25598e9f005df2b630aeaecdd5962a7b43f3d11.
+Native build: 9 checks; browser calculation: 7 checks plus initial exact
+native/browser result comparison.
+
+## Independent delivery question
+
+18 shipments joined to 3 routes, a different schema/question. On-time rate uses
+delivered shipments as its denominator. Missing or future delivery dates stay
+open, not failed/zero observations. As-of and region controls affect the query.
+
+At 2026-04-30: 18 shipments, 15 delivered, 3 open, 7 on time: 46.7%. Route rates
+are Metro 100%, Coastal 40%, Highlands 0%. Source links include original missing
+delivery strings. The schema's empty-date-to-null rule is visible.
+
+Changing shipment '0017' from missing to delivery on 2026-04-19 produced 16
+delivered, 2 open and 8/16 = 50.0% on time. This is not the now-unequally-weighted
+average of route percentages. Saved project, database and HTML exports retained
+that revision. Python independently read the downloaded database and CSVs and
+reproduced the counts/rate. An earlier as-of date with no delivered shipments
+produced missing rates in all three chart categories, not 0%.
+
+Original source revision:
+8d75488a06c2c671b2c007c29142acb3a7555381c0c3016f683e0421cc6af7d0.
+Native build: 8 checks; browser calculation: 6 plus initial native comparison.
+
+## Practical-size run
+
+An additional generated load case contained 50,000 transaction lines plus the
+6-product catalog: 3,800,269 source CSV bytes. Native import, four queries,
+SQLite read-only reopen, 9 checks and portable ZIP generation completed in
+11.33 seconds on this machine. Both month totals were exactly 190,000,000 cents;
+all 50,000 original line IDs remained in the database. The detail SQL explicitly
+limited its ordered result to 10,000 rows and disclosed that limit.
+
+The actual standalone browser rebuilt and matched this result in 2.59 seconds,
+then paged rows 1–50 and 51–100 of the 10,000-row query with no page errors.
+These are single-machine measurements, not universal latency or capacity promises.
+
+## Failure cases, UI and remaining limits
+
+Duplicate product keys, unmatched foreign keys, missing required prices,
+malformed dates/numbers/CSV, undeclared parameters, unsafe/multiple/write SQL,
+out-of-range integers, BLOB results, bad reconciliation queries, project hash
+tampering, runtime tampering and source symlinks are rejected. A changed source
+during the actual calculation blocks publication. A deliberately nonterminating
+native query hits the 20-second budget and leaves the previous ZIP byte-identical.
+
+Browser acceptance exercised successful replacement, duplicate rejection,
+invalid SQL, corrupt project JSON, every download type, empty results, missing
+growth, missing rate bars, 390px layout, no external HTTP requests, and four
+independent contexts. A nonterminating browser query was both cancelled and
+allowed to hit the 20-second budget; the page continued rendering and the last
+good result remained intact. Source CSV download is byte-compared with the input.
+
+The exported HTML is inert and escapes labels/notes. Result CSV protects against
+formula-looking text with an apostrophe; null becomes an empty CSV field.
+SQLite and project/result JSON preserve exact types, text and nulls. Source
+CSV exports are original, untrusted text. Exported projects contain raw inputs;
+no redaction/encryption or automatic sharing is implied.
+
+Limits: 8 files, 50 columns each, 100,000 total records, 1,000,000 cells, 6 MiB
+CSV combined, 12 queries, 10,000 rows / 4 MiB per result, 8 MiB combined results,
+128 MiB SQLite heap and 20 seconds per calculation. No Excel workbook import,
+distributed database, extension/file SQL or arbitrary SQL correctness guarantee.
+Record-link existence and reconciliation checks do not prove causal/business
+interpretation. Users still need to confirm domain assumptions and units.
+
+## Retained local evidence
+
+Root: /private/tmp/harness-data-workflows.zEZK7d/.
+release-browser/ and release-final/ contain actual saved JSON, CSV, HTML,
+SQLite and ZIP downloads, restored/extracted workspaces, desktop/mobile images
+and browser receipts. release-browser/sales/.harness/ contains the packaged
+readiness proof and loaded-file hashes. scale-50000/ contains the large-case
+database, full source, build/browser receipts and screenshot. Three store JPEGs
+are direct captures of real working pages and were visually inspected.
+
+Earlier probe/acceptance folders retain debugging evidence, not release claims.
+No physical hardware or private dataset validation was claimed.
diff --git a/store/agents/data-studio/test/analysis.test.mjs b/store/agents/data-studio/test/analysis.test.mjs
new file mode 100644
index 000000000..13753227b
--- /dev/null
+++ b/store/agents/data-studio/test/analysis.test.mjs
@@ -0,0 +1,391 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ readFile,
+ mkdtemp,
+ cp,
+ writeFile,
+ mkdir,
+ symlink,
+ readdir,
+} from "node:fs/promises";
+import { join, dirname } from "node:path";
+import { tmpdir } from "node:os";
+import { fileURLToPath } from "node:url";
+import { DatabaseSync } from "node:sqlite";
+import { spawn } from "node:child_process";
+import { once } from "node:events";
+import { runAnalysis, revision } from "../template/tools/engine-node.mjs";
+import { build, loadBundle } from "../template/tools/build.mjs";
+import { restore } from "../template/tools/restore.mjs";
+import { sha } from "../template/tools/files.mjs";
+import { unzip } from "../template/tools/archive.mjs";
+import "../template/core.js";
+const C = globalThis.DataStudioCore,
+ root = fileURLToPath(new URL("../", import.meta.url)),
+ template = join(root, "template");
+const clone = structuredClone;
+async function bundle(where = template) {
+ return (await loadBundle(where)).bundle;
+}
+async function workspace(prefix = "data-workflow-") {
+ const dir = await mkdtemp(join(tmpdir(), prefix));
+ await cp(template, dir, { recursive: true });
+ return dir;
+}
+const result = (r, id) => r.results.find((r) => r.id === id);
+
+test("report exports escape data and result row limits are enforced", async () => {
+ const b = await bundle();
+ b.config.title = "<img src=x onerror=alert(1)>";
+ const report = runAnalysis(b),
+ html = globalThis.DataStudioReport(
+ b,
+ report,
+ "</pre><script>alert(1)</script>",
+ );
+ assert.ok(!html.includes("<img"));
+ assert.ok(!html.includes("<script"));
+ assert.ok(html.includes("&lt;script&gt;"));
+ assert.ok(html.includes("Synthetic example data"));
+ assert.throws(
+ () =>
+ C.result(
+ ["n"],
+ Array.from({ length: 10001 }, () => [1]),
+ { kind: "table" },
+ ),
+ /10,000/,
+ );
+ assert.throws(() => C.parseCSV("a\n" + "x".repeat(4097)), /4096/);
+});
+
+test("a source edited during the real calculation cannot publish stale results", async () => {
+ const w = await workspace();
+ await build(w);
+ const before = sha(await readFile(join(w, "output/project.zip")));
+ const calculate = join(w, "tools/calculate.mjs");
+ await writeFile(
+ calculate,
+ "await new Promise(r=>setTimeout(r,350));\n" +
+ (await readFile(calculate, "utf8")),
+ );
+ const child = spawn(process.execPath, [join(w, "tools/build.mjs"), w], {
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let stderr = "";
+ child.stderr.on("data", (b) => (stderr += b));
+ child.stdout.resume();
+ const closed = once(child, "close");
+ let inputReady = false;
+ for (let i = 0; i < 150; i++) {
+ for (const name of await readdir(join(w, ".harness"))) {
+ if (!name.startsWith("data-") || name.endsWith(".lock")) continue;
+ try {
+ await readFile(join(w, ".harness", name, "input.json"));
+ inputReady = true;
+ } catch {}
+ }
+ if (inputReady) break;
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ assert.equal(inputReady, true);
+ const products = join(w, "sources/products.csv");
+ await writeFile(
+ products,
+ (await readFile(products, "utf8")) + "099,New item,Creative\n",
+ );
+ assert.equal((await closed)[0], 1, stderr);
+ assert.match(stderr, /Source changed during build/);
+ assert.equal(sha(await readFile(join(w, "output/project.zip"))), before);
+});
+
+test("CSV preserves text IDs, multiline records, quotes and BOM; rejects damaged records", () => {
+ const p = C.parseCSV(
+ '\uFEFFid,label,value\r\n001,"North, coast",-2.50\r\n002,"A ""quoted""\nteam",0\r\n',
+ );
+ assert.deepEqual(p.headers, ["id", "label", "value"]);
+ assert.deepEqual(p.records, [
+ ["001", "North, coast", "-2.50"],
+ ["002", 'A "quoted"\nteam', "0"],
+ ]);
+ for (const csv of [
+ "",
+ "a,a\n1,2",
+ "a,b\n1",
+ "a,b\n1,2,3",
+ 'a\n"unclosed',
+ 'a\n"closed"x',
+ "a\n\n",
+ "a\n1\n\n",
+ " a\nx",
+ "a\nx\0",
+ ])
+ assert.throws(() => C.parseCSV(csv), undefined, csv);
+});
+test("explicit number/date rules retain missing and reject coercion or hidden rounding", () => {
+ const money = { type: "decimal", scale: 2, nullable: false };
+ assert.equal(C.convert("12.30", money, "USD"), 1230);
+ assert.equal(C.convert("-0.01", money, "USD"), -1);
+ for (const raw of [
+ "0x10",
+ "1e2",
+ "12.301",
+ " 12.3",
+ "NaN",
+ "Infinity",
+ "1,000.00",
+ "",
+ ])
+ assert.throws(() => C.convert(raw, money, "USD"));
+ assert.equal(C.convert("", { type: "real", nullable: true }, "x"), null);
+ assert.equal(C.convert("0", { type: "integer" }, "x"), 0);
+ assert.equal(C.convert("001", { type: "text" }, "id"), "001");
+ assert.equal(C.convert("2024-02-29", { type: "date" }, "date"), "2024-02-29");
+ assert.throws(() => C.convert("2026-02-30", { type: "date" }, "date"));
+ assert.throws(() => C.convert("9007199254740992", { type: "integer" }, "x"));
+ assert.throws(() => C.scalar(9007199254740992n));
+});
+test("SQL lexer allows quoted separators but blocks writes, multiple statements and undeclared parameters", () => {
+ const c = { parameters: [{ id: "region" }] };
+ assert.deepEqual(
+ C.validateSQL(
+ "WITH t AS (SELECT ';--' AS x) SELECT * FROM t WHERE :region='West'; -- done",
+ c,
+ ),
+ ["region"],
+ );
+ for (const sql of [
+ "SELECT 1; SELECT 2",
+ "PRAGMA query_only=OFF",
+ "ATTACH 'secret' AS x",
+ "WITH x AS (SELECT 1) DELETE FROM t",
+ "SELECT load_extension('x')",
+ "SELECT \"readfile\"('x')",
+ "SELECT * FROM pragma_database_list",
+ "SELECT :unknown",
+ "SELECT ?",
+ "SELECT 1 /*",
+ "SELECT 'unterminated",
+ ])
+ assert.throws(() => C.validateSQL(sql, c), undefined, sql);
+});
+test("actual sales example reconciles exact money and trace rows; no inferred ID/year measures", async () => {
+ const b = await bundle(),
+ r = runAnalysis(b);
+ assert.deepEqual(result(r, "headline").rows[0], [
+ 460450,
+ 436650,
+ -23800,
+ -23800 / 460450,
+ 24,
+ ]);
+ const categories = result(r, "contribution").rows;
+ assert.deepEqual(categories, [
+ ["Creative", 123200, 196800, 73600],
+ ["Home", 165350, 127550, -37800],
+ ["Outdoor", 171900, 112300, -59600],
+ ]);
+ assert.equal(
+ categories.reduce((n, row) => n + row[3], 0),
+ -23800,
+ );
+ const traced = runAnalysis(b, { category: "Outdoor" });
+ assert.equal(result(traced, "transactions_detail").rows.length, 8);
+ C.verifyLinks(b, traced.results);
+ assert.equal(result(traced, "transactions_detail").rows[0][2], "00005");
+ assert.equal(C.prepare(b).tables[1].rows[0][1], "001");
+ const noSales = runAnalysis(b, {
+ baseline: "2027-01-01",
+ comparison: "2027-02-01",
+ });
+ assert.deepEqual(result(noSales, "headline").rows[0], [0, 0, 0, null, 0]);
+ assert.deepEqual(result(noSales, "contribution").rows, []);
+});
+test("duplicate keys, unmatched joins, missing prices and malformed rules fail before analysis", async () => {
+ const b = await bundle();
+ for (const mutate of [
+ (b) => (b.sources["sources/products.csv"] += "001,Duplicate,Home\r\n"),
+ (b) =>
+ (b.sources["sources/transactions.csv"] = b.sources[
+ "sources/transactions.csv"
+ ].replace(",001,", ",999,")),
+ (b) =>
+ (b.sources["sources/transactions.csv"] = b.sources[
+ "sources/transactions.csv"
+ ].replace(",38.00,", ",,")),
+ (b) => (b.config.tables[0].columns[0].type = "integer"),
+ (b) => (b.config.relationships[0].to.column = "category"),
+ (b) => (b.config.tables[0].file = "../outside.csv"),
+ (b) => (b.config.unrecognized = true),
+ ]) {
+ const c = clone(b);
+ mutate(c);
+ assert.throws(() => runAnalysis(c));
+ }
+ assert.throws(
+ () => runAnalysis(b, { baseline: "2026-01-02" }),
+ /first-of-month/,
+ );
+ assert.throws(() => runAnalysis(b, { region: "unknown" }), /allowed choices/);
+});
+test("delivery workflow uses the correct denominator and retains missing outcomes", async () => {
+ const b = await bundle(join(root, "test/fixtures/delivery")),
+ r = runAnalysis(b);
+ assert.deepEqual(result(r, "headline").rows[0], [18, 15, 3, 7 / 15]);
+ const routes = result(r, "routes_summary").rows;
+ assert.deepEqual(routes, [
+ ["Metro", 6, 5, 1, 1],
+ ["Coastal", 6, 5, 1, 0.4],
+ ["Highlands", 6, 5, 1, 0],
+ ]);
+ const early = runAnalysis(b, { as_of: "2026-04-01" });
+ assert.deepEqual(result(early, "headline").rows[0], [18, 0, 18, null]);
+ assert.ok(result(early, "routes_summary").rows.every((r) => r[4] === null));
+ const revised = clone(b);
+ revised.sources["sources/shipments.csv"] = revised.sources[
+ "sources/shipments.csv"
+ ].replace("0017,02,2026-04-19,,1", "0017,02,2026-04-19,2026-04-19,1");
+ const after = runAnalysis(revised);
+ assert.deepEqual(result(after, "headline").rows[0], [18, 16, 2, 0.5]);
+ assert.notEqual(revision(revised), revision(b));
+});
+test("query shape, missing chart values, duplicate aliases, large results and checks are validated", async () => {
+ const b = await bundle();
+ for (const [sql, pattern] of [
+ ["SELECT 1 AS x, 2 AS x", /Duplicate/],
+ ["SELECT 9223372036854775807 AS x", /exact range/],
+ ["SELECT randomblob(10) AS x", /Unsupported/],
+ ]) {
+ const c = clone(b);
+ c.sql[c.config.queries[0].file] = sql;
+ assert.throws(() => runAnalysis(c), pattern);
+ }
+ assert.throws(
+ () => C.result(["a"], [[1], [2]], { kind: "metric" }),
+ /exactly one/,
+ );
+ assert.throws(
+ () =>
+ C.result(["x", "y"], [["a", "not a number"]], {
+ kind: "bar",
+ x: "x",
+ y: "y",
+ }),
+ /numeric or null/,
+ );
+ assert.equal(
+ C.result(["x", "y"], [["a", null]], { kind: "bar", x: "x", y: "y" })
+ .rows[0][1],
+ null,
+ );
+ const c = clone(b);
+ c.sql[c.config.checks[0].file] = "SELECT 1 AS violations";
+ assert.throws(() => runAnalysis(c), /violations=0/);
+});
+test("spreadsheet-safe CSV protects formula-like text while JSON retains exact null/text", () => {
+ const rows = [
+ ["001", '=HYPERLINK("https://invalid")', null, -2],
+ ["002", " +SUM(1,2)", "", 0],
+ ];
+ const csv = C.csv(["id", "note", "missing", "amount"], rows),
+ p = C.parseCSV(csv);
+ assert.match(p.records[0][1], /^'=/);
+ assert.match(p.records[1][1], /^' /);
+ assert.equal(p.records[0][3], "-2");
+ assert.deepEqual(JSON.parse(JSON.stringify(rows)), rows);
+});
+test("real build reopens SQLite, excludes undeclared files, restores portable project and preserves good outputs on errors", async () => {
+ const w = await workspace(),
+ r = await build(w);
+ assert.equal(r.checks, 9);
+ const first = await readFile(join(w, "output/analysis-result.json")),
+ report = JSON.parse(first),
+ database = new DatabaseSync(join(w, "output/analysis.sqlite"), {
+ readOnly: true,
+ });
+ assert.equal(
+ database.prepare("SELECT line_id FROM transactions WHERE _record=2").get()
+ .line_id,
+ "00001",
+ );
+ database.close();
+ await writeFile(join(w, "private-note.txt"), "not part of this analysis");
+ await build(w);
+ const archive = unzip(await readFile(join(w, "output/project.zip")));
+ assert.equal(archive.has("private-note.txt"), false);
+ assert.equal(archive.has(".harness/verdict.json"), false);
+ assert.ok(archive.has("vendor/sqlite3.wasm"));
+ const extracted = await mkdtemp(join(tmpdir(), "data-portable-"));
+ for (const [name, bytes] of archive) {
+ await mkdir(dirname(join(extracted, name)), { recursive: true });
+ await writeFile(join(extracted, name), bytes);
+ }
+ const rebuilt = await build(extracted);
+ assert.equal(rebuilt.revision, r.revision);
+ assert.deepEqual(
+ JSON.parse(await readFile(join(extracted, "output/analysis-result.json")))
+ .results,
+ report.results,
+ );
+ const restored = await mkdtemp(join(tmpdir(), "data-restored-"));
+ await restore(join(w, "output/project.data-studio.json"), restored);
+ assert.equal((await build(restored)).revision, r.revision);
+ await assert.rejects(
+ restore(join(w, "output/project.data-studio.json"), restored),
+ /empty/,
+ );
+ const before = sha(await readFile(join(w, "output/project.zip"))),
+ csv = await readFile(join(w, "sources/products.csv"), "utf8");
+ await writeFile(
+ join(w, "sources/products.csv"),
+ csv + "001,duplicate,Home\n",
+ );
+ await assert.rejects(build(w), /duplicate key/);
+ assert.equal(sha(await readFile(join(w, "output/project.zip"))), before);
+ assert.equal(
+ JSON.parse(await readFile(join(w, ".harness/verdict.json"))).ready,
+ false,
+ );
+ await writeFile(join(w, "sources/products.csv"), csv);
+ await mkdir(join(w, ".harness/data-build.lock"));
+ await assert.rejects(build(w), /Another build/);
+});
+test("saved project tampering, source symlinks and runtime tampering are rejected", async () => {
+ const w = await workspace();
+ await build(w);
+ const p = JSON.parse(
+ await readFile(join(w, "output/project.data-studio.json")),
+ );
+ p.bundle.config.title = "Tampered";
+ const path = join(w, "tampered.json");
+ await writeFile(path, JSON.stringify(p));
+ await assert.rejects(restore(path, join(w, "new")), /checksum/);
+ const links = await workspace();
+ const c = JSON.parse(await readFile(join(links, "analysis.json")));
+ c.tables[0].file = "linked.csv";
+ await writeFile(join(links, "analysis.json"), JSON.stringify(c));
+ await symlink(
+ join(links, "sources/transactions.csv"),
+ join(links, "linked.csv"),
+ );
+ await assert.rejects(build(links), /symlinks/);
+ const changed = await workspace();
+ await writeFile(join(changed, "vendor/sqlite3.js"), "tampered");
+ await assert.rejects(build(changed), /checksum mismatch/);
+});
+test("a nonterminating read-only query times out without replacing the last good project", async () => {
+ const w = await workspace();
+ await build(w);
+ const before = sha(await readFile(join(w, "output/project.zip")));
+ await writeFile(
+ join(w, "queries/monthly.sql"),
+ "WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n) SELECT sum(x) AS total FROM n",
+ );
+ await assert.rejects(build(w), /20-second query budget/);
+ assert.equal(sha(await readFile(join(w, "output/project.zip"))), before);
+ assert.equal(
+ JSON.parse(await readFile(join(w, ".harness/verdict.json"))).ready,
+ false,
+ );
+});
diff --git a/store/agents/data-studio/test/browser.mjs b/store/agents/data-studio/test/browser.mjs
new file mode 100644
index 000000000..995df5e86
--- /dev/null
+++ b/store/agents/data-studio/test/browser.mjs
@@ -0,0 +1,448 @@
+// Real-browser acceptance, not a DOM mock. Run with PLAYWRIGHT_MODULE pointing to
+// playwright/index.mjs or playwright-core/index.mjs. All evidence stays outside source.
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, cp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve, dirname } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { DatabaseSync } from "node:sqlite";
+import { spawnSync } from "node:child_process";
+import { build } from "../template/tools/build.mjs";
+import { unzip } from "../template/tools/archive.mjs";
+import { createPreview } from "../template/tools/serve.mjs";
+import { createHtmlViewer } from "../../../viewers/isolated-web-viewer/viewer.mjs";
+const { chromium } = await import(
+ process.env.PLAYWRIGHT_MODULE
+ ? pathToFileURL(resolve(process.env.PLAYWRIGHT_MODULE)).href
+ : "playwright"
+);
+const root = fileURLToPath(new URL("../", import.meta.url)),
+ evidence = process.env.DATA_EVIDENCE_DIR
+ ? resolve(process.env.DATA_EVIDENCE_DIR)
+ : await mkdtemp(join(tmpdir(), "data-browser-"));
+await mkdir(evidence, { recursive: true });
+const sales = join(evidence, "sales"),
+ delivery = join(evidence, "delivery");
+await cp(join(root, "template"), sales, { recursive: true });
+await cp(join(root, "template"), delivery, { recursive: true });
+await cp(join(root, "test/fixtures/delivery"), delivery, { recursive: true });
+for (const w of [sales, delivery]) await build(w);
+const browser = await chromium.launch({
+ headless: true,
+ ...(process.env.BROWSER_EXECUTABLE
+ ? { executablePath: process.env.BROWSER_EXECUTABLE }
+ : {}),
+});
+const receipts = [];
+async function context(workspace, direct, run) {
+ const server = await (direct
+ ? createPreview(workspace)
+ : createHtmlViewer(workspace));
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const url =
+ "http://127.0.0.1:" +
+ server.address().port +
+ (direct ? server.previewPrefix : "/");
+ const page = await browser.newPage({
+ viewport: { width: 1560, height: 1100 },
+ acceptDownloads: true,
+ }),
+ errors = [],
+ external = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ page.on("console", (m) => {
+ if (m.type() === "error") errors.push(m.text());
+ });
+ page.on("request", (r) => {
+ if (/^https?:/.test(r.url()) && !r.url().startsWith("http://127.0.0.1:"))
+ external.push(r.url());
+ });
+ try {
+ await page.goto(url);
+ const f = direct ? page : page.frameLocator("#preview");
+ await f.locator("body[data-ready=true]").waitFor({ timeout: 30000 });
+ try {
+ await run(page, f);
+ } catch (error) {
+ console.error(
+ "Browser status:",
+ await f.locator("#status").textContent(),
+ );
+ throw error;
+ }
+ assert.deepEqual(errors, []);
+ assert.deepEqual(external, []);
+ receipts.push({ workspace, direct, errors, external });
+ } finally {
+ await page.close();
+ server.closeAllConnections();
+ await new Promise((r) => server.close(r));
+ }
+}
+async function download(page, locator, name) {
+ const wait = page.waitForEvent("download");
+ await locator.click();
+ const file = await wait,
+ path = join(evidence, name);
+ await file.saveAs(path);
+ return path;
+}
+async function settled(f) {
+ await f.locator("body[data-busy=false]").waitFor({ timeout: 30000 });
+}
+try {
+ await context(sales, false, async (page, f) => {
+ assert.equal(
+ await f.locator('[data-metric="change"] strong').textContent(),
+ "-$238.00",
+ );
+ await f
+ .locator("body")
+ .screenshot({ path: join(evidence, "sales-initial.png") });
+ await f.locator('[data-category="Outdoor"]').focus();
+ await page.keyboard.press("Enter");
+ await f.locator('#row-count[data-count="8"]').waitFor();
+ await f.locator('.source-link[data-table="transactions"]').first().click();
+ assert.match(await f.locator("#raw-record").textContent(), /00005/);
+ const rawCsv = await download(
+ page,
+ f.locator("#download-source"),
+ "sales-original-transactions.csv",
+ );
+ assert.deepEqual(
+ await readFile(rawCsv),
+ await readFile(join(sales, "sources/transactions.csv")),
+ );
+ await f.locator("#close-source").click();
+ await f
+ .locator("body")
+ .screenshot({ path: join(evidence, "sales-evidence.png") });
+ await f.locator("#reset-trace").click();
+ await f.locator('#row-count[data-count="24"]').waitFor();
+ await f.locator("#param-region").selectOption("West");
+ await f.locator("#apply-controls").click();
+ await settled(f);
+ assert.equal(
+ await f.locator('[data-metric="baseline_sales"] strong').textContent(),
+ "$2,583.50",
+ );
+ assert.equal(
+ await f.locator("#row-count").getAttribute("data-count"),
+ "12",
+ );
+ await f.locator("#param-region").selectOption("");
+ await f.locator("#apply-controls").click();
+ await settled(f);
+ await f.locator('[data-query="monthly"]').click();
+ await f.locator("#calculation summary").click();
+ const original = await f.locator("#sql").inputValue();
+ await f
+ .locator("#sql")
+ .fill(
+ original.replace(
+ "WHERE status='completed'",
+ "WHERE status='completed' AND quantity>=15",
+ ),
+ );
+ await f.locator("#run-sql").click();
+ await settled(f);
+ assert.match(
+ await f.locator("#query-explanation").textContent(),
+ /Edited query/,
+ );
+ const revised = await download(
+ page,
+ f.locator("#export-json"),
+ "sales-revised-query.json",
+ );
+ const revisedRows = JSON.parse(await readFile(revised)).rows;
+ assert.equal(revisedRows.length, 2);
+ await f.locator("#sql").fill("DROP TABLE transactions");
+ await f.locator("#run-sql").click();
+ await settled(f);
+ assert.match(
+ await f.locator("#status").textContent(),
+ /Last good analysis/,
+ );
+ await f.locator('[data-source="transactions"]').click();
+ const input = await readFile(
+ join(sales, "sources/transactions.csv"),
+ "utf8",
+ );
+ const changed = join(evidence, "revised-transactions.csv");
+ await writeFile(changed, input.replace(",12,38.00,", ",12,40.00,"));
+ await f.locator("#replace-source").setInputFiles(changed);
+ await settled(f);
+ assert.equal(
+ await f.locator('[data-metric="change"] strong').textContent(),
+ "-$262.00",
+ );
+ await f.locator("#close-source").click();
+ await f.locator('[data-source="products"]').click();
+ const duplicate = join(evidence, "bad-products.csv");
+ await writeFile(
+ duplicate,
+ (await readFile(join(sales, "sources/products.csv"), "utf8")) +
+ "001,Duplicate,Home\n",
+ );
+ await f.locator("#replace-source").setInputFiles(duplicate);
+ await settled(f);
+ assert.match(await f.locator("#status").textContent(), /duplicate key/);
+ await f.locator("#close-source").click();
+ await f
+ .locator("#notes")
+ .fill(
+ "Synthetic acceptance review: changed the first unit price and restricted the monthly query to lines with at least 15 units.",
+ );
+ const saved = await download(
+ page,
+ f.locator("#save-project"),
+ "sales-saved.data-studio.json",
+ );
+ await download(page, f.locator("#export-db"), "sales-browser.sqlite");
+ await download(page, f.locator("#export-report"), "sales-report.html");
+ await download(page, f.locator("#export-csv"), "sales-revised-query.csv");
+ await download(page, f.locator("#export-json"), "sales-current-query.json");
+ await download(page, f.locator("#portable"), "sales-original.zip");
+ await f.locator("#notes").fill("not saved");
+ await f.locator("#open-project").setInputFiles(saved);
+ await settled(f);
+ assert.match(
+ await f.locator("#notes").inputValue(),
+ /restricted the monthly/,
+ );
+ assert.equal(
+ await f.locator('[data-metric="change"] strong').textContent(),
+ "-$262.00",
+ );
+ const p = JSON.parse(await readFile(saved));
+ p.revision = "0".repeat(64);
+ const corrupt = join(evidence, "corrupt.json");
+ await writeFile(corrupt, JSON.stringify(p));
+ await f.locator("#open-project").setInputFiles(corrupt);
+ await f
+ .locator("#status")
+ .filter({ hasText: "checksum mismatch" })
+ .waitFor();
+ assert.equal(
+ await f.locator('[data-metric="change"] strong').textContent(),
+ "-$262.00",
+ );
+ await f.locator("#param-baseline").fill("2027-01-01");
+ // Long SQL must neither freeze the page nor replace the last good result.
+ if (!(await f.locator("#sql").isVisible()))
+ await f.locator("#calculation summary").click();
+ await f
+ .locator("#sql")
+ .fill(
+ "WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n) SELECT sum(x) AS total FROM n",
+ );
+ await f.locator("#run-sql").click();
+ await f.locator("#cancel-run").waitFor();
+ const frames = await f.locator("body").evaluate(
+ () =>
+ new Promise((resolve) => {
+ let n = 0;
+ const start = performance.now();
+ const tick = () => {
+ if (++n === 5)
+ resolve({ frames: n, ms: performance.now() - start });
+ else requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ }),
+ );
+ assert.equal(frames.frames, 5);
+ assert.ok(frames.ms < 2000);
+ await f.locator("#cancel-run").click();
+ await settled(f);
+ assert.match(await f.locator("#status").textContent(), /cancelled/);
+ await f.locator("#run-sql").click();
+ await settled(f);
+ assert.match(
+ await f.locator("#status").textContent(),
+ /20-second query budget/,
+ );
+ assert.equal(
+ await f.locator('[data-metric="change"] strong').textContent(),
+ "-$262.00",
+ );
+ await f.locator("#param-comparison").fill("2027-02-01");
+ await f.locator("#apply-controls").click();
+ await settled(f);
+ await f.locator('[data-query="contribution"]').click();
+ assert.equal(await f.locator("#row-count").getAttribute("data-count"), "0");
+ assert.equal(
+ await f.locator('[data-metric="growth"] strong').textContent(),
+ "Missing",
+ );
+ await page.setViewportSize({ width: 390, height: 844 });
+ assert.equal(
+ await f
+ .locator("body")
+ .evaluate(() => document.documentElement.scrollWidth > innerWidth),
+ false,
+ );
+ await f
+ .locator("body")
+ .screenshot({ path: join(evidence, "sales-mobile.png") });
+ });
+ const downloaded = JSON.parse(
+ await readFile(join(evidence, "sales-saved.data-studio.json")),
+ ),
+ db = new DatabaseSync(join(evidence, "sales-browser.sqlite"), {
+ readOnly: true,
+ });
+ assert.equal(
+ db.prepare("PRAGMA integrity_check").get().integrity_check,
+ "ok",
+ );
+ assert.equal(
+ db
+ .prepare("SELECT unit_price_cents FROM transactions WHERE _record=2")
+ .get().unit_price_cents,
+ 4000,
+ );
+ const stmt = db.prepare(downloaded.bundle.sql["queries/monthly.sql"]);
+ assert.deepEqual(
+ stmt.all({ ":region": "" }).map((row) => Object.values(row)),
+ JSON.parse(await readFile(join(evidence, "sales-current-query.json"))).rows,
+ );
+ db.close();
+ const restored = join(evidence, "restored-browser-project");
+ const restore = spawnSync(
+ process.execPath,
+ [
+ join(sales, "tools/restore.mjs"),
+ join(evidence, "sales-saved.data-studio.json"),
+ restored,
+ ],
+ { encoding: "utf8" },
+ );
+ assert.equal(restore.status, 0, restore.stderr);
+ const rebuilt = await build(restored);
+ assert.equal(rebuilt.revision, downloaded.revision);
+ await context(restored, true, async (page, f) => {
+ assert.equal(
+ await f.locator('[data-metric="change"] strong').textContent(),
+ "-$262.00",
+ );
+ assert.match(
+ await f.locator("#notes").inputValue(),
+ /restricted the monthly/,
+ );
+ await f
+ .locator("body")
+ .screenshot({ path: join(evidence, "restored-browser-project.png") });
+ });
+ const extracted = join(evidence, "extracted-zip");
+ for (const [name, bytes] of unzip(
+ await readFile(join(evidence, "sales-original.zip")),
+ )) {
+ await mkdir(dirname(join(extracted, name)), { recursive: true });
+ await writeFile(join(extracted, name), bytes);
+ }
+ await build(extracted);
+ await context(extracted, true, async (page, f) => {
+ assert.equal(
+ await f.locator('[data-metric="change"] strong').textContent(),
+ "-$238.00",
+ );
+ await f.locator('[data-category="Creative"]').click();
+ await f.locator('#row-count[data-count="8"]').waitFor();
+ await download(page, f.locator("#export-db"), "portable.sqlite");
+ });
+ await context(delivery, false, async (page, f) => {
+ assert.equal(
+ await f.locator('[data-metric="on_time_rate"] strong').textContent(),
+ "46.7%",
+ );
+ await f
+ .locator("body")
+ .screenshot({ path: join(evidence, "delivery-initial.png") });
+ await f.locator('[data-category="Highlands"]').click();
+ await f.locator('#row-count[data-count="6"]').waitFor();
+ assert.match(await f.locator("#result-table").textContent(), /Missing/);
+ await f.locator('[data-source="shipments"]').click();
+ const revised = join(evidence, "revised-shipments.csv");
+ await writeFile(
+ revised,
+ (await readFile(join(delivery, "sources/shipments.csv"), "utf8")).replace(
+ "0017,02,2026-04-19,,1",
+ "0017,02,2026-04-19,2026-04-19,1",
+ ),
+ );
+ await f.locator("#replace-source").setInputFiles(revised);
+ await settled(f);
+ await f.locator("#close-source").click();
+ assert.equal(
+ await f.locator('[data-metric="on_time_rate"] strong').textContent(),
+ "50.0%",
+ );
+ await download(
+ page,
+ f.locator("#save-project"),
+ "delivery-saved.data-studio.json",
+ );
+ await download(page, f.locator("#export-db"), "delivery-browser.sqlite");
+ await download(page, f.locator("#export-report"), "delivery-report.html");
+ await f.locator("#param-as_of").fill("2026-04-01");
+ await f.locator("#apply-controls").click();
+ await settled(f);
+ assert.equal(
+ await f.locator('[data-metric="on_time_rate"] strong').textContent(),
+ "Missing",
+ );
+ await f.locator('[data-query="routes_summary"]').click();
+ assert.equal(await f.locator(".null-bar").count(), 3);
+ await page.setViewportSize({ width: 390, height: 844 });
+ assert.equal(
+ await f
+ .locator("body")
+ .evaluate(() => document.documentElement.scrollWidth > innerWidth),
+ false,
+ );
+ await f
+ .locator("body")
+ .screenshot({ path: join(evidence, "delivery-mobile.png") });
+ });
+ await writeFile(
+ join(evidence, "browser-receipt.json"),
+ JSON.stringify(
+ {
+ at: new Date().toISOString(),
+ contexts: receipts,
+ checks: [
+ "native/browser equality",
+ "keyboard drilldown",
+ "raw CSV download is byte-identical",
+ "cancel and timeout preserve good results",
+ "page remains responsive during long SQL",
+ "raw source records",
+ "controls",
+ "SQL revision",
+ "invalid SQL preserves good result",
+ "valid CSV revision",
+ "duplicate CSV rejection",
+ "all downloads",
+ "project reopen",
+ "checksum rejection",
+ "empty/missing states",
+ "390px layout",
+ "native reopen of browser SQLite",
+ "JSON restore + rebuild",
+ "ZIP extraction + rebuild",
+ "standalone CSP",
+ "second independent schema + revision",
+ ],
+ },
+ null,
+ 2,
+ ),
+ );
+ console.log(
+ JSON.stringify({ evidence, contexts: receipts.length, passed: true }),
+ );
+} finally {
+ await browser.close();
+}
diff --git a/store/agents/data-studio/test/data.test.mjs b/store/agents/data-studio/test/data.test.mjs
deleted file mode 100644
index e3c74347c..000000000
--- a/store/agents/data-studio/test/data.test.mjs
+++ /dev/null
@@ -1,42 +0,0 @@
-import assert from 'node:assert/strict';
-import { readFileSync } from 'node:fs';
-import { test } from 'node:test';
-import { parseCSV, inferFields, summarize, exportCSV } from '../template/data.mjs';
-
-test('CSV supports BOM, CRLF, quoted commas, doubled quotes, multiline fields and negative/decimal numbers', () => {
- const table = parseCSV('\uFEFFperiod,group,value\r\nQ1,"North, coast",-2.5\r\nQ2,"A ""quoted""\nteam",4.75\r\n');
- assert.equal(table.rows[0].group, 'North, coast');
- assert.equal(table.rows[1].group, 'A "quoted"\nteam');
- assert.deepEqual(parseCSV(exportCSV(table.headers, table.rows)), table);
- const fields = inferFields(table);
- assert.equal(summarize(table, fields, new Set(table.rows.map(row => row.group))).total, 2.25);
-});
-
-test('malformed CSV is rejected rather than charted as plausible numbers', () => {
- for (const csv of ['', 'x,x\na,b', 'x,\na,b', 'x,y\na,b,c', 'x,y\n"unfinished,b', 'x,y\n"a"oops,b']) {
- assert.throws(() => parseCSV(csv), undefined, csv);
- }
- assert.throws(() => inferFields(parseCSV('period,group,value\nQ1,A,NaN')));
- assert.throws(() => inferFields(parseCSV('period,group,value\nQ1,A,')));
-});
-
-test('new groups/periods, repeated observations, zeros and negative values determine the view', () => {
- const table = parseCSV('period,group,value\nQ1,New group,0\nQ2,New group,20\nQ2,New group,5\nQ2,Other,-8');
- const fields = inferFields(table);
- const all = summarize(table, fields, new Set(['New group', 'Other']));
- assert.equal(all.total, 17);
- assert.equal(all.growth, null, 'a zero baseline has no finite percentage growth');
- assert.equal(all.ranked[0].value, 25);
- assert.equal(summarize(table, fields, new Set()).rows.length, 0);
- assert.equal(summarize(table, fields, new Set(['Other']), { start: 'Q2', end: 'Q2' }).total, -8);
-});
-
-test('the actual starter totals and filters agree with the underlying rows', () => {
- const table = parseCSV(readFileSync(new URL('../template/data.csv', import.meta.url), 'utf8'));
- const fields = inferFields(table);
- const result = summarize(table, fields, new Set(['North', 'East', 'South', 'West']));
- assert.equal(result.total, 203000);
- assert.equal(result.ranked[0].name, 'East');
- assert.equal(result.ranked[0].value, 67200);
- assert.equal(summarize(table, fields, new Set(['North'])).total, 54600);
-});
diff --git a/store/agents/data-studio/test/fixtures/delivery/analysis.json b/store/agents/data-studio/test/fixtures/delivery/analysis.json
new file mode 100644
index 000000000..644187aca
--- /dev/null
+++ b/store/agents/data-studio/test/fixtures/delivery/analysis.json
@@ -0,0 +1,181 @@
+{
+ "spec": 1,
+ "title": "Where are deliveries slipping?",
+ "question": "Which routes missed their promised date, and how many shipments are still open as of a chosen day?",
+ "example": true,
+ "method": "Join each shipment to a unique route. A shipment is delivered only when its recorded delivery date is on or before the as-of date. On-time rate = delivered on or before promised date / all delivered shipments; open shipments are excluded from this denominator. Each shipment counts once regardless of package quantity.",
+ "limitations": [
+ "Synthetic operations data, not an assessment of a real carrier.",
+ "Open or future-dated deliveries have no observed delivery outcome. Their on-time status is not imputed as zero.",
+ "Descriptive route comparisons do not establish the cause of delays. Results do not predict future delivery dates."
+ ],
+ "tables": [
+ {
+ "id": "shipments",
+ "file": "sources/shipments.csv",
+ "label": "Shipment log · synthetic",
+ "key": [
+ "shipment_id"
+ ],
+ "columns": [
+ {
+ "name": "shipment_id",
+ "source": "shipment_id",
+ "type": "text",
+ "nullable": false
+ },
+ {
+ "name": "route_id",
+ "source": "route_id",
+ "type": "text",
+ "nullable": false
+ },
+ {
+ "name": "promised_on",
+ "source": "promised_on",
+ "type": "date",
+ "nullable": false
+ },
+ {
+ "name": "delivered_on",
+ "source": "delivered_on",
+ "type": "date",
+ "nullable": true
+ },
+ {
+ "name": "packages",
+ "source": "packages",
+ "type": "integer",
+ "nullable": false
+ }
+ ]
+ },
+ {
+ "id": "routes",
+ "file": "sources/routes.csv",
+ "label": "Route catalog · synthetic",
+ "key": [
+ "route_id"
+ ],
+ "columns": [
+ {
+ "name": "route_id",
+ "source": "route_id",
+ "type": "text",
+ "nullable": false
+ },
+ {
+ "name": "route",
+ "source": "route",
+ "type": "text",
+ "nullable": false
+ },
+ {
+ "name": "region",
+ "source": "region",
+ "type": "text",
+ "nullable": false
+ }
+ ]
+ }
+ ],
+ "relationships": [
+ {
+ "from": {
+ "table": "shipments",
+ "column": "route_id"
+ },
+ "to": {
+ "table": "routes",
+ "column": "route_id"
+ },
+ "allowMissing": false
+ }
+ ],
+ "parameters": [
+ {
+ "id": "as_of",
+ "label": "As of",
+ "type": "date",
+ "default": "2026-04-30"
+ },
+ {
+ "id": "region",
+ "label": "Region",
+ "type": "text",
+ "default": "",
+ "choices": [
+ "",
+ "South",
+ "North",
+ "Central"
+ ]
+ },
+ {
+ "id": "route",
+ "label": "Drilldown route",
+ "type": "text",
+ "default": "",
+ "hidden": true
+ }
+ ],
+ "queries": [
+ {
+ "id": "headline",
+ "title": "Delivery snapshot",
+ "file": "queries/headline.sql",
+ "kind": "metric",
+ "formats": {
+ "on_time_rate": {
+ "style": "percent",
+ "digits": 1
+ }
+ },
+ "explanation": "Counts of shipments, not packages. Open shipments stay outside the delivered denominator."
+ },
+ {
+ "id": "routes_summary",
+ "title": "On-time delivery by route",
+ "file": "queries/routes.sql",
+ "kind": "bar",
+ "x": "route",
+ "y": "on_time_rate",
+ "formats": {
+ "on_time_rate": {
+ "style": "percent",
+ "digits": 1
+ }
+ },
+ "trace": {
+ "query": "shipment_detail",
+ "bindings": {
+ "route": "route"
+ }
+ },
+ "explanation": "Each rate is calculated from its own delivered count. A route with no delivered shipments has a missing rate, not 0%."
+ },
+ {
+ "id": "shipment_detail",
+ "title": "Shipment evidence",
+ "file": "queries/detail.sql",
+ "kind": "detail",
+ "sourceLinks": {
+ "shipments_record": "shipments",
+ "routes_record": "routes"
+ },
+ "explanation": "Joined source records with outcome as of the selected day. Open shipments retain a missing delivery date."
+ }
+ ],
+ "checks": [
+ {
+ "id": "packages_positive",
+ "file": "checks/packages.sql",
+ "description": "Every shipment has a positive number of packages."
+ },
+ {
+ "id": "reconcile_deliveries",
+ "file": "checks/reconcile.sql",
+ "description": "Route-level delivered counts reconcile to the shipment-level total."
+ }
+ ]
+}
diff --git a/store/agents/data-studio/test/fixtures/delivery/checks/packages.sql b/store/agents/data-studio/test/fixtures/delivery/checks/packages.sql
new file mode 100644
index 000000000..f53375d71
--- /dev/null
+++ b/store/agents/data-studio/test/fixtures/delivery/checks/packages.sql
@@ -0,0 +1 @@
+SELECT count(*) AS violations FROM shipments WHERE packages<=0;
diff --git a/store/agents/data-studio/test/fixtures/delivery/checks/reconcile.sql b/store/agents/data-studio/test/fixtures/delivery/checks/reconcile.sql
new file mode 100644
index 000000000..bb88ad725
--- /dev/null
+++ b/store/agents/data-studio/test/fixtures/delivery/checks/reconcile.sql
@@ -0,0 +1,7 @@
+WITH route_counts AS (
+ SELECT r.route,count(*) AS n FROM shipments s JOIN routes r ON s.route_id=r.route_id
+ WHERE s.delivered_on<=:as_of AND (:region='' OR r.region=:region) GROUP BY r.route
+)
+SELECT CASE WHEN coalesce((SELECT sum(n) FROM route_counts),0)=(
+ SELECT count(*) FROM shipments s WHERE s.delivered_on<=:as_of AND (:region='' OR s.route_id IN (SELECT route_id FROM routes WHERE region=:region))
+) THEN 0 ELSE 1 END AS violations;
diff --git a/store/agents/data-studio/test/fixtures/delivery/queries/detail.sql b/store/agents/data-studio/test/fixtures/delivery/queries/detail.sql
new file mode 100644
index 000000000..bdabc1cbf
--- /dev/null
+++ b/store/agents/data-studio/test/fixtures/delivery/queries/detail.sql
@@ -0,0 +1,6 @@
+SELECT s._record AS shipments_record,r._record AS routes_record,s.shipment_id,r.route,s.promised_on,s.delivered_on,
+ CASE WHEN s.delivered_on IS NULL OR s.delivered_on>:as_of THEN 'Open'
+ WHEN s.delivered_on<=s.promised_on THEN 'On time' ELSE 'Late' END AS outcome,s.packages
+FROM shipments s JOIN routes r ON s.route_id=r.route_id
+WHERE (:region='' OR r.region=:region) AND (:route='' OR r.route=:route)
+ORDER BY s.promised_on,s.shipment_id;
diff --git a/store/agents/data-studio/test/fixtures/delivery/queries/headline.sql b/store/agents/data-studio/test/fixtures/delivery/queries/headline.sql
new file mode 100644
index 000000000..7f3154713
--- /dev/null
+++ b/store/agents/data-studio/test/fixtures/delivery/queries/headline.sql
@@ -0,0 +1,9 @@
+WITH joined AS (
+ SELECT s.* FROM shipments s JOIN routes r ON s.route_id=r.route_id WHERE :region='' OR r.region=:region
+)
+SELECT count(*) AS shipments,
+ count(CASE WHEN delivered_on<=:as_of THEN 1 END) AS delivered,
+ count(CASE WHEN delivered_on IS NULL OR delivered_on>:as_of THEN 1 END) AS open,
+ count(CASE WHEN delivered_on<=:as_of AND delivered_on<=promised_on THEN 1 END)*1.0
+ /nullif(count(CASE WHEN delivered_on<=:as_of THEN 1 END),0) AS on_time_rate
+FROM joined;
diff --git a/store/agents/data-studio/test/fixtures/delivery/queries/routes.sql b/store/agents/data-studio/test/fixtures/delivery/queries/routes.sql
new file mode 100644
index 000000000..4f986122d
--- /dev/null
+++ b/store/agents/data-studio/test/fixtures/delivery/queries/routes.sql
@@ -0,0 +1,8 @@
+SELECT r.route, count(*) AS shipments,
+ count(CASE WHEN s.delivered_on<=:as_of THEN 1 END) AS delivered,
+ count(CASE WHEN s.delivered_on IS NULL OR s.delivered_on>:as_of THEN 1 END) AS open,
+ count(CASE WHEN s.delivered_on<=:as_of AND s.delivered_on<=s.promised_on THEN 1 END)*1.0
+ /nullif(count(CASE WHEN s.delivered_on<=:as_of THEN 1 END),0) AS on_time_rate
+FROM shipments s JOIN routes r ON s.route_id=r.route_id
+WHERE :region='' OR r.region=:region
+GROUP BY r.route ORDER BY on_time_rate DESC, r.route;
diff --git a/store/agents/data-studio/test/fixtures/delivery/sources/routes.csv b/store/agents/data-studio/test/fixtures/delivery/sources/routes.csv
new file mode 100644
index 000000000..ae727133a
--- /dev/null
+++ b/store/agents/data-studio/test/fixtures/delivery/sources/routes.csv
@@ -0,0 +1,4 @@
+route_id,route,region
+01,Coastal,South
+02,Highlands,North
+03,Metro,Central
diff --git a/store/agents/data-studio/test/fixtures/delivery/sources/shipments.csv b/store/agents/data-studio/test/fixtures/delivery/sources/shipments.csv
new file mode 100644
index 000000000..0a2b1386c
--- /dev/null
+++ b/store/agents/data-studio/test/fixtures/delivery/sources/shipments.csv
@@ -0,0 +1,19 @@
+shipment_id,route_id,promised_on,delivered_on,packages
+0001,01,2026-04-03,2026-04-04,1
+0002,02,2026-04-04,2026-04-06,2
+0003,03,2026-04-05,2026-04-05,3
+0004,01,2026-04-06,2026-04-06,4
+0005,02,2026-04-07,2026-04-09,1
+0006,03,2026-04-08,2026-04-08,2
+0007,01,2026-04-09,2026-04-10,3
+0008,02,2026-04-10,2026-04-12,4
+0009,03,2026-04-11,2026-04-11,1
+0010,01,2026-04-12,2026-04-12,2
+0011,02,2026-04-13,2026-04-15,3
+0012,03,2026-04-14,2026-04-14,4
+0013,01,2026-04-15,2026-04-16,1
+0014,02,2026-04-16,2026-04-18,2
+0015,03,2026-04-17,2026-04-17,3
+0016,01,2026-04-18,,4
+0017,02,2026-04-19,,1
+0018,03,2026-04-20,,2
diff --git a/store/agents/data-studio/test/server.test.mjs b/store/agents/data-studio/test/server.test.mjs
new file mode 100644
index 000000000..102171381
--- /dev/null
+++ b/store/agents/data-studio/test/server.test.mjs
@@ -0,0 +1,57 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, cp, writeFile, symlink, rename } from "node:fs/promises";
+import { request } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { createPreview } from "../template/tools/serve.mjs";
+test("portable server is tokenized, read-only, loopback-only and excludes unrelated files/symlinks", async () => {
+ const w = await mkdtemp(join(tmpdir(), "data-server-"));
+ await cp(fileURLToPath(new URL("../template", import.meta.url)), w, {
+ recursive: true,
+ });
+ await writeFile(join(w, "private.txt"), "must not be served");
+ const server = await createPreview(w);
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const base = "http://127.0.0.1:" + server.address().port,
+ p = server.previewPrefix;
+ try {
+ const page = await fetch(base + p);
+ assert.equal(page.status, 200);
+ assert.match(
+ page.headers.get("content-security-policy"),
+ /worker-src blob:/,
+ );
+ assert.equal((await fetch(base + "/index.html")).status, 404);
+ assert.equal((await fetch(base + p + "private.txt")).status, 404);
+ assert.equal((await fetch(base + p + "analysis.json")).status, 404);
+ assert.equal(
+ (await fetch(base + p, { method: "POST", body: "x" })).status,
+ 405,
+ );
+ const hostStatus = await new Promise((resolve, reject) => {
+ const r = request(
+ {
+ hostname: "127.0.0.1",
+ port: server.address().port,
+ path: p,
+ headers: { Host: "untrusted.example" },
+ },
+ (response) => {
+ response.resume();
+ resolve(response.statusCode);
+ },
+ );
+ r.on("error", reject);
+ r.end();
+ });
+ assert.equal(hostStatus, 403);
+ await rename(join(w, "core.js"), join(w, "saved-core.js"));
+ await symlink(join(w, "private.txt"), join(w, "core.js"));
+ assert.equal((await fetch(base + p + "core.js")).status, 404);
+ } finally {
+ server.closeAllConnections();
+ await new Promise((r) => server.close(r));
+ }
+});
diff --git a/store/agents/data-studio/test/toolchain.test.mjs b/store/agents/data-studio/test/toolchain.test.mjs
index 9f1fd60c6..5a8863e2f 100644
--- a/store/agents/data-studio/test/toolchain.test.mjs
+++ b/store/agents/data-studio/test/toolchain.test.mjs
@@ -1,106 +1,107 @@
-// The Data Studio harness's scripts, run the way Harness runs them: by path, in the directory
-// Harness gives them, with the environment Harness sets.
-//
-// node --test test/*.test.mjs
-import assert from 'node:assert/strict'
-import { spawnSync } from 'node:child_process'
-import { accessSync, constants, existsSync, mkdtempSync, readFileSync, writeFileSync, rmSync, chmodSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { fileURLToPath } from 'node:url'
-import { after, test } from 'node:test'
-
-const here = fileURLToPath(new URL('..', import.meta.url))
-const manifest = JSON.parse(readFileSync(join(here, 'harness.json'), 'utf8'))
-const scratch = []
-after(() => { for (const dir of scratch) rmSync(dir, { recursive: true, force: true }) })
-
-function tempDir() {
- const dir = mkdtempSync(join(tmpdir(), 'data-studio-'))
- scratch.push(dir)
- return dir
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import {
+ mkdtemp,
+ cp,
+ readFile,
+ writeFile,
+ access,
+ symlink,
+ mkdir,
+} from "node:fs/promises";
+import { constants } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+const root = fileURLToPath(new URL("../", import.meta.url));
+async function workspace() {
+ const p = await mkdtemp(join(tmpdir(), "data-toolchain-"));
+ await cp(join(root, "template"), p, { recursive: true });
+ return p;
}
-
-function run(script, { cwd = here, env = {} } = {}) {
- const merged = { ...process.env }
- for (const [key, value] of Object.entries(env)) if (value === null) delete merged[key]; else merged[key] = value
- const result = spawnSync(join(here, script), { cwd, env: merged, encoding: 'utf8' })
- return { code: result.status, stdout: result.stdout, stderr: result.stderr }
-}
-
-/** A fake `node` (this harness's only local runtime gate) that reports a version. */
-function fakeNode() {
- const dir = tempDir()
- const bin = join(dir, 'node')
- writeFileSync(bin, '#!/bin/sh\nfor a in "$@"; do [ "$a" = "--version" ] && echo "v20.19.0"; done; exit 0\n')
- chmodSync(bin, 0o755)
- return dir
-}
-
-test('every script the manifest names is in the folder and executable', () => {
- for (const script of [manifest.workspace.init, manifest.toolchain.setup, manifest.toolchain.doctor, 'skills/data/scripts/update-verdict.sh']) {
- assert.doesNotThrow(() => accessSync(join(here, script), constants.X_OK), script)
- }
-})
-
-test('setup finds node on PATH and says ok', () => {
- const dir = fakeNode()
- const { code, stdout } = run(manifest.toolchain.setup, { env: { PATH: `${dir}:/usr/bin:/bin` } })
- assert.equal(code, 0)
- assert.match(stdout, /ok node/)
-})
-
-test('doctor says ok when node is on PATH', () => {
- const dir = fakeNode()
- const { code, stdout } = run(manifest.toolchain.doctor, { env: { PATH: `${dir}:/usr/bin:/bin` } })
- assert.equal(code, 0)
- assert.match(stdout, /ok node/)
-})
-
-test('doctor says miss and fails when node is absent', () => {
- const { code, stdout } = run(manifest.toolchain.doctor, { env: { PATH: tempDir() } })
- assert.equal(code, 1)
- assert.match(stdout, /miss node/)
-})
-
-test('init seeds the first verdict and the initialized marker', () => {
- const workspace = tempDir()
- const { code } = run(manifest.workspace.init, { cwd: workspace, env: { HARNESS_DSH: manifest.id } })
- assert.equal(code, 0)
- const verdict = JSON.parse(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8'))
- assert.equal(verdict.ready, false)
- assert.match(readFileSync(join(workspace, '.harness-initialized'), 'utf8'), new RegExp(manifest.id.replace('/', '/')))
-})
-
-test('file existence cannot turn an unavailable browser proof into a ready verdict', () => {
- const skill = readFileSync(join(here, 'skills/data/SKILL.md'), 'utf8')
- const command = 'sh "$DATA_SKILLS/data/scripts/update-verdict.sh"'
- assert.ok(skill.includes(command), 'SKILL.md should document the one-stop update command')
- assert.equal(manifest.agent.env.DATA_SKILLS, '${dsh}/skills')
-
- const workspace = tempDir()
- writeFileSync(join(workspace, 'index.html'), '<!doctype html><h1>dash</h1>\n')
- writeFileSync(join(workspace, 'data.csv'), 'quarter,region,revenue\n2025-Q1,North,12\n')
- const result = spawnSync('/bin/sh', ['-c', command], {
- cwd: workspace,
- env: { ...process.env, DATA_SKILLS: join(here, 'skills'), HARNESS_WORKSPACE: workspace, PLAYWRIGHT_MODULE: join(workspace, 'missing-playwright.mjs') },
- encoding: 'utf8',
- })
- assert.equal(result.status, 1, result.stderr)
- const verdict = JSON.parse(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8'))
- assert.equal(verdict.ready, false)
- assert.match(verdict.findings[0].message, /Playwright is missing/)
- assert.equal(verdict.artifact, 'index.html')
-})
-
-test('update-verdict.sh reports missing index.html and fails', () => {
- const workspace = tempDir()
- writeFileSync(join(workspace, 'data.csv'), 'q,r,v\n1,2,3\n')
- const result = spawnSync('/bin/sh', ['-c', 'sh "$DATA_SKILLS/data/scripts/update-verdict.sh"'], {
- cwd: workspace,
- env: { ...process.env, DATA_SKILLS: join(here, 'skills'), HARNESS_WORKSPACE: workspace },
- encoding: 'utf8',
- })
- assert.equal(result.status, 1)
- assert.match(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8'), /index\.html missing/)
-})
+const run = (script, work, extra = {}) =>
+ spawnSync("/bin/sh", [join(root, script)], {
+ cwd: work,
+ env: {
+ ...process.env,
+ PATH: dirname(process.execPath) + ":" + process.env.PATH,
+ HARNESS_WORKSPACE: work,
+ HARNESS_DSH: "autonomous/data-studio",
+ ...extra,
+ },
+ encoding: "utf8",
+ timeout: 30000,
+ });
+test("manifest scripts are executable and doctor verifies real native/browser SQLite", async () => {
+ for (const p of [
+ "toolchain/setup.sh",
+ "toolchain/doctor.sh",
+ "toolchain/init-workspace.sh",
+ "toolchain/node.sh",
+ "skills/data/scripts/update-verdict.sh",
+ ])
+ await access(join(root, p), constants.X_OK);
+ const r = run("toolchain/doctor.sh", root);
+ assert.equal(r.status, 0, r.stdout + r.stderr);
+ assert.match(r.stdout, /native SQLite/);
+ assert.match(r.stdout, /pinned SQLite/);
+});
+test("doctor fails when both PATH and managed Node are absent", async () => {
+ const runtime = await mkdtemp(join(tmpdir(), "data-no-node-")),
+ bin = join(runtime, "bin");
+ await mkdir(bin);
+ for (const [name, target] of [
+ ["bash", "/bin/bash"],
+ ["dirname", "/usr/bin/dirname"],
+ ["cat", "/bin/cat"],
+ ])
+ await symlink(target, join(bin, name));
+ const r = run("toolchain/doctor.sh", root, {
+ PATH: bin,
+ ADAPTER_RUNTIME_DIR: runtime,
+ });
+ assert.equal(r.status, 1, r.stdout + r.stderr);
+ assert.match(r.stdout, /miss node/);
+});
+test("actual initializer builds a usable source project but keeps readiness false pending browser proof", async () => {
+ const w = await workspace(),
+ r = run("toolchain/init-workspace.sh", w);
+ assert.equal(r.status, 0, r.stdout + r.stderr);
+ assert.match(
+ await readFile(join(w, ".harness-initialized"), "utf8"),
+ /autonomous\/data-studio/,
+ );
+ assert.equal(
+ JSON.parse(await readFile(join(w, ".harness/verdict.json"))).ready,
+ false,
+ );
+ await access(join(w, "output/analysis.sqlite"));
+ await access(join(w, "output/project.zip"));
+});
+test("missing browser dependency cannot turn a native build into ready", async () => {
+ const w = await workspace(),
+ r = run("skills/data/scripts/update-verdict.sh", w, {
+ PLAYWRIGHT_MODULE: join(w, "missing-playwright.mjs"),
+ });
+ assert.equal(r.status, 1, r.stderr);
+ const v = JSON.parse(await readFile(join(w, ".harness/verdict.json")));
+ assert.equal(v.ready, false);
+ assert.match(v.findings[0].message, /Playwright is missing/);
+});
+test("invalid input clears readiness and keeps the previous useful output", async () => {
+ const w = await workspace();
+ assert.equal(run("toolchain/init-workspace.sh", w).status, 0);
+ const zip = await readFile(join(w, "output/project.zip"));
+ await writeFile(
+ join(w, ".harness/verdict.json"),
+ JSON.stringify({ spec: 1, ready: true }),
+ );
+ await writeFile(join(w, "sources/products.csv"), "wrong,header\nx,y\n");
+ assert.equal(run("skills/data/scripts/update-verdict.sh", w).status, 1);
+ assert.equal(
+ JSON.parse(await readFile(join(w, ".harness/verdict.json"))).ready,
+ false,
+ );
+ assert.deepEqual(await readFile(join(w, "output/project.zip")), zip);
+});
diff --git a/store/agents/data-studio/test/verify-exports.py b/store/agents/data-studio/test/verify-exports.py
new file mode 100644
index 000000000..d2a87375b
--- /dev/null
+++ b/store/agents/data-studio/test/verify-exports.py
@@ -0,0 +1,71 @@
+"""Independent stdlib CSV/Decimal/SQLite checks of actual browser downloads.
+
+Usage: python3 test/verify-exports.py EVIDENCE_DIRECTORY
+No harness parsing or aggregation helper is imported.
+"""
+import csv
+import io
+import json
+import sqlite3
+import sys
+from decimal import Decimal
+from pathlib import Path
+
+root = Path(sys.argv[1])
+if sqlite3.sqlite_version_info < (3, 37, 0):
+ raise SystemExit('This independent reader needs SQLite 3.37+ for STRICT tables. Use a current Python runtime; do not weaken schema validation.')
+sales = json.loads((root / 'sales-saved.data-studio.json').read_text())
+source = sales['bundle']['sources']
+transactions = list(csv.DictReader(io.StringIO(source['sources/transactions.csv'])))
+products = {r['product_id']: r for r in csv.DictReader(io.StringIO(source['sources/products.csv']))}
+assert '001' in products
+totals = {'2026-01': Decimal(0), '2026-02': Decimal(0)}
+monthly = {}
+categories = {}
+for row in transactions:
+ if row['status'] != 'completed':
+ continue
+ net = (int(row['quantity']) * Decimal(row['unit_price_usd'])
+ - Decimal(row['discount_usd']) - Decimal(row['refund_usd']))
+ month = row['sold_on'][:7]
+ if month in totals:
+ totals[month] += net
+ cat = products[row['product_id']]['category']
+ categories[cat] = categories.get(cat, Decimal(0)) + net * (1 if month == '2026-02' else -1)
+ if int(row['quantity']) >= 15:
+ total, count = monthly.get(month, (Decimal(0), 0))
+ monthly[month] = (total + net, count + 1)
+assert totals == {'2026-01': Decimal('4628.50'), '2026-02': Decimal('4366.50')}
+assert sum(categories.values()) == Decimal('-262.00')
+expected = [[month, int(total * 100), count] for month, (total, count) in sorted(monthly.items())]
+actual = json.loads((root / 'sales-current-query.json').read_text())
+assert actual['rows'] == expected
+with sqlite3.connect('file:' + str(root / 'sales-browser.sqlite') + '?mode=ro', uri=True) as db:
+ assert db.execute('PRAGMA integrity_check').fetchone() == ('ok',)
+ assert db.execute('SELECT line_id, unit_price_cents FROM transactions WHERE _record=2').fetchone() == ('00001', 4000)
+ assert [list(r) for r in db.execute(sales['bundle']['sql']['queries/monthly.sql'], {'region': ''})] == expected
+safe_rows = list(csv.reader(io.StringIO((root / 'sales-revised-query.csv').read_text())))
+assert safe_rows[0] == actual['columns']
+assert safe_rows[1:] == [[str(v) for v in r] for r in expected]
+
+delivery = json.loads((root / 'delivery-saved.data-studio.json').read_text())
+rows = list(csv.DictReader(io.StringIO(delivery['bundle']['sources']['sources/shipments.csv'])))
+as_of = delivery['view']['parameters']['as_of']
+delivered = [r for r in rows if r['delivered_on'] and r['delivered_on'] <= as_of]
+on_time = [r for r in delivered if r['delivered_on'] <= r['promised_on']]
+assert (len(rows), len(delivered), len(rows)-len(delivered), len(on_time)) == (18, 16, 2, 8)
+with sqlite3.connect('file:' + str(root / 'delivery-browser.sqlite') + '?mode=ro', uri=True) as db:
+ assert db.execute('PRAGMA integrity_check').fetchone() == ('ok',)
+ assert db.execute('SELECT delivered_on FROM shipments WHERE shipment_id=?', ('0017',)).fetchone() == ('2026-04-19',)
+ assert db.execute('SELECT count(*) FROM shipments WHERE delivered_on IS NULL').fetchone() == (2,)
+ result = db.execute(delivery['bundle']['sql']['queries/headline.sql'], {'as_of': as_of, 'region': ''}).fetchone()
+ assert result == (18, 16, 2, 0.5)
+for report in ['sales-report.html', 'delivery-report.html']:
+ text = (root / report).read_text()
+ assert '<script' not in text.lower()
+ assert 'Synthetic example data' in text
+ assert 'Applied controls' in text
+print(json.dumps({'independentReader': 'Python ' + sys.version.split()[0] + ' / CSV + Decimal + SQLite ' + sqlite3.sqlite_version,
+ 'salesTotalsUSD': {k: str(v) for k, v in totals.items()},
+ 'monthlyRows': expected, 'delivery': {'delivered': 16, 'open': 2, 'onTimeRate': 0.5},
+ 'passed': True}, indent=2))
diff --git a/store/agents/data-studio/toolchain/doctor.sh b/store/agents/data-studio/toolchain/doctor.sh
index 2b8161f7d..9eaeb6e39 100755
--- a/store/agents/data-studio/toolchain/doctor.sh
+++ b/store/agents/data-studio/toolchain/doctor.sh
@@ -1,13 +1,4 @@
#!/bin/sh
-# Exit 0 when this machine can run the Data Studio harness. Print one line per check.
-set -u
-dsh="${HARNESS_DSH_DIR:-$PWD}"
-fail=0
-if command -v node >/dev/null 2>&1; then
- echo "ok node $(node --version 2>/dev/null) at $(command -v node)"
-else
- echo "miss node — run toolchain/setup.sh or install Node.js 20+ from https://nodejs.org"
- fail=1
-fi
-[ -d "$dsh/skills/data" ] && echo "ok data skill" || { echo "warn data skill missing"; fail=1; }
-exit $fail
+set -eu
+here="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
+exec bash "$here/setup.sh"
diff --git a/store/agents/data-studio/toolchain/init-workspace.sh b/store/agents/data-studio/toolchain/init-workspace.sh
index 6903fb46a..4aa183242 100755
--- a/store/agents/data-studio/toolchain/init-workspace.sh
+++ b/store/agents/data-studio/toolchain/init-workspace.sh
@@ -1,9 +1,6 @@
#!/bin/sh
-# Runs once in a fresh workspace (cwd = the workspace) after the template copy.
-set -u
-mkdir -p .harness
-cat > .harness/verdict.json <<'JSON'
-{ "spec": 1, "ready": false, "summary": "Data Studio workspace ready — open data.csv and tell me the view you want",
- "findings": [], "artifact": null, "updatedAt": "2026-09-18T00:00:00Z" }
-JSON
-printf 'Data Studio workspace initialized by %s\n' "${HARNESS_DSH:-data-studio}" > .harness-initialized
+set -eu
+here="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
+workspace="${HARNESS_WORKSPACE:-$PWD}"
+bash "$here/node.sh" "$workspace/tools/build.mjs" "$workspace"
+printf 'Data Studio workspace initialized by %s\n' "${HARNESS_DSH:-autonomous/data-studio}" > "$workspace/.harness-initialized"
diff --git a/store/agents/data-studio/toolchain/node.sh b/store/agents/data-studio/toolchain/node.sh
new file mode 100755
index 000000000..55f6521ca
--- /dev/null
+++ b/store/agents/data-studio/toolchain/node.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+. "$here/runtimes.sh"
+harness_node 22.16 || exit 1
+exec node "$@"
diff --git a/store/agents/data-studio/toolchain/runtimes.sh b/store/agents/data-studio/toolchain/runtimes.sh
new file mode 100644
index 000000000..7223c78dc
--- /dev/null
+++ b/store/agents/data-studio/toolchain/runtimes.sh
@@ -0,0 +1,192 @@
+# shellcheck shell=bash
+# runtimes.sh — the interpreters a store package runs on, found on this machine or fetched, never
+# asked of the person who pressed Get.
+#
+# Sourced (not run) by a package's setup, doctor and viewer scripts. A new Mac has Apple's Python 3.9,
+# no Homebrew and, for most people, no Node on PATH; a package that answers "brew install [email protected]"
+# has failed its install. So:
+#
+# harness_node 18 node >= 18 on PATH, with npm: the machine's own, else the Node Harness
+# itself runs on (~/.harness/runtime/current-node, laid down with the CLI)
+# harness_uv uv on PATH: the machine's own, else a pinned, checksummed release
+# fetched into ~/.harness/runtime
+# harness_venv DIR 3.12 [MIN [BELOW]]
+# DIR is a venv on CPython 3.12, which uv downloads when the machine
+# has none. A venv already there on a Python in [MIN, BELOW) is kept.
+# harness_pip DIR PKG… install into that venv, through uv
+# harness_micromamba micromamba, pinned and checksummed, for native libraries PyPI has
+# no wheel for (pycairo on macOS)
+# harness_conda_env DIR SPEC… DIR is a conda-forge environment with those packages
+#
+# Every function prints `miss …` and returns 1 when it cannot deliver, so `harness_node 18 || exit 1`
+# reads like the rest of a setup script. Nothing here touches the user's shell profile; what it
+# installs lands in ~/.harness/runtime or the package's own directory (uv keeps its download cache
+# where it always does, which a venv does not depend on).
+#
+# ONE copy is written by hand: store/tools/runtimes.sh in the OpenHarness repository. Each package
+# carries an identical copy (a package installs alone, so it cannot reach this one);
+# `node store/tools/sync-runtimes.mjs` rewrites them and the CLI's store spec fails when one drifts.
+
+HARNESS_RUNTIME="${ADAPTER_RUNTIME_DIR:-${HOME:-}/.harness/runtime}"
+# The Pythons uv downloads live with Harness's other runtimes, not in uv's own ~/.local/share/uv:
+# a package's venv points at its interpreter, and `uv python uninstall` there must not break it.
+UV_PYTHON_INSTALL_DIR="${UV_PYTHON_INSTALL_DIR:-$HARNESS_RUNTIME/python}"
+export UV_PYTHON_INSTALL_DIR
+HARNESS_UV_VERSION=0.12.15
+HARNESS_MICROMAMBA_VERSION=2.9.0-0
+
+_harness_platform() {
+ case "$(uname -s)-$(uname -m)" in
+ Darwin-arm64) echo darwin-arm64 ;;
+ Darwin-x86_64) echo darwin-x64 ;;
+ Linux-x86_64) echo linux-x64 ;;
+ Linux-aarch64 | Linux-arm64) echo linux-arm64 ;;
+ *) return 1 ;;
+ esac
+}
+
+_harness_sha256() {
+ if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1
+ else sha256sum "$1" | cut -d' ' -f1; fi
+}
+
+# _harness_fetch URL DEST SHA256 — DEST exists only if what arrived matches the pinned checksum.
+_harness_fetch() {
+ local part="$2.part.$$"
+ if ! curl -fsSL --retry 3 --connect-timeout 20 --max-time 900 -o "$part" "$1"; then
+ rm -f "$part"; echo "miss could not download $1 — check this machine's internet connection"; return 1
+ fi
+ if [ "$(_harness_sha256 "$part")" != "$3" ]; then
+ rm -f "$part"; echo "miss $1 did not match its pinned checksum; nothing was installed"; return 1
+ fi
+ mv -f "$part" "$2"
+}
+
+_harness_node_at_least() {
+ command -v node >/dev/null 2>&1 || return 1
+ node -e '
+ const [a, b = 0] = process.argv[1].split(".").map(Number)
+ const [x, y] = process.versions.node.split(".").map(Number)
+ process.exit(x > a || (x === a && y >= b) ? 0 : 1)
+ ' "$1" >/dev/null 2>&1
+}
+
+harness_node() {
+ local min="${1:-18}" recorded saved="$PATH" own=0
+ _harness_node_at_least "$min" && own=1
+ # A node without npm beside it (a distro's nodejs package) cannot run a setup's `npm ci`.
+ if [ "$own" = 1 ] && command -v npm >/dev/null 2>&1; then return 0; fi
+ recorded="$(cat "$HARNESS_RUNTIME/current-node" 2>/dev/null || true)"
+ # Already Harness's own (a second call, or a wrapper calling a script that asks again): nothing to add.
+ if [ "$own" = 1 ] && [ -n "$recorded" ] && [ "$(command -v node)" = "${recorded%/*}/node" ]; then return 0; fi
+ if [ -n "$recorded" ] && [ -x "${recorded%/*}/node" ]; then
+ PATH="${recorded%/*}:$PATH"; export PATH; hash -r 2>/dev/null || true
+ _harness_node_at_least "$min" && return 0
+ PATH="$saved"; export PATH; hash -r 2>/dev/null || true
+ [ "$own" = 1 ] && return 0
+ echo "miss node >= $min — this machine's newest is $("${recorded%/*}/node" -v), Harness's own; update Harness"
+ return 1
+ fi
+ [ "$own" = 1 ] && return 0
+ echo "miss node >= $min, and Harness's own Node is not in $HARNESS_RUNTIME — run \`harness start\` once to lay it down"
+ return 1
+}
+
+harness_uv() {
+ local dir asset sum tmp
+ command -v uv >/dev/null 2>&1 && return 0
+ for dir in "${HOME:-}/.local/bin" "${HOME:-}/.cargo/bin"; do
+ [ -n "${HOME:-}" ] || break
+ if [ -x "$dir/uv" ]; then PATH="$dir:$PATH"; export PATH; return 0; fi
+ done
+ dir="$HARNESS_RUNTIME/uv-$HARNESS_UV_VERSION"
+ if [ ! -x "$dir/uv" ]; then
+ case "$(_harness_platform)" in
+ darwin-arm64) asset=uv-aarch64-apple-darwin sum=dc304b9ed1b24174572290fba60ac3f6fe63c73a671f0439e62a91375841964d ;;
+ darwin-x64) asset=uv-x86_64-apple-darwin sum=e9ca61775532368fe518ab03e7a354c7ecab8ccb3c7d941c775fcc4a362b801b ;;
+ linux-x64) asset=uv-x86_64-unknown-linux-gnu sum=f97935763c04be3e692460a7aaeaaab8fc3b78fcf8b389da820b38ae7423a638 ;;
+ linux-arm64) asset=uv-aarch64-unknown-linux-gnu sum=0e9a3499b0587d449c9ff684c0160da607826e4af1cee220bc87f378702d3e08 ;;
+ *) echo "miss uv — there is no uv release for $(uname -s) $(uname -m); install it from https://docs.astral.sh/uv/"; return 1 ;;
+ esac
+ echo " fetching uv $HARNESS_UV_VERSION into $HARNESS_RUNTIME (it brings Python and the packages)"
+ mkdir -p "$HARNESS_RUNTIME" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }
+ tmp="$(mktemp -d "$HARNESS_RUNTIME/.uv.XXXXXX")" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }
+ if ! _harness_fetch "https://github.com/astral-sh/uv/releases/download/$HARNESS_UV_VERSION/$asset.tar.gz" "$tmp/uv.tar.gz" "$sum"; then
+ rm -rf "$tmp"; return 1
+ fi
+ tar -xzf "$tmp/uv.tar.gz" -C "$tmp" && chmod +x "$tmp/$asset/uv" "$tmp/$asset/uvx" \
+ || { rm -rf "$tmp"; echo "miss the uv archive would not unpack"; return 1; }
+ # Two installs at once both get here; whichever renames first wins and the other's copy goes.
+ # (mv onto a directory that exists would nest the copy inside it, hence the test.)
+ [ -e "$dir" ] || mv "$tmp/$asset" "$dir" 2>/dev/null || true
+ rm -rf "$tmp"
+ [ -x "$dir/uv" ] || { echo "miss uv did not land in $dir"; return 1; }
+ fi
+ PATH="$dir:$PATH"; export PATH
+}
+
+# harness_venv DIR VERSION [MIN [BELOW]] — MIN defaults to VERSION; BELOW is exclusive and optional.
+harness_venv() {
+ local dir="${1:?harness_venv needs a directory}" want="${2:?harness_venv needs a Python version}"
+ local min="${3:-$2}" below="${4:-}"
+ if [ -x "$dir/bin/python" ] && "$dir/bin/python" -c '
+import sys
+at = lambda s: tuple(int(p) for p in s.split("."))
+v = sys.version_info[:2]
+sys.exit(0 if v >= at(sys.argv[1]) and (not sys.argv[2] or v < at(sys.argv[2])) else 1)
+' "$min" "$below" 2>/dev/null; then
+ echo "ok $("$dir/bin/python" --version) in $dir"
+ return 0
+ fi
+ harness_uv || return 1
+ echo " python $want in $dir (uv downloads it when this machine has none)"
+ rm -rf "$dir"
+ # only-managed: the same python-build-standalone interpreter on every machine, so a package tested
+ # once is tested everywhere — not whichever Homebrew or pyenv Python happened to be first on PATH.
+ uv venv --quiet --seed --python "$want" --python-preference only-managed "$dir" \
+ || { echo "miss could not make a Python $want environment in $dir"; return 1; }
+ echo "ok $("$dir/bin/python" --version) in $dir"
+}
+
+harness_pip() {
+ local dir="${1:?harness_pip needs a venv}"
+ shift
+ harness_uv || return 1
+ # uv's own error comes first; the miss line is last, so it is the line the store shows.
+ uv pip install --quiet --python "$dir/bin/python" "$@" \
+ || { echo "miss could not install $* into $dir"; return 1; }
+}
+
+harness_micromamba() {
+ local dir asset sum
+ dir="$HARNESS_RUNTIME/micromamba-$HARNESS_MICROMAMBA_VERSION"
+ if [ ! -x "$dir/micromamba" ]; then
+ case "$(_harness_platform)" in
+ darwin-arm64) asset=micromamba-osx-arm64 sum=ec2a072f028e1a7cf20f3e2e74d5a8127cf5a5f27636375b5359811565f4e5be ;;
+ darwin-x64) asset=micromamba-osx-64 sum=1e71054bb3ac9a076e21f7ec48acfef536f9b3f1408f371a942784bf5ef83d8a ;;
+ linux-x64) asset=micromamba-linux-64 sum=366cd9cd8be14df1ab8ed50352a82111082a36686b2d389fdb79a92c3fafb3e3 ;;
+ linux-arm64) asset=micromamba-linux-aarch64 sum=9f93b974adcb4d166996af969b6cd371287d1a3e52733704727884d9b74cb7a7 ;;
+ *) echo "miss micromamba — there is no release for $(uname -s) $(uname -m)"; return 1 ;;
+ esac
+ echo " fetching micromamba $HARNESS_MICROMAMBA_VERSION into $HARNESS_RUNTIME (native libraries PyPI has no wheel for)"
+ mkdir -p "$dir" || { echo "miss cannot write $dir"; return 1; }
+ _harness_fetch "https://github.com/mamba-org/micromamba-releases/releases/download/$HARNESS_MICROMAMBA_VERSION/$asset" "$dir/micromamba.$$" "$sum" || return 1
+ chmod +x "$dir/micromamba.$$" && mv -f "$dir/micromamba.$$" "$dir/micromamba" \
+ || { rm -f "$dir/micromamba.$$"; echo "miss micromamba would not install into $dir"; return 1; }
+ fi
+ HARNESS_MICROMAMBA="$dir/micromamba"
+ export HARNESS_MICROMAMBA
+}
+
+# harness_conda_env DIR SPEC… — conda-forge only, packages cached under ~/.harness/runtime/mamba.
+harness_conda_env() {
+ local dir="${1:?harness_conda_env needs a directory}"
+ shift
+ # micromamba takes a relative --prefix as a name under its root prefix and "succeeds" there.
+ case "$dir" in /*) ;; *) dir="$PWD/$dir" ;; esac
+ harness_micromamba || return 1
+ MAMBA_ROOT_PREFIX="$HARNESS_RUNTIME/mamba" "$HARNESS_MICROMAMBA" create --yes --quiet \
+ --prefix "$dir" --override-channels --channel conda-forge "$@" >/dev/null \
+ && [ -d "$dir/conda-meta" ] \
+ || { echo "miss could not make the conda-forge environment in $dir ($*)"; return 1; }
+}
diff --git a/store/agents/data-studio/toolchain/setup.sh b/store/agents/data-studio/toolchain/setup.sh
index 0024cf785..49b4f6769 100755
--- a/store/agents/data-studio/toolchain/setup.sh
+++ b/store/agents/data-studio/toolchain/setup.sh
@@ -1,12 +1,10 @@
-#!/bin/sh
-# Install/verify the runtime for this harness. cwd = the package install dir.
-# Data Studio is web-native: the shared isolated-web-viewer renders index.html in the pane. The only
-# local runtime the harness needs is Node (it drives the data helpers and the test suite).
-set -u
-dsh="${HARNESS_DSH_DIR:-$PWD}"
-if command -v node >/dev/null 2>&1; then
- echo "ok node $(node --version 2>/dev/null) at $(command -v node)"
- exit 0
-fi
-echo "miss node — install Node.js 20+ from https://nodejs.org (or via nvm/brew) and re-run setup."
-exit 1
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+. "$here/runtimes.sh"
+harness_node 22.16 || exit 1
+node --input-type=module -e 'import {DatabaseSync} from "node:sqlite"; const d=new DatabaseSync(":memory:"); const s=d.prepare("SELECT 1 AS ok"); if(s.columns()[0].name!=="ok")process.exit(1);d.close();'
+node --input-type=module -e 'import {readFileSync} from "node:fs";import {createHash} from "node:crypto";const base=process.argv[1],pins=JSON.parse(readFileSync(base+"/checksums.json"));for(const n of ["sqlite3.js","sqlite3.wasm"]){if(createHash("sha256").update(readFileSync(base+"/"+n)).digest("hex")!==pins[n])throw new Error("SQLite asset checksum mismatch: "+n)}' "$here/../template/vendor"
+echo "ok node $(node --version) with native SQLite"
+echo "ok pinned SQLite 3.53.4 browser runtime"
+test -f "$here/../skills/data/SKILL.md" && echo "ok data analysis skill"
diff --git a/store/showcase/data-studio/delivery.jpg b/store/showcase/data-studio/delivery.jpg
new file mode 100644
index 000000000..a6008a445
Binary files /dev/null and b/store/showcase/data-studio/delivery.jpg differ
diff --git a/store/showcase/data-studio/evidence.jpg b/store/showcase/data-studio/evidence.jpg
new file mode 100644
index 000000000..9bc622cae
Binary files /dev/null and b/store/showcase/data-studio/evidence.jpg differ
diff --git a/store/showcase/data-studio/starter.jpg b/store/showcase/data-studio/starter.jpg
index 4137b0389..bd595614e 100644
Binary files a/store/showcase/data-studio/starter.jpg and b/store/showcase/data-studio/starter.jpg differ
diff --git a/store/tools/REAL-WORKFLOWS.md b/store/tools/REAL-WORKFLOWS.md
index d72575ba0..9172c0d10 100644
--- a/store/tools/REAL-WORKFLOWS.md
+++ b/store/tools/REAL-WORKFLOWS.md
@@ -21,7 +21,7 @@ catalog workflow and verify the live catalog after each accepted release.
| 2 | score | Musical brief and player constraints → revised score, audible mix, individual parts and practice exports | Implemented and validated; relisted in this change. See [acceptance evidence](../agents/score/test/ACCEPTANCE.md). |
| 3 | openscad | Dimensions and fabrication constraints → parametric parts, verified variants and usable exports | Implemented and validated; relisted in this change. See [acceptance evidence](../agents/openscad/test/ACCEPTANCE.md). |
| 4 | orca-slicer | User mesh and explicit machine/material profiles → compared slicing options and reviewed toolpath handoff | Implemented and validated; relisted in this change. See [acceptance evidence](../agents/orca-slicer/test/ACCEPTANCE.md). |
-| 5 | data-studio | User data and a question → saved analysis, source-linked results and repeatable report | Not started; unlisted |
+| 5 | data-studio | User data and a question → saved analysis, source-linked results and repeatable report | Implemented and validated; relisted in this change. See [acceptance evidence](../agents/data-studio/test/ACCEPTANCE.md). |
| 6 | gis | User geographic data and a decision → reproducible spatial analysis and exported results | Not started; unlisted |
| 7 | web-studio | User application brief → useful app with durable data and a runnable handoff | Not started; unlisted |
| 8 | sheet-docs | User document/data requirements → editable, recalculated and reconciled deliverables | Not started; unlisted |