@dashspec/renderer 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,90 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@dashspec/renderer` are documented here.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this
6
+ project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). The dashboard
7
+ JSON format (`dashspec.dev/v2`) has its own promise: within v2 there are only optional
8
+ additions, so a saved dashboard keeps rendering the same way on every later version
9
+ (see [MAINTAINING.md](MAINTAINING.md#1-the-compatibility-contract)).
10
+
11
+ Each entry goes under **Unreleased** in the pull request that makes the change, in one of
12
+ these groups: Added, Changed, Deprecated, Removed, Fixed, Security. A release moves them
13
+ under the new version.
14
+
15
+ ## [Unreleased]
16
+
17
+ ## [0.1.1] - 2026-11-18
18
+
19
+ ### Fixed
20
+
21
+ - The grid now follows the dashboard's width after mount. A dashboard that was first measured
22
+ narrow (for example while the host page was still laying out) stayed in the one-column phone
23
+ layout at any width.
24
+
25
+ ## [0.1.0] - 2026-11-18
26
+
27
+ First public release.
28
+
29
+ ### Added
30
+
31
+ - `DashboardRenderer`: renders a `dashspec.dev/v2` dashboard document — grid layouts per
32
+ view and breakpoint (desktop, tablet, mobile, TV; explicit positions or automatic
33
+ `flow` / `stack`), a filter bar, pop-ups, drill-down, URL sync and TV mode.
34
+ - `DashSpecProvider`: register design systems, widgets, named themes, actions, functions,
35
+ datasource types, network settings and host hooks once for the whole app; renderers
36
+ inside use them and can override them.
37
+ - 30 built-in widgets: KPI, tiles, bar / line / pie / scatter / gauge / matrix charts,
38
+ breakdown, table, stage tracker, state timeline, status, card grid, image map,
39
+ sparkline, content (Markdown), image, filter, the layout nodes container / row / column
40
+ / card / tabs / repeater, and the atoms text / value / progress / icon / divider.
41
+ - Nesting: any widget can hold others in named slots (header, footer, body, items, one
42
+ per tab, repeater item), at any depth; data flows from parent to child.
43
+ - Data: http, GraphQL, SSE and WebSocket (with automatic reconnect), static and
44
+ host-provided datasources; derived datasources with transforms (filter, map, group and
45
+ aggregate, pivot, sort, limit, pick, sandboxed code); connections with base URLs per
46
+ host, bearer / API key / cookie / header auth, token refresh, retries and caching.
47
+ - Events and actions: 28 built-in actions (filters, state, pop-ups, views, drill-down,
48
+ show/hide, refresh, HTTP calls, navigation, export, toasts…), named actions, `watch`
49
+ on any state path, and your own namespaced actions.
50
+ - Bring your own design system: `defineDesignSystem`, `combineDesignSystems`,
51
+ `wrapComponent`, `defineWidget`, `lazyWidget`, aliases, your own filter controls and
52
+ empty / error / loading states.
53
+ - Theming: design tokens as `--ds-*` CSS variables, `createTheme`, light / dark / auto,
54
+ named themes picked by the document (`display.theme`), chart themes from the same tokens.
55
+ - State access for the host: change callbacks, controlled `variables` / `state` / `view`,
56
+ an imperative handle (`ref`), and `useDashboardState` / `useDashboardActions` by id.
57
+ - `@dashspec/renderer/core` (no React): `loadDocument`, `validateDocument` with
58
+ forward-compatible reading (unknown fields and values are warnings with "did you
59
+ mean"), migration from v1 documents, the expression language, the HTTP client,
60
+ transforms, `safeLink`, `RENDERER_VERSION` and `satisfies`.
61
+ - The main entry also exports everything in `/core`, and `widgetChecks` so documents can be
62
+ validated against your own widgets.
63
+ - `builtInWidgetChecks` in `/core`: validates built-in widget props without React, e.g.
64
+ `loadDocument(json, { widgets: builtInWidgetChecks })` in a React Server Component.
65
+ - `@dashspec/renderer/sandbox`: a QuickJS sandbox for custom code in documents, with time
66
+ and memory limits; loaded only when a document has code.
67
+ - `@dashspec/renderer/schema.json`: the JSON Schema of the document, for editor
68
+ autocompletion.
69
+ - Dashboard settings: a filters drawer (`display.filters: "drawer"`), a guided tour
70
+ (`spec.tour`), translations (`display.translations` with `${t.key}` in templates), a
71
+ per-panel loading message (`messages.loading`) and theme `density` (compact,
72
+ comfortable, spacious).
73
+ - GraphQL datasources send a real GraphQL request (`query` + templated `variables`) and
74
+ report GraphQL `errors`; a document with exactly one connection uses it by default.
75
+ - Host `data` and `context` can change after mount and the dashboard follows.
76
+ - Document metadata: `metadata.generator` (the tool that wrote it) and
77
+ `spec.requires.renderer` (the renderer version it needs; older renderers warn).
78
+ - Works with React 18 and 19, server rendering and the Next.js App Router.
79
+
80
+ ### Security
81
+
82
+ - Documents are treated as untrusted input: links are checked after templates are
83
+ filled (`javascript:` and other schemes refused), stored credentials go only to trusted
84
+ origins (`trustedOrigins`), values in request paths are URL-encoded, lookups by name
85
+ never reach object prototypes, values inserted into Markdown are escaped, and custom
86
+ code runs in the sandbox by default. See [docs/security.md](docs/security.md).
87
+
88
+ [Unreleased]: https://github.com/vaskar-nowpurchase/dashspec-renderer/compare/v0.1.1...HEAD
89
+ [0.1.1]: https://github.com/vaskar-nowpurchase/dashspec-renderer/compare/v0.1.0...v0.1.1
90
+ [0.1.0]: https://github.com/vaskar-nowpurchase/dashspec-renderer/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DashSpec contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,318 @@
1
- # Temporary Holding Version
1
+ # @dashspec/renderer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@dashspec/renderer.svg)](https://www.npmjs.com/package/@dashspec/renderer)
4
+ [![CI](https://github.com/vaskar-nowpurchase/dashspec-renderer/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/vaskar-nowpurchase/dashspec-renderer/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/@dashspec/renderer.svg)](LICENSE)
6
+
7
+ **Render complete, interactive dashboards from JSON, in any React app, with any design system.**
8
+
9
+ You describe a dashboard once as a JSON document (layout, filters, data sources, widgets,
10
+ what happens on click), and `<DashboardRenderer>` draws it. A new dashboard, or a new
11
+ version of one, is a new document — not new frontend code and not a redeploy.
12
+
13
+ - **30 built-in widgets**: KPIs, charts, tables, tiles, status, layout containers and
14
+ small building blocks, nestable at any depth.
15
+ - **Data built in**: REST, GraphQL, SSE and WebSocket sources, auth and token refresh,
16
+ caching, polling, transforms.
17
+ - **Interactive**: global filters, cross-filtering, drill-down, pop-ups, 28 actions,
18
+ shared state, URL sync.
19
+ - **Yours to style and extend**: plug in your design system's components, controls and
20
+ themes; register your own widgets and actions once with `DashSpecProvider`.
21
+ - **Safe with untrusted documents**: links, requests, credentials and custom code are
22
+ checked and sandboxed.
23
+ - **Stable format**: documents written today keep rendering the same way; newer
24
+ documents degrade gracefully on older renderers.
25
+
26
+ Works with React 18 and 19, server rendering and the Next.js App Router.
27
+
28
+ ## Contents
29
+
30
+ - [Install](#install)
31
+ - [Quick start](#quick-start)
32
+ - [Set things up once: `DashSpecProvider`](#set-things-up-once-dashspecprovider)
33
+ - [Loading and validating documents](#loading-and-validating-documents)
34
+ - [Data and authentication](#data-and-authentication)
35
+ - [Your own widgets and design system](#your-own-widgets-and-design-system)
36
+ - [Theming](#theming)
37
+ - [State, events and actions](#state-events-and-actions)
38
+ - [Server rendering and Next.js](#server-rendering-and-nextjs)
39
+ - [Security](#security)
40
+ - [Entry points](#entry-points)
41
+ - [Documentation and examples](#documentation-and-examples)
42
+ - [Compatibility and versioning](#compatibility-and-versioning)
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ npm install @dashspec/renderer react react-dom zod
48
+ # or: pnpm add / yarn add
49
+ ```
50
+
51
+ `react` and `react-dom` (18 or 19) and `zod` (3.23+) are peer dependencies: you already
52
+ have React, and you use zod to describe your own widgets' props.
53
+
54
+ ## Quick start
55
+
56
+ A dashboard document:
57
+
58
+ ```json
59
+ {
60
+ "apiVersion": "dashspec.dev/v2",
61
+ "kind": "Dashboard",
62
+ "metadata": { "key": "sales", "name": "Sales" },
63
+ "spec": {
64
+ "variables": [{ "name": "region", "kind": "Select", "label": "Region", "options": ["North", "South"] }],
65
+ "datasources": {
66
+ "orders": {
67
+ "type": "static",
68
+ "data": [
69
+ { "region": "North", "month": "Jan", "revenue": 120 },
70
+ { "region": "North", "month": "Feb", "revenue": 150 },
71
+ { "region": "South", "month": "Jan", "revenue": 90 },
72
+ { "region": "South", "month": "Feb", "revenue": 110 }
73
+ ]
74
+ },
75
+ "inRegion": { "from": "orders", "transform": [{ "filter": "!filters.region || region == filters.region" }] },
76
+ "total": { "from": "inRegion", "transform": [{ "sum": "revenue" }] }
77
+ },
78
+ "panels": {
79
+ "revenue": { "kind": "Kpi", "spec": { "title": "Revenue", "data": { "source": "total", "path": "revenue" }, "unit": "k$" } },
80
+ "byMonth": { "kind": "BarChart", "spec": { "title": "By month", "data": { "source": "inRegion" }, "x": "month", "y": "revenue" } }
81
+ },
82
+ "layouts": [
83
+ { "breakpoint": "desktop", "items": [
84
+ { "panel": "revenue", "x": 0, "y": 0, "w": 4, "h": 5 },
85
+ { "panel": "byMonth", "x": 4, "y": 0, "w": 8, "h": 8 }
86
+ ] },
87
+ { "breakpoint": "mobile", "auto": "flow" }
88
+ ]
89
+ }
90
+ }
91
+ ```
92
+
93
+ Render it:
94
+
95
+ ```tsx
96
+ import { DashboardRenderer } from "@dashspec/renderer";
97
+ import sales from "./sales.json";
98
+
99
+ export function SalesPage() {
100
+ return <DashboardRenderer document={sales} />;
101
+ }
102
+ ```
103
+
104
+ That's a working dashboard: a region filter, a KPI and a chart that follow the filter, and
105
+ a phone layout. The `document` prop takes the dashboard JSON as an object — from a file,
106
+ your API or a database. Older (v1) documents are upgraded automatically.
107
+
108
+ Next: the [getting-started guide](docs/getting-started.md) and the complete
109
+ [JSON format](docs/json-format.md).
110
+
111
+ ## Set things up once: `DashSpecProvider`
112
+
113
+ Register what your dashboards may use once, at the top of your app. Every
114
+ `DashboardRenderer` inside uses it, and documents refer to it by name:
115
+
116
+ ```tsx
117
+ import { DashSpecProvider, createTheme } from "@dashspec/renderer";
118
+
119
+ const themes = {
120
+ "acme-light": createTheme({ name: "acme-light", mode: "light", colors: { primary: "#0b5fff" } }),
121
+ "acme-dark": createTheme({ name: "acme-dark", mode: "dark", colors: { primary: "#4d8dff" } }),
122
+ };
123
+
124
+ export function Root() {
125
+ return (
126
+ <DashSpecProvider
127
+ designSystems={[acme]} // components "acme.*", filter controls, theme
128
+ widgets={[furnaceGauge]} // more components: "kind": "acme.FurnaceGauge"
129
+ themes={themes} // "display": { "theme": "acme-dark" }
130
+ theme={themes["acme-light"]} // when a document names no theme
131
+ actions={{ "acme.notify": (a) => notify(a) }} // "do": "acme.notify"
132
+ getToken={() => auth.currentToken()} // connections with "token": { "from": "host" }
133
+ trustedOrigins={["https://api.example.com"]}
134
+ onError={(e) => log.warn(e.code, e.message)}
135
+ >
136
+ <App />
137
+ </DashSpecProvider>
138
+ );
139
+ }
140
+ ```
141
+
142
+ A renderer's own props win over the provider's. Providers nest: lists (`designSystems`,
143
+ `widgets`, `datasourceTypes`, `trustedOrigins`) are combined, maps (`ui`, `aliases`,
144
+ `actions`, `functions`, `themes`, `context`, `data`, `connections`) are merged, and any other
145
+ setting comes from the innermost place that sets it. Every setting is listed in the
146
+ [API reference](docs/api.md#dashspecprovider).
147
+
148
+ ## Loading and validating documents
149
+
150
+ Every document is migrated and validated before it renders. Unknown fields and values are
151
+ **warnings** with "did you mean" hints, so a document from a newer version still opens;
152
+ real errors show an "invalid dashboard" message instead of a broken page.
153
+
154
+ Validate wherever you save documents (an API, CI, an AI tool) — `@dashspec/renderer/core`
155
+ has no React and runs anywhere:
156
+
157
+ ```ts
158
+ import { loadDocument } from "@dashspec/renderer/core";
159
+
160
+ const result = loadDocument(json);
161
+ if (result.status === "invalid") {
162
+ for (const p of result.problems) console.log(p.severity, p.path, p.code, p.message);
163
+ }
164
+ ```
165
+
166
+ To check widget props too, pass your widgets:
167
+ `loadDocument(json, { widgets: widgetChecks(createWidgetRegistry(builtInWidgets, myWidgets)) })`.
168
+ For editors, `@dashspec/renderer/schema.json` is the JSON Schema (`"$schema"` gives
169
+ autocompletion).
170
+
171
+ ## Data and authentication
172
+
173
+ Documents declare connections and datasources; your app supplies credentials:
174
+
175
+ ```json
176
+ "connections": {
177
+ "api": { "baseUrl": { "app.example.com": "https://api.example.com/v1/", "*": "/api/v1/" },
178
+ "auth": { "type": "bearer", "token": { "from": "host" } } }
179
+ },
180
+ "datasources": {
181
+ "orders": { "type": "http", "connection": "api", "path": "/orders",
182
+ "query": { "region": "${filters.region}" }, "refresh": { "every": "60s" } }
183
+ }
184
+ ```
185
+
186
+ `getToken(connectionName)` returns the current token; it is read on every request and
187
+ refreshed on a 401 (`refreshToken`). Tokens never go in the document. `${…}` templates fill
188
+ values from filters, state and data, and a datasource reloads when what it reads changes.
189
+ SSE and WebSocket sources reconnect automatically. See [docs/data.md](docs/data.md).
190
+
191
+ ## Your own widgets and design system
192
+
193
+ Use any React component as a widget:
194
+
195
+ ```tsx
196
+ import { wrapComponent, defineDesignSystem } from "@dashspec/renderer";
197
+ import { z } from "zod";
198
+
199
+ const DataGrid = wrapComponent(AcmeDataGrid, {
200
+ kind: "acme.DataGrid", // "kind" in the JSON
201
+ meta: { label: "Data grid" },
202
+ schema: z.object({ dense: z.boolean().optional() }),
203
+ events: { onRowActivate: "rowClick" }, // component callback → DashSpec event
204
+ });
205
+
206
+ export const acme = defineDesignSystem({
207
+ name: "Acme",
208
+ widgets: [DataGrid],
209
+ ui: { Select: AcmeSelect, DateRange: AcmeDateRange }, // DashSpec's filter bar uses your controls
210
+ theme: acmeTheme,
211
+ });
212
+ ```
213
+
214
+ Widgets written with `defineWidget` get the data, the dashboard state (`store`), events
215
+ (`emit`) and nested children (`renderSlot`). `aliases` swaps a built-in for yours in every
216
+ document (`{ "Table": "acme.DataGrid" }`). See [docs/widgets.md](docs/widgets.md) and
217
+ [docs/design-systems.md](docs/design-systems.md).
218
+
219
+ ## Theming
220
+
221
+ Everything is styled from design tokens exposed as `--ds-*` CSS variables. Build a theme
222
+ with `createTheme` (a short form of brand colours, font, radius and density, or full
223
+ overrides per light and dark mode), and let documents pick a registered theme by name with
224
+ `"display": { "theme": "acme-dark" }`. See [docs/theming.md](docs/theming.md).
225
+
226
+ ## State, events and actions
227
+
228
+ Each dashboard has one state tree (filters, widget selections and pages, view, data…).
229
+ Documents react to events with actions:
230
+
231
+ ```json
232
+ "on": { "rowClick": [{ "do": "setVariable", "name": "order", "value": "${event.datum.id}" },
233
+ { "do": "openModal", "modal": "orderDetails" }] }
234
+ ```
235
+
236
+ Your app can follow and drive the same state:
237
+
238
+ ```tsx
239
+ <DashboardRenderer
240
+ id="sales"
241
+ ref={handleRef} // getState, setVariable, refresh, run, exportData…
242
+ document={doc}
243
+ variables={{ region: selectedRegion }} // controlled filters
244
+ onVariableChange={(name, value) => save(name, value)}
245
+ />
246
+
247
+ // anywhere else in the app:
248
+ const region = useDashboardState("sales", (t) => t.filters.region);
249
+ const { setVariable } = useDashboardActions("sales");
250
+ ```
251
+
252
+ All 28 actions, `watch`, host actions and scripts: [docs/state-and-events.md](docs/state-and-events.md).
253
+
254
+ ## Server rendering and Next.js
255
+
256
+ The React entry is marked `"use client"`, so it works in the Next.js App Router as is.
257
+ Load and validate documents on the server with `@dashspec/renderer/core`, render them in a
258
+ client component. Theme and URL state hydrate without mismatches. See
259
+ [docs/server-rendering.md](docs/server-rendering.md).
260
+
261
+ ## Security
262
+
263
+ Dashboard documents are often written by people other than the app's developers (other
264
+ teams, end users through a builder, AI tools), so the renderer treats them as untrusted:
265
+
266
+ - links open only `http(s)`, `mailto` and same-site paths — checked after templates are filled;
267
+ - tokens come from your app (`getToken`); tokens kept in browser storage are sent only to
268
+ origins you trust (`trustedOrigins`);
269
+ - values placed in request paths are URL-encoded;
270
+ - custom code in documents runs in a QuickJS sandbox with time and memory limits (the
271
+ default `scripts="sandbox"`);
272
+ - names from a document never reach object prototypes; values inserted into Markdown are escaped.
273
+
274
+ Details, and what your app should do (Content Security Policy for the sandbox, etc.):
275
+ [docs/security.md](docs/security.md). To report a vulnerability, see [SECURITY.md](SECURITY.md).
276
+
277
+ ## Entry points
278
+
279
+ | Import | Contains | React |
280
+ |---|---|---|
281
+ | `@dashspec/renderer` | `DashboardRenderer`, `DashSpecProvider`, widgets, theming, design systems, state hooks — and everything in `/core` | yes (`"use client"`) |
282
+ | `@dashspec/renderer/core` | `loadDocument`, `validateDocument`, schemas, migration, expressions, HTTP client, transforms, `safeLink`, `RENDERER_VERSION`, `satisfies` | no |
283
+ | `@dashspec/renderer/sandbox` | `createSandboxRunner` (loaded automatically when a document has code) | no |
284
+ | `@dashspec/renderer/schema.json` | JSON Schema of the document | — |
285
+
286
+ Two names differ between the main entry and `/core`: in the main entry `Grid` is the React
287
+ grid and `StatusTone` the theme type; in `/core` they are the document schemas.
288
+
289
+ ## Documentation and examples
290
+
291
+ - [Getting started](docs/getting-started.md)
292
+ - [JSON format](docs/json-format.md) — every part of a document
293
+ - [Widgets](docs/widgets.md) — built-ins, nesting, writing your own
294
+ - [Design systems](docs/design-systems.md) · [Theming](docs/theming.md)
295
+ - [Data and connections](docs/data.md) · [State, events and actions](docs/state-and-events.md)
296
+ - [Server rendering](docs/server-rendering.md) · [Security](docs/security.md)
297
+ - [API reference](docs/api.md)
298
+ - [Examples](examples/README.md): ready-to-use dashboard JSON, code snippets, a Vite app
299
+ and a Next.js setup
300
+
301
+ The guides also ship inside the package (`node_modules/@dashspec/renderer/docs`).
302
+
303
+ ## Compatibility and versioning
304
+
305
+ - React 18 and 19 (both tested in CI); modern browsers; Node 18+ for `/core`.
306
+ - The package follows [semantic versioning](https://semver.org). The dashboard format
307
+ `dashspec.dev/v2` only gains optional additions, so saved documents keep working; a
308
+ document can state the renderer it needs with `"spec": { "requires": { "renderer": ">=0.2.0" } }`.
309
+ - What changed in each version: [CHANGELOG.md](CHANGELOG.md).
310
+
311
+ ## Contributing
312
+
313
+ Issues and pull requests are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). Please
314
+ follow the [code of conduct](CODE_OF_CONDUCT.md).
315
+
316
+ ## License
317
+
318
+ [MIT](LICENSE)
@@ -0,0 +1,254 @@
1
+ import {
2
+ BLOCKED,
3
+ ScriptError,
4
+ getPath
5
+ } from "./chunk-NLKXHTLO.js";
6
+
7
+ // src/runtime/scripts/sandbox.ts
8
+ import releaseSync from "@jitl/quickjs-wasmfile-release-sync";
9
+ import {
10
+ newQuickJSWASMModuleFromVariant,
11
+ shouldInterruptAfterDeadline
12
+ } from "quickjs-emscripten-core";
13
+ var PRELUDE = `
14
+ (() => {
15
+ const g = globalThis;
16
+ const get = g.__get, set = g.__set, keys = g.__keys, run = g.__do, call = g.__call;
17
+ for (const k of ["__get", "__set", "__keys", "__do", "__call"]) delete g[k];
18
+ const wrap = (path) => new Proxy({}, {
19
+ get(_, k) {
20
+ if (typeof k !== "string") return undefined;
21
+ if (k === "toJSON") return () => JSON.parse(get(JSON.stringify(path)));
22
+ const p = [...path, k];
23
+ const v = JSON.parse(get(JSON.stringify(p)));
24
+ return v !== null && typeof v === "object" ? wrap(p) : v;
25
+ },
26
+ set(_, k, v) { set(JSON.stringify([...path, k]), JSON.stringify(v === undefined ? null : v)); return true; },
27
+ deleteProperty(_, k) { set(JSON.stringify([...path, k]), "null"); return true; },
28
+ has(_, k) { return JSON.parse(keys(JSON.stringify(path))).includes(k); },
29
+ ownKeys() { return JSON.parse(keys(JSON.stringify(path))); },
30
+ getOwnPropertyDescriptor(_, k) {
31
+ const v = JSON.parse(get(JSON.stringify([...path, k])));
32
+ return v === undefined ? undefined : { enumerable: true, configurable: true, writable: true, value: v };
33
+ },
34
+ });
35
+ const json = (s) => JSON.parse(s);
36
+ g.__state = wrap([]);
37
+ g.__api = Object.freeze({
38
+ fetch: (source, params) => call("fetch", JSON.stringify([source, params])).then(json),
39
+ http: (connection, request) => call("http", JSON.stringify([connection, request])).then(json),
40
+ call: (fn, args) => call("call", JSON.stringify([fn, args])).then(json),
41
+ refresh: (source) => { run("refresh", JSON.stringify([source])); },
42
+ navigate: (to) => { run("navigate", JSON.stringify([to])); },
43
+ toast: (message, tone) => { run("toast", JSON.stringify([message, tone])); },
44
+ emit: (event, payload) => { run("emit", JSON.stringify([event, payload])); },
45
+ });
46
+ })();
47
+ `;
48
+ var HARDEN = `
49
+ (() => {
50
+ "use strict";
51
+ const g = globalThis;
52
+ for (const name of Object.getOwnPropertyNames(g)) {
53
+ const v = g[name];
54
+ if ((typeof v === "function" || (v && typeof v === "object")) && v !== g) {
55
+ Object.freeze(v);
56
+ if (typeof v === "function" && v.prototype) Object.freeze(v.prototype);
57
+ }
58
+ }
59
+ Object.freeze(Object.getPrototypeOf(function* () {}));
60
+ Object.freeze(Object.getPrototypeOf(async function () {}));
61
+ Object.freeze(g);
62
+ })();
63
+ `;
64
+ var modulePromise;
65
+ var loadQuickJS = () => {
66
+ modulePromise ??= newQuickJSWASMModuleFromVariant(releaseSync);
67
+ return modulePromise;
68
+ };
69
+ var toJson = (v) => {
70
+ const x = v === void 0 ? null : v;
71
+ try {
72
+ return JSON.stringify(x);
73
+ } catch {
74
+ const path = [];
75
+ return JSON.stringify(x, function(_k, val) {
76
+ if (val && typeof val === "object") {
77
+ while (path.length && path[path.length - 1] !== this) path.pop();
78
+ if (path.includes(val)) return void 0;
79
+ path.push(val);
80
+ }
81
+ return val;
82
+ });
83
+ }
84
+ };
85
+ var statePath = (p) => {
86
+ const path = JSON.parse(p);
87
+ if (!Array.isArray(path) || path.length === 0 || !path.every((k) => typeof k === "string" && !BLOCKED.has(k) || typeof k === "number" && Number.isInteger(k)))
88
+ throw new ScriptError("Invalid state path");
89
+ return path;
90
+ };
91
+ async function createSandboxRunner(opts = {}) {
92
+ const QuickJS = await loadQuickJS();
93
+ const syncMs = opts.syncTimeoutMs ?? 1e3;
94
+ const fnMs = opts.fnPropTimeoutMs ?? 50;
95
+ const asyncMs = opts.asyncTimeoutMs ?? 3e4;
96
+ const memory = opts.memoryBytes ?? 32 * 1024 * 1024;
97
+ const newVm = () => {
98
+ const vm = QuickJS.newContext();
99
+ vm.runtime.setMemoryLimit(memory);
100
+ vm.runtime.setMaxStackSize(1024 * 1024);
101
+ return vm;
102
+ };
103
+ const arm = (vm, ms = syncMs) => vm.runtime.setInterruptHandler(shouldInterruptAfterDeadline(Date.now() + ms));
104
+ const unwrap = (vm, r) => {
105
+ if (r.error) {
106
+ const e = vm.dump(r.error);
107
+ r.error.dispose();
108
+ throw new ScriptError(
109
+ typeof e === "object" && e && "message" in e ? String(e.message) : String(e)
110
+ );
111
+ }
112
+ return r.value;
113
+ };
114
+ const fn = (vm, name, impl) => {
115
+ const h = vm.newFunction(name, (...args) => {
116
+ const out = impl(...args.map((a) => vm.getString(a)));
117
+ return out === void 0 ? vm.undefined : vm.newString(out);
118
+ });
119
+ vm.setProp(vm.global, name, h);
120
+ h.dispose();
121
+ };
122
+ const hardenedVm = () => {
123
+ const vm = newVm();
124
+ arm(vm);
125
+ unwrap(vm, vm.evalCode(HARDEN)).dispose();
126
+ return vm;
127
+ };
128
+ let syncVm = hardenedVm();
129
+ const runSync = (src, ms) => {
130
+ arm(syncVm, ms);
131
+ try {
132
+ const h = unwrap(syncVm, syncVm.evalCode(src));
133
+ const s = syncVm.getString(h);
134
+ h.dispose();
135
+ return JSON.parse(s);
136
+ } catch (e) {
137
+ syncVm.dispose();
138
+ syncVm = hardenedVm();
139
+ throw e;
140
+ }
141
+ };
142
+ return {
143
+ async callback(code, event, state, api) {
144
+ const vm = newVm();
145
+ const pending = /* @__PURE__ */ new Set();
146
+ try {
147
+ const live = state;
148
+ const root = () => live.toJSON();
149
+ fn(vm, "__get", (p) => toJson(getPath(root(), JSON.parse(p))));
150
+ fn(vm, "__keys", (p) => {
151
+ const v2 = getPath(root(), JSON.parse(p));
152
+ return JSON.stringify(v2 && typeof v2 === "object" ? Object.keys(v2) : []);
153
+ });
154
+ fn(vm, "__set", (p, v2) => {
155
+ const path = statePath(p);
156
+ let target = live;
157
+ for (const k of path.slice(0, -1)) {
158
+ target = target[k];
159
+ if (!target || typeof target !== "object") throw new ScriptError(`Can't write state.${path.join(".")}`);
160
+ }
161
+ target[path[path.length - 1]] = JSON.parse(
162
+ v2
163
+ );
164
+ return void 0;
165
+ });
166
+ fn(vm, "__do", (name, args) => {
167
+ const a = JSON.parse(args);
168
+ api[name](...a);
169
+ return void 0;
170
+ });
171
+ const call = vm.newFunction("__call", (nameH, argsH) => {
172
+ const name = vm.getString(nameH);
173
+ const args = JSON.parse(vm.getString(argsH));
174
+ const promise = vm.newPromise();
175
+ const p = api[name](args[0], args[1]).then(
176
+ (v2) => {
177
+ if (!vm.alive) return;
178
+ const h = vm.newString(toJson(v2));
179
+ promise.resolve(h);
180
+ h.dispose();
181
+ },
182
+ (e) => {
183
+ if (!vm.alive) return;
184
+ const h = vm.newError(e.message ?? String(e));
185
+ promise.reject(h);
186
+ h.dispose();
187
+ }
188
+ ).finally(() => {
189
+ pending.delete(p);
190
+ if (vm.alive) {
191
+ arm(vm);
192
+ vm.runtime.executePendingJobs();
193
+ }
194
+ });
195
+ pending.add(p);
196
+ promise.settled.then(() => vm.alive && vm.runtime.executePendingJobs());
197
+ return promise.handle;
198
+ });
199
+ vm.setProp(vm.global, "__call", call);
200
+ call.dispose();
201
+ arm(vm);
202
+ unwrap(vm, vm.evalCode(PRELUDE)).dispose();
203
+ const fnH = unwrap(vm, vm.evalCode(`(${code})`));
204
+ const evH = unwrap(vm, vm.evalCode(`(${toJson(event)})`));
205
+ const stateH = vm.getProp(vm.global, "__state");
206
+ const apiH = vm.getProp(vm.global, "__api");
207
+ const result = vm.callFunction(fnH, vm.undefined, evH, stateH, apiH);
208
+ for (const h of [fnH, evH, stateH, apiH]) h.dispose();
209
+ const resH = unwrap(vm, result);
210
+ const settled = vm.resolvePromise(resH);
211
+ resH.dispose();
212
+ vm.runtime.executePendingJobs();
213
+ let timer;
214
+ const out = await Promise.race([
215
+ settled,
216
+ new Promise((_, rej) => {
217
+ timer = setTimeout(() => rej(new ScriptError(`Callback took longer than ${asyncMs / 1e3} s`)), asyncMs);
218
+ })
219
+ ]);
220
+ clearTimeout(timer);
221
+ if (out.error) {
222
+ const e = vm.dump(out.error);
223
+ out.error.dispose();
224
+ throw new ScriptError(
225
+ typeof e === "object" && e && "message" in e ? String(e.message) : String(e)
226
+ );
227
+ }
228
+ const v = vm.dump(out.value);
229
+ out.value.dispose();
230
+ return v;
231
+ } finally {
232
+ await Promise.allSettled([...pending]);
233
+ vm.dispose();
234
+ }
235
+ },
236
+ transform(code, rows) {
237
+ return runSync(`JSON.stringify((function(rows){ "use strict"; ${code} })(${toJson(rows)}) ?? null)`, syncMs);
238
+ },
239
+ fnProp(code, params) {
240
+ return (...args) => {
241
+ return runSync(
242
+ `JSON.stringify((function(${params.join(",")}){ "use strict"; ${code} })(...${toJson(args)}) ?? null)`,
243
+ fnMs
244
+ );
245
+ };
246
+ }
247
+ };
248
+ }
249
+
250
+ export {
251
+ loadQuickJS,
252
+ createSandboxRunner
253
+ };
254
+ //# sourceMappingURL=chunk-M4WXE3FW.js.map