@vvedantb/server 0.5.0 → 0.6.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 CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.1
4
+
5
+ Fix: the artifact guest bridge now connects in a browser iframe. No API change.
6
+
7
+ - The 0.6.0 guest sent `artifact:ready` only through a port it did not have yet, so the host never sent one. State requests went nowhere, and the built-in quiz and flashcards pages waited forever on `getAll()`. The guest now posts `artifact:ready` to `window.parent`, queues requests made before the port arrives, and sends them when it does. React Native WebViews are unchanged.
8
+ - Tests: the guest run in a VM realm with a parent window and no `ReactNativeWebView`: ready goes to the parent, a `getAll()` made before the port is sent once the port arrives, and its result resolves.
9
+
10
+ ## 0.6.0
11
+
12
+ Additive: a pure artifacts core joins the root. Nothing in 0.5.0 changes. See `docs/artifacts.md`.
13
+
14
+ ### Added
15
+
16
+ - `createArtifactSchemas(z)` (zod 3.25+ or 4, passed in): `artifactType`, `artifactFormat`, `stateSpec`, `quizBodyV1`, `flashcardsBodyV1`, `listRow`, `detailRow`, and `validateArtifactBody(type, format, body, schemaVersion?)`, which caps bodies at 400,000 characters and allows `json` only for quiz and flashcards v1. Constants `ARTIFACT_TYPES`, `ARTIFACT_FORMATS`, `ARTIFACT_JSON_TYPES`, `ARTIFACT_TITLE_MAX_CHARS`, `ARTIFACT_DESCRIPTION_MAX_CHARS`, `ARTIFACT_BODY_MAX_CHARS`. Types `ArtifactType`, `ArtifactFormat`, `ArtifactStateSpec`, `QuizBodyV1`, `FlashcardsBodyV1`, `ArtifactOrigin`, `ArtifactListRow`, `ArtifactDetailRow`, `ArtifactSchemas`, `ArtifactBodyValidation`.
17
+ - State: limits (32 keys, 64-character keys, 16 KiB per value, 64 KiB in total, 1 s between writes, 400/4,000 daily writes, 5 s/30 s save debounce, 10 versions kept), `applyArtifactStateOp`, `applyArtifactStatePatch`, `validateArtifactStateMap`, `parseArtifactStateOp`, `utcDayKey`, `utf8ByteLength`, `createTrailingMaxDebounce`, and the storage-shim prefixes and helpers (`ls:`, `ss:`).
18
+ - Rendering: `buildQuizHtml`, `buildFlashcardsHtml`, `htmlFromArtifactTemplate` with lenient `parseQuizTemplate` and `parseFlashcardsTemplate`, `wrapArtifactDocument(body, format, snapshot?, { title?, template?, stateGlobalAliases? })`, `wrapArtifactHtml`, `artifactGuestScript`, `GUEST_BOOTSTRAP_SCRIPT`, `ARTIFACT_CSP`, `formatFromLanguage`, `ARTIFACT_FORMAT_FILES` and `artifactFileName`.
19
+ - Bridge messages with neutral names: `artifact:ready`, `artifact:port`, `artifact:state`, `artifact:state-result`. The guest exposes `window.artifactState`, plus `window[alias].state` for each alias the host passes (`assertStateGlobalAliases` refuses non-identifiers and globals such as `document`). The built-in pages use `window.artifactState`.
20
+ - Tests: `tests/artifacts` (protocol and alias injection, the guest run in a VM realm, state limit edges, debounce, templates, document formats, schema v1 round trips under zod 4 and 3.25, and a check that no app name appears in the source or shipped docs). `tests-node` imports the new exports from the built package with no peer installed, type-checks them for zod 4 and 3.25 consumers, and bundles them for Convex V8.
21
+
22
+ ### Changed (from the app code this came from)
23
+
24
+ - The snapshot global is `__ARTIFACT_SNAPSHOT__`. The guest limit checks use the exported constants.
25
+ - `applyArtifactStatePatch` returns the current data unchanged when any set or remove fails. Before, a failing set returned the partly applied data.
26
+ - The quiz and flashcards builders are `buildQuizHtml` and `buildFlashcardsHtml`; their card and question types are `Flashcard` and `QuizQuestion`.
27
+
3
28
  ## 0.5.0
4
29
 
5
30
  Additive: a QuickJS code sandbox joins the root. Nothing in 0.4.1 changes.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @vvedantb/server
2
2
 
3
- Server-side helpers for Convex backends, Convex optimistic updates, Node-side MCP OAuth client helpers and a QuickJS code sandbox, from one root import.
3
+ Server-side helpers for Convex backends, Convex optimistic updates, Node-side MCP OAuth client helpers, a QuickJS code sandbox and an artifacts core, from one root import.
4
4
 
5
5
  ```sh
6
6
  npm install @vvedantb/server
@@ -19,6 +19,7 @@ There are no subpath exports (0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG
19
19
  | Crypto | WebCrypto-only base64/base64url/hex, SHA-256, random tokens, `timingSafeEqual`, AES-GCM. Convex default runtime and Node 20+. | [docs/crypto.md](docs/crypto.md) |
20
20
  | Optimistic updates | `mapLoadedQuery` (also `forEachLoadedQuery`, `updateAllCachedQueries`), `patchLoadedQuery`, `tempId`, `createMemoryOptimisticStore`. Client-side, no React. | [docs/convex.md](docs/convex.md#optimistic-updates-client-side) |
21
21
  | MCP OAuth client | Node only (Electron main): OAuth provider over injected storage, sign-in, refresh, revocation, loopback redirect server. Node built-ins and the MCP SDK load on first use, so Convex V8 bundles of the root stay clean. | [docs/mcp-oauth-client.md](docs/mcp-oauth-client.md) |
22
+ | Artifacts core | Pure, no DOM: Zod contract for artifact rows and typed bodies (`createArtifactSchemas`, `validateArtifactBody`), state limits and ops, the host's save debounce, built-in quiz and flashcards pages, and `wrapArtifactDocument` (CSP plus a guest state bridge with host-given global aliases). | [docs/artifacts.md](docs/artifacts.md) |
22
23
  | Code sandbox | Node only: `runSandboxedScript` runs untrusted JavaScript in QuickJS (WASM) with a `tools` proxy to host handlers, time, heap, stack, call and log limits, injected `globals`, and an `onCall` hook for allow-lists and dry runs. QuickJS loads on first call. | [docs/sandbox.md](docs/sandbox.md) |
23
24
 
24
25
  Migration steps per app: [docs/migration.md](docs/migration.md).
@@ -28,7 +29,7 @@ Migration steps per app: [docs/migration.md](docs/migration.md).
28
29
  All are optional. None is imported when the root loads.
29
30
 
30
31
  - `@clerk/backend` `>=1`: only for `getClerkClient` and `verifyClerkAccessToken`, which take its client or factory as an argument.
31
- - `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`, or your `z` to `createMcpOAuthStateSchema`.
32
+ - `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`, or your `z` to `createMcpOAuthStateSchema` or `createArtifactSchemas`.
32
33
  - `convex` `^1.24.0`: types only, for the optimistic-update helpers. The package never imports `convex` at runtime: `registerMcpRoutes` and `createClerkUserAuth` type the router and ctx structurally, and `createMemoryOptimisticStore` carries its own copy of `getFunctionName` (`convex` is a dev dependency, used to check that real Convex types fit).
33
34
  - `@modelcontextprotocol/sdk` `^1.29.0`: only for the MCP client OAuth calls, which import it on first use.
34
35
  - `quickjs-emscripten-core` and `@jitl/quickjs-singlefile-cjs-release-sync` `^0.32.0`: only for `runSandboxedScript`, which imports them on first call. The `browser` field maps both to empty modules, so browser-platform bundles (Convex V8) of the root never include them.
@@ -38,20 +39,22 @@ No React, no web dependencies. `"sideEffects": false`. Compiled ESM with types i
38
39
  ## Layout
39
40
 
40
41
  ```
41
- src/index.ts the only export: re-exports the five folders
42
+ src/index.ts the only export: re-exports the six folders
42
43
  src/convex/ Convex helpers and optimistic updates
43
44
  src/mcp/ MCP scaffolding (imports ../convex by relative path)
44
45
  src/mcp-oauth-client/ MCP OAuth client helpers (Node only; lazy node:http and SDK imports)
45
46
  src/crypto/ WebCrypto primitives
46
47
  src/sandbox/ QuickJS code sandbox (Node only; lazy QuickJS import)
48
+ src/artifacts/ artifacts core (pure strings and data; runs anywhere)
47
49
  tests/convex/ vitest
48
50
  tests/mcp/ vitest, with fixtures/ (SDK captures, app references)
49
51
  tests/mcp-oauth-client/ vitest, against fake MCP and authorization servers
50
52
  tests/crypto/ vitest, with published vectors and app format parity
51
53
  tests/sandbox/ vitest, against real QuickJS
54
+ tests/artifacts/ vitest, including the guest bootstrap in a VM realm and a no-app-name check
52
55
  tests-node/ plain Node checks of the built package: exports map and peers (esm-exports.mjs),
53
56
  Convex V8 and Node/Electron bundles with esbuild (bundle.mjs)
54
- docs/ convex.md, mcp.md, mcp-oauth-client.md, crypto.md, sandbox.md, migration.md, migrated/<app>/
57
+ docs/ convex.md, mcp.md, mcp-oauth-client.md, crypto.md, sandbox.md, artifacts.md, migration.md, migrated/<app>/
55
58
  scripts/ capture-sdk-fixtures.mjs
56
59
  ```
57
60
 
@@ -0,0 +1,16 @@
1
+ export type DebounceTimers = {
2
+ setTimeout: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;
3
+ clearTimeout: (id: ReturnType<typeof setTimeout>) => void;
4
+ };
5
+ export type TrailingMaxDebounce = {
6
+ schedule(): void;
7
+ flushNow(): void;
8
+ cancel(): void;
9
+ readonly isPending: boolean;
10
+ };
11
+ /**
12
+ * Calls `flush` `trailingMs` after the last `schedule()`, and at the latest
13
+ * `maxMs` after the first one, so steady changes still save. `flushNow()`
14
+ * runs a pending flush at once (for `pagehide`); `cancel()` drops it.
15
+ */
16
+ export declare function createTrailingMaxDebounce(flush: () => void, trailingMs?: number, maxMs?: number, timers?: DebounceTimers): TrailingMaxDebounce;
@@ -0,0 +1,49 @@
1
+ import { ARTIFACT_STATE_DEBOUNCE_MS, ARTIFACT_STATE_MAX_WAIT_MS } from "./limits.js";
2
+ /**
3
+ * Calls `flush` `trailingMs` after the last `schedule()`, and at the latest
4
+ * `maxMs` after the first one, so steady changes still save. `flushNow()`
5
+ * runs a pending flush at once (for `pagehide`); `cancel()` drops it.
6
+ */
7
+ export function createTrailingMaxDebounce(flush, trailingMs = ARTIFACT_STATE_DEBOUNCE_MS, maxMs = ARTIFACT_STATE_MAX_WAIT_MS, timers = {
8
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
9
+ clearTimeout: (id) => globalThis.clearTimeout(id),
10
+ }) {
11
+ let trailingId;
12
+ let maxId;
13
+ let pending = false;
14
+ function clearTimers() {
15
+ if (trailingId !== undefined)
16
+ timers.clearTimeout(trailingId);
17
+ if (maxId !== undefined)
18
+ timers.clearTimeout(maxId);
19
+ trailingId = undefined;
20
+ maxId = undefined;
21
+ }
22
+ function run() {
23
+ clearTimers();
24
+ if (!pending)
25
+ return;
26
+ pending = false;
27
+ flush();
28
+ }
29
+ return {
30
+ schedule() {
31
+ pending = true;
32
+ if (trailingId !== undefined)
33
+ timers.clearTimeout(trailingId);
34
+ trailingId = timers.setTimeout(run, trailingMs);
35
+ if (maxId === undefined)
36
+ maxId = timers.setTimeout(run, maxMs);
37
+ },
38
+ flushNow() {
39
+ run();
40
+ },
41
+ cancel() {
42
+ pending = false;
43
+ clearTimers();
44
+ },
45
+ get isPending() {
46
+ return pending;
47
+ },
48
+ };
49
+ }
@@ -0,0 +1,26 @@
1
+ import { type ArtifactGuestOptions } from "./protocol.js";
2
+ import type { ArtifactFormat } from "./schemas.js";
3
+ import type { ArtifactStateMap } from "./stateOps.js";
4
+ import { type ArtifactTemplateName } from "./templates.js";
5
+ export type WrapArtifactDocumentOptions = ArtifactGuestOptions & {
6
+ /** Heading for a built-in template when the body has no title. Default "Artifact". */
7
+ title?: string;
8
+ /** From `stateSpec.template`. Tried first for any format; `json` bodies without one try both templates. */
9
+ template?: ArtifactTemplateName;
10
+ };
11
+ /** The body format for a fenced code block's language: html, svg and markdown render; anything else is code. */
12
+ export declare function formatFromLanguage(language: string | undefined): "html" | "markdown" | "svg" | "code";
13
+ /**
14
+ * The `srcdoc` for an artifact: the body as a document (a built-in template
15
+ * for quiz and flashcards JSON), with the CSP and the guest state bootstrap
16
+ * (snapshot plus `stateGlobalAliases`) at the start of <head>. Render it in an
17
+ * iframe with `sandbox="allow-scripts"` and no `allow-same-origin`.
18
+ */
19
+ export declare function wrapArtifactDocument(body: string, format: ArtifactFormat, snapshot?: ArtifactStateMap, options?: WrapArtifactDocumentOptions): string;
20
+ /** File extension and MIME type for downloading a body of each format. */
21
+ export declare const ARTIFACT_FORMAT_FILES: Record<ArtifactFormat, {
22
+ extension: string;
23
+ mime: string;
24
+ }>;
25
+ /** A download file name: the title with characters that file systems refuse replaced by "-", plus the format's extension. */
26
+ export declare function artifactFileName(title: string, format: ArtifactFormat): string;
@@ -0,0 +1,61 @@
1
+ import { wrapArtifactHtml } from "./protocol.js";
2
+ import { htmlFromArtifactTemplate } from "./templates.js";
3
+ /** The body format for a fenced code block's language: html, svg and markdown render; anything else is code. */
4
+ export function formatFromLanguage(language) {
5
+ const normalized = (language ?? "html").toLowerCase();
6
+ if (normalized === "html" || normalized === "htm")
7
+ return "html";
8
+ if (normalized === "svg")
9
+ return "svg";
10
+ if (normalized === "md" || normalized === "markdown")
11
+ return "markdown";
12
+ return "code";
13
+ }
14
+ function escapeText(value) {
15
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
16
+ }
17
+ function plainTextDocument(body) {
18
+ return `<!doctype html><html><head><meta charset="utf-8"/><style>body{font-family:system-ui,sans-serif;margin:16px;white-space:pre-wrap}</style></head><body><pre>${escapeText(body)}</pre></body></html>`;
19
+ }
20
+ /** A full HTML document for `body` before the guest is injected. Markdown and code show as escaped text. */
21
+ function previewDocument(body, format, options) {
22
+ if (options.template !== undefined || format === "json") {
23
+ const templated = htmlFromArtifactTemplate({
24
+ title: options.title ?? "Artifact",
25
+ content: body,
26
+ template: options.template,
27
+ });
28
+ if (templated)
29
+ return templated;
30
+ }
31
+ if (format === "svg") {
32
+ return `<!doctype html><html><body style="margin:0;display:grid;place-items:center;min-height:100vh;background:#fff">${body}</body></html>`;
33
+ }
34
+ if (format === "html") {
35
+ return body.includes("<html")
36
+ ? body
37
+ : `<!doctype html><html><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><style>body{font-family:system-ui,sans-serif;margin:16px}</style></head><body>${body}</body></html>`;
38
+ }
39
+ return plainTextDocument(body);
40
+ }
41
+ /**
42
+ * The `srcdoc` for an artifact: the body as a document (a built-in template
43
+ * for quiz and flashcards JSON), with the CSP and the guest state bootstrap
44
+ * (snapshot plus `stateGlobalAliases`) at the start of <head>. Render it in an
45
+ * iframe with `sandbox="allow-scripts"` and no `allow-same-origin`.
46
+ */
47
+ export function wrapArtifactDocument(body, format, snapshot, options = {}) {
48
+ return wrapArtifactHtml(previewDocument(body, format, options), snapshot, options);
49
+ }
50
+ /** File extension and MIME type for downloading a body of each format. */
51
+ export const ARTIFACT_FORMAT_FILES = {
52
+ html: { extension: "html", mime: "text/html" },
53
+ markdown: { extension: "md", mime: "text/markdown" },
54
+ svg: { extension: "svg", mime: "image/svg+xml" },
55
+ code: { extension: "txt", mime: "text/plain" },
56
+ json: { extension: "json", mime: "application/json" },
57
+ };
58
+ /** A download file name: the title with characters that file systems refuse replaced by "-", plus the format's extension. */
59
+ export function artifactFileName(title, format) {
60
+ return `${title.replace(/[/\\?%*:|"<>]/g, "-")}.${ARTIFACT_FORMAT_FILES[format].extension}`;
61
+ }
@@ -0,0 +1,8 @@
1
+ export { createTrailingMaxDebounce, type DebounceTimers, type TrailingMaxDebounce } from "./debounce.js";
2
+ export { ARTIFACT_FORMAT_FILES, artifactFileName, formatFromLanguage, wrapArtifactDocument, type WrapArtifactDocumentOptions, } from "./document.js";
3
+ export { ARTIFACT_BODY_MAX_CHARS, ARTIFACT_STATE_DAILY_WRITES, ARTIFACT_STATE_DEBOUNCE_MS, ARTIFACT_STATE_MAX_KEY_LENGTH, ARTIFACT_STATE_MAX_KEYS, ARTIFACT_STATE_MAX_TOTAL_BYTES, ARTIFACT_STATE_MAX_VALUE_BYTES, ARTIFACT_STATE_MAX_WAIT_MS, ARTIFACT_STATE_MIN_WRITE_INTERVAL_MS, ARTIFACT_VERSION_KEEP, utcDayKey, utf8ByteLength, } from "./limits.js";
4
+ export { ARTIFACT_ALIASES_GLOBAL, ARTIFACT_CSP, ARTIFACT_PORT_TYPE, ARTIFACT_READY_TYPE, ARTIFACT_SNAPSHOT_GLOBAL, ARTIFACT_STATE_RESULT_TYPE, ARTIFACT_STATE_TYPE, GUEST_BOOTSTRAP_SCRIPT, artifactGuestScript, assertStateGlobalAliases, wrapArtifactHtml, type ArtifactGuestOptions, } from "./protocol.js";
5
+ export { ARTIFACT_DESCRIPTION_MAX_CHARS, ARTIFACT_FORMATS, ARTIFACT_JSON_TYPES, ARTIFACT_TITLE_MAX_CHARS, ARTIFACT_TYPES, createArtifactSchemas, type ArtifactBodyValidation, type ArtifactDetailRow, type ArtifactFormat, type ArtifactListRow, type ArtifactOrigin, type ArtifactSchemas, type ArtifactStateSpec, type ArtifactType, type FlashcardsBodyV1, type QuizBodyV1, } from "./schemas.js";
6
+ export { applyArtifactStateOp, applyArtifactStatePatch, parseArtifactStateOp, validateArtifactStateMap, type ArtifactStateMap, type ArtifactStateOp, type ArtifactStateOpResult, type ArtifactStatePatch, } from "./stateOps.js";
7
+ export { ARTIFACT_LOCAL_STORAGE_PREFIX, ARTIFACT_SESSION_STORAGE_PREFIX, clearPrefixedKeys, prefixedStorageKey, storageView, unprefixStorageKey, } from "./storageShim.js";
8
+ export { buildFlashcardsHtml, buildQuizHtml, htmlFromArtifactTemplate, parseFlashcardsTemplate, parseQuizTemplate, type ArtifactTemplateName, type Flashcard, type QuizQuestion, } from "./templates.js";
@@ -0,0 +1,8 @@
1
+ export { createTrailingMaxDebounce } from "./debounce.js";
2
+ export { ARTIFACT_FORMAT_FILES, artifactFileName, formatFromLanguage, wrapArtifactDocument, } from "./document.js";
3
+ export { ARTIFACT_BODY_MAX_CHARS, ARTIFACT_STATE_DAILY_WRITES, ARTIFACT_STATE_DEBOUNCE_MS, ARTIFACT_STATE_MAX_KEY_LENGTH, ARTIFACT_STATE_MAX_KEYS, ARTIFACT_STATE_MAX_TOTAL_BYTES, ARTIFACT_STATE_MAX_VALUE_BYTES, ARTIFACT_STATE_MAX_WAIT_MS, ARTIFACT_STATE_MIN_WRITE_INTERVAL_MS, ARTIFACT_VERSION_KEEP, utcDayKey, utf8ByteLength, } from "./limits.js";
4
+ export { ARTIFACT_ALIASES_GLOBAL, ARTIFACT_CSP, ARTIFACT_PORT_TYPE, ARTIFACT_READY_TYPE, ARTIFACT_SNAPSHOT_GLOBAL, ARTIFACT_STATE_RESULT_TYPE, ARTIFACT_STATE_TYPE, GUEST_BOOTSTRAP_SCRIPT, artifactGuestScript, assertStateGlobalAliases, wrapArtifactHtml, } from "./protocol.js";
5
+ export { ARTIFACT_DESCRIPTION_MAX_CHARS, ARTIFACT_FORMATS, ARTIFACT_JSON_TYPES, ARTIFACT_TITLE_MAX_CHARS, ARTIFACT_TYPES, createArtifactSchemas, } from "./schemas.js";
6
+ export { applyArtifactStateOp, applyArtifactStatePatch, parseArtifactStateOp, validateArtifactStateMap, } from "./stateOps.js";
7
+ export { ARTIFACT_LOCAL_STORAGE_PREFIX, ARTIFACT_SESSION_STORAGE_PREFIX, clearPrefixedKeys, prefixedStorageKey, storageView, unprefixStorageKey, } from "./storageShim.js";
8
+ export { buildFlashcardsHtml, buildQuizHtml, htmlFromArtifactTemplate, parseFlashcardsTemplate, parseQuizTemplate, } from "./templates.js";
@@ -0,0 +1,21 @@
1
+ /** Largest artifact body, in characters. Convex documents stop at 1 MiB. */
2
+ export declare const ARTIFACT_BODY_MAX_CHARS = 400000;
3
+ /** Versions kept per artifact; older ones are pruned. */
4
+ export declare const ARTIFACT_VERSION_KEEP = 10;
5
+ export declare const ARTIFACT_STATE_MAX_KEYS = 32;
6
+ export declare const ARTIFACT_STATE_MAX_VALUE_BYTES: number;
7
+ export declare const ARTIFACT_STATE_MAX_TOTAL_BYTES: number;
8
+ export declare const ARTIFACT_STATE_MAX_KEY_LENGTH = 64;
9
+ /** Server side: a second state write for the same artifact and user within this window is refused. */
10
+ export declare const ARTIFACT_STATE_MIN_WRITE_INTERVAL_MS = 1000;
11
+ /** Host side: state is saved this long after the last change, and at least this often while changes keep coming. */
12
+ export declare const ARTIFACT_STATE_DEBOUNCE_MS = 5000;
13
+ export declare const ARTIFACT_STATE_MAX_WAIT_MS = 30000;
14
+ /** State writes per user per UTC day (see `utcDayKey`). */
15
+ export declare const ARTIFACT_STATE_DAILY_WRITES: {
16
+ readonly free: 400;
17
+ readonly pro: 4000;
18
+ };
19
+ export declare function utf8ByteLength(value: string): number;
20
+ /** The UTC day of `now` as a number, for example 20261022. */
21
+ export declare function utcDayKey(now: number): number;
@@ -0,0 +1,23 @@
1
+ /** Largest artifact body, in characters. Convex documents stop at 1 MiB. */
2
+ export const ARTIFACT_BODY_MAX_CHARS = 400_000;
3
+ /** Versions kept per artifact; older ones are pruned. */
4
+ export const ARTIFACT_VERSION_KEEP = 10;
5
+ export const ARTIFACT_STATE_MAX_KEYS = 32;
6
+ export const ARTIFACT_STATE_MAX_VALUE_BYTES = 16 * 1024;
7
+ export const ARTIFACT_STATE_MAX_TOTAL_BYTES = 64 * 1024;
8
+ export const ARTIFACT_STATE_MAX_KEY_LENGTH = 64;
9
+ /** Server side: a second state write for the same artifact and user within this window is refused. */
10
+ export const ARTIFACT_STATE_MIN_WRITE_INTERVAL_MS = 1000;
11
+ /** Host side: state is saved this long after the last change, and at least this often while changes keep coming. */
12
+ export const ARTIFACT_STATE_DEBOUNCE_MS = 5000;
13
+ export const ARTIFACT_STATE_MAX_WAIT_MS = 30_000;
14
+ /** State writes per user per UTC day (see `utcDayKey`). */
15
+ export const ARTIFACT_STATE_DAILY_WRITES = { free: 400, pro: 4000 };
16
+ export function utf8ByteLength(value) {
17
+ return new TextEncoder().encode(value).byteLength;
18
+ }
19
+ /** The UTC day of `now` as a number, for example 20261022. */
20
+ export function utcDayKey(now) {
21
+ const date = new Date(now);
22
+ return date.getUTCFullYear() * 10000 + (date.getUTCMonth() + 1) * 100 + date.getUTCDate();
23
+ }
@@ -0,0 +1,47 @@
1
+ import type { ArtifactStateMap } from "./stateOps.js";
2
+ /** No network, no frames, no forms: the artifact runs offline in a sandboxed iframe or WebView. */
3
+ export declare const ARTIFACT_CSP = "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
4
+ /** Guest → host (window message): the bootstrap ran; send the port. */
5
+ export declare const ARTIFACT_READY_TYPE = "artifact:ready";
6
+ /** Host → guest (window message, with a MessagePort): state requests go over this port from now on. */
7
+ export declare const ARTIFACT_PORT_TYPE = "artifact:port";
8
+ /** Guest → host: `{ type, requestId, op, key?, value? }`. Parse with `parseArtifactStateOp`. */
9
+ export declare const ARTIFACT_STATE_TYPE = "artifact:state";
10
+ /** Host → guest: `{ type, requestId, ok, value?, error? }`. */
11
+ export declare const ARTIFACT_STATE_RESULT_TYPE = "artifact:state-result";
12
+ /** The global the host sets before the bootstrap runs: the state snapshot. The bootstrap deletes it. */
13
+ export declare const ARTIFACT_SNAPSHOT_GLOBAL = "__ARTIFACT_SNAPSHOT__";
14
+ /** The global the host sets before the bootstrap runs: extra names for the state API. The bootstrap deletes it. */
15
+ export declare const ARTIFACT_ALIASES_GLOBAL = "__ARTIFACT_ALIASES__";
16
+ /**
17
+ * Runs first in the guest document. Exposes `window.artifactState`
18
+ * (`get`, `set`, `getAll`, `remove`, `reset`; promises; values are JSON), and
19
+ * `window[alias].state` for each alias in `window.__ARTIFACT_ALIASES__`.
20
+ * Replaces `localStorage` and `sessionStorage` with shims over the same state
21
+ * (keys prefixed `ls:` and `ss:`). Writes over the state limits fail in the
22
+ * guest before they reach the host. In an iframe it posts `artifact:ready` to
23
+ * the parent window, then talks over the MessagePort the host sends back and
24
+ * queues requests made before the port arrives. In a React Native WebView it
25
+ * uses `window.ReactNativeWebView.postMessage`.
26
+ */
27
+ export declare const GUEST_BOOTSTRAP_SCRIPT: string;
28
+ export type ArtifactGuestOptions = {
29
+ /**
30
+ * Extra globals for the state API: `["app"]` makes `window.app.state` the
31
+ * same object as `window.artifactState`. Each must be a JavaScript
32
+ * identifier and must not name a built-in global (`window`, `document`, …).
33
+ */
34
+ stateGlobalAliases?: readonly string[];
35
+ };
36
+ /** Throws on an alias that is not an identifier or would replace a global the page or the bootstrap needs. */
37
+ export declare function assertStateGlobalAliases(aliases: readonly string[]): void;
38
+ /** JSON for an inline <script>: `<` is escaped so the data cannot close the script element. */
39
+ export declare function embedJsonInScript(value: object): string;
40
+ /**
41
+ * The inline script for the guest: the snapshot and aliases, then
42
+ * `GUEST_BOOTSTRAP_SCRIPT`. A React Native WebView can pass it as
43
+ * `injectedJavaScriptBeforeContentLoaded`.
44
+ */
45
+ export declare function artifactGuestScript(snapshot?: ArtifactStateMap, options?: ArtifactGuestOptions): string;
46
+ /** Put the CSP meta tag and the guest script at the start of the document's <head>, adding a <head> or a whole document when missing. */
47
+ export declare function wrapArtifactHtml(html: string, snapshot?: ArtifactStateMap, options?: ArtifactGuestOptions): string;
@@ -0,0 +1,256 @@
1
+ import { ARTIFACT_STATE_MAX_KEY_LENGTH, ARTIFACT_STATE_MAX_KEYS, ARTIFACT_STATE_MAX_TOTAL_BYTES, ARTIFACT_STATE_MAX_VALUE_BYTES, } from "./limits.js";
2
+ import { ARTIFACT_LOCAL_STORAGE_PREFIX, ARTIFACT_SESSION_STORAGE_PREFIX } from "./storageShim.js";
3
+ /** No network, no frames, no forms: the artifact runs offline in a sandboxed iframe or WebView. */
4
+ export const ARTIFACT_CSP = "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
5
+ /** Guest → host (window message): the bootstrap ran; send the port. */
6
+ export const ARTIFACT_READY_TYPE = "artifact:ready";
7
+ /** Host → guest (window message, with a MessagePort): state requests go over this port from now on. */
8
+ export const ARTIFACT_PORT_TYPE = "artifact:port";
9
+ /** Guest → host: `{ type, requestId, op, key?, value? }`. Parse with `parseArtifactStateOp`. */
10
+ export const ARTIFACT_STATE_TYPE = "artifact:state";
11
+ /** Host → guest: `{ type, requestId, ok, value?, error? }`. */
12
+ export const ARTIFACT_STATE_RESULT_TYPE = "artifact:state-result";
13
+ /** The global the host sets before the bootstrap runs: the state snapshot. The bootstrap deletes it. */
14
+ export const ARTIFACT_SNAPSHOT_GLOBAL = "__ARTIFACT_SNAPSHOT__";
15
+ /** The global the host sets before the bootstrap runs: extra names for the state API. The bootstrap deletes it. */
16
+ export const ARTIFACT_ALIASES_GLOBAL = "__ARTIFACT_ALIASES__";
17
+ /**
18
+ * Runs first in the guest document. Exposes `window.artifactState`
19
+ * (`get`, `set`, `getAll`, `remove`, `reset`; promises; values are JSON), and
20
+ * `window[alias].state` for each alias in `window.__ARTIFACT_ALIASES__`.
21
+ * Replaces `localStorage` and `sessionStorage` with shims over the same state
22
+ * (keys prefixed `ls:` and `ss:`). Writes over the state limits fail in the
23
+ * guest before they reach the host. In an iframe it posts `artifact:ready` to
24
+ * the parent window, then talks over the MessagePort the host sends back and
25
+ * queues requests made before the port arrives. In a React Native WebView it
26
+ * uses `window.ReactNativeWebView.postMessage`.
27
+ */
28
+ export const GUEST_BOOTSTRAP_SCRIPT = `(function(){
29
+ var port=null;
30
+ var seq=0;
31
+ var pending={};
32
+ var store=window.${ARTIFACT_SNAPSHOT_GLOBAL}&&typeof window.${ARTIFACT_SNAPSHOT_GLOBAL}==="object"?window.${ARTIFACT_SNAPSHOT_GLOBAL}:{};
33
+ var aliases=Array.isArray(window.${ARTIFACT_ALIASES_GLOBAL})?window.${ARTIFACT_ALIASES_GLOBAL}:[];
34
+ try{delete window.${ARTIFACT_SNAPSHOT_GLOBAL};delete window.${ARTIFACT_ALIASES_GLOBAL};}catch(e){}
35
+ function copyStore(){
36
+ var next={};
37
+ for(var k in store){if(Object.prototype.hasOwnProperty.call(store,k))next[k]=store[k];}
38
+ return next;
39
+ }
40
+ function utf8len(s){
41
+ return new TextEncoder().encode(String(s)).length;
42
+ }
43
+ function fits(data){
44
+ var keys=Object.keys(data);
45
+ if(keys.length>${String(ARTIFACT_STATE_MAX_KEYS)})return false;
46
+ var total=0;
47
+ for(var i=0;i<keys.length;i++){
48
+ var k=keys[i];
49
+ if(!k||k.length>${String(ARTIFACT_STATE_MAX_KEY_LENGTH)})return false;
50
+ var v=data[k];
51
+ if(typeof v!=="string")return false;
52
+ var sz=utf8len(v);
53
+ if(sz>${String(ARTIFACT_STATE_MAX_VALUE_BYTES)})return false;
54
+ total+=utf8len(k)+sz;
55
+ }
56
+ return total<=${String(ARTIFACT_STATE_MAX_TOTAL_BYTES)};
57
+ }
58
+ var queued=[];
59
+ function nativeView(){
60
+ return window.ReactNativeWebView&&typeof window.ReactNativeWebView.postMessage==="function"?window.ReactNativeWebView:null;
61
+ }
62
+ function send(msg){
63
+ var native=nativeView();
64
+ if(native){
65
+ native.postMessage(JSON.stringify(msg));
66
+ return;
67
+ }
68
+ if(port){port.postMessage(msg);return;}
69
+ queued.push(msg);
70
+ }
71
+ function call(op,extra){
72
+ return new Promise(function(resolve,reject){
73
+ var requestId=++seq;
74
+ pending[requestId]={resolve:resolve,reject:reject};
75
+ var msg={type:"${ARTIFACT_STATE_TYPE}",requestId:requestId,op:op};
76
+ if(extra){for(var k in extra){if(Object.prototype.hasOwnProperty.call(extra,k))msg[k]=extra[k];}}
77
+ send(msg);
78
+ });
79
+ }
80
+ function handleResult(msg){
81
+ var waiter=pending[msg.requestId];
82
+ if(!waiter)return;
83
+ delete pending[msg.requestId];
84
+ if(msg.ok)waiter.resolve(msg.value);
85
+ else waiter.reject(new Error(msg.error||"State error"));
86
+ }
87
+ function createStorage(prefix){
88
+ function names(){
89
+ var out=[];
90
+ for(var k in store){
91
+ if(Object.prototype.hasOwnProperty.call(store,k)&&k.indexOf(prefix)===0){
92
+ out.push(k.slice(prefix.length));
93
+ }
94
+ }
95
+ return out;
96
+ }
97
+ var api={
98
+ get length(){return names().length;},
99
+ key:function(i){
100
+ var n=names();
101
+ return i>=0&&i<n.length?n[i]:null;
102
+ },
103
+ getItem:function(key){
104
+ var k=prefix+String(key);
105
+ return Object.prototype.hasOwnProperty.call(store,k)?store[k]:null;
106
+ },
107
+ setItem:function(key,value){
108
+ var k=prefix+String(key);
109
+ var v=String(value);
110
+ var next=copyStore();
111
+ next[k]=v;
112
+ if(!fits(next)){
113
+ throw new DOMException("The quota has been exceeded.","QuotaExceededError");
114
+ }
115
+ store=next;
116
+ call("set",{key:k,value:v});
117
+ },
118
+ removeItem:function(key){
119
+ var k=prefix+String(key);
120
+ if(!Object.prototype.hasOwnProperty.call(store,k))return;
121
+ var next=copyStore();
122
+ delete next[k];
123
+ store=next;
124
+ call("remove",{key:k});
125
+ },
126
+ clear:function(){
127
+ var n=names();
128
+ var next=copyStore();
129
+ for(var i=0;i<n.length;i++) delete next[prefix+n[i]];
130
+ store=next;
131
+ for(var j=0;j<n.length;j++) call("remove",{key:prefix+n[j]});
132
+ }
133
+ };
134
+ return new Proxy(api,{
135
+ get:function(t,p){
136
+ if(p in t)return t[p];
137
+ if(typeof p==="string")return t.getItem(p);
138
+ return undefined;
139
+ },
140
+ set:function(t,p,v){
141
+ t.setItem(String(p),String(v));
142
+ return true;
143
+ },
144
+ deleteProperty:function(t,p){
145
+ t.removeItem(String(p));
146
+ return true;
147
+ }
148
+ });
149
+ }
150
+ try{
151
+ Object.defineProperty(window,"localStorage",{configurable:true,enumerable:true,value:createStorage("${ARTIFACT_LOCAL_STORAGE_PREFIX}")});
152
+ Object.defineProperty(window,"sessionStorage",{configurable:true,enumerable:true,value:createStorage("${ARTIFACT_SESSION_STORAGE_PREFIX}")});
153
+ }catch(err){}
154
+ var state={
155
+ get:function(key){return call("get",{key:String(key)});},
156
+ set:function(key,value){
157
+ var encoded;
158
+ try{encoded=JSON.stringify(value);}
159
+ catch(e){return Promise.reject(e);}
160
+ var next=copyStore();
161
+ next[String(key)]=encoded;
162
+ if(!fits(next))return Promise.reject(new Error("State exceeds quota."));
163
+ store=next;
164
+ return call("set",{key:String(key),value:encoded});
165
+ },
166
+ getAll:function(){return call("getAll");},
167
+ remove:function(key){
168
+ var next=copyStore();
169
+ delete next[String(key)];
170
+ store=next;
171
+ return call("remove",{key:String(key)});
172
+ },
173
+ reset:function(){
174
+ store={};
175
+ return call("reset");
176
+ }
177
+ };
178
+ window.artifactState=state;
179
+ for(var a=0;a<aliases.length;a++){
180
+ if(typeof aliases[a]==="string")window[aliases[a]]={state:state};
181
+ }
182
+ window.addEventListener("message",function(event){
183
+ var data=event.data;
184
+ if(!data||typeof data!=="object")return;
185
+ if(data.type==="${ARTIFACT_PORT_TYPE}"&&event.ports&&event.ports[0]){
186
+ port=event.ports[0];
187
+ port.onmessage=function(e){
188
+ var msg=e.data;
189
+ if(msg&&msg.type==="${ARTIFACT_STATE_RESULT_TYPE}")handleResult(msg);
190
+ };
191
+ for(var q=0;q<queued.length;q++)port.postMessage(queued[q]);
192
+ queued=[];
193
+ return;
194
+ }
195
+ if(data.type==="${ARTIFACT_STATE_RESULT_TYPE}")handleResult(data);
196
+ });
197
+ var ready={type:"${ARTIFACT_READY_TYPE}"};
198
+ var native=nativeView();
199
+ if(native)native.postMessage(JSON.stringify(ready));
200
+ else if(window.parent&&window.parent!==window)window.parent.postMessage(ready,"*");
201
+ })();`;
202
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
203
+ const RESERVED_ALIASES = new Set([
204
+ "artifactState",
205
+ "window",
206
+ "self",
207
+ "globalThis",
208
+ "document",
209
+ "location",
210
+ "top",
211
+ "parent",
212
+ "frames",
213
+ "localStorage",
214
+ "sessionStorage",
215
+ "ReactNativeWebView",
216
+ ARTIFACT_SNAPSHOT_GLOBAL,
217
+ ARTIFACT_ALIASES_GLOBAL,
218
+ ]);
219
+ /** Throws on an alias that is not an identifier or would replace a global the page or the bootstrap needs. */
220
+ export function assertStateGlobalAliases(aliases) {
221
+ for (const alias of aliases) {
222
+ if (!IDENTIFIER.test(alias) || RESERVED_ALIASES.has(alias)) {
223
+ throw new Error(`Invalid artifact state alias: ${JSON.stringify(alias)}`);
224
+ }
225
+ }
226
+ }
227
+ /** JSON for an inline <script>: `<` is escaped so the data cannot close the script element. */
228
+ export function embedJsonInScript(value) {
229
+ return JSON.stringify(value).replace(/</g, "\\u003c");
230
+ }
231
+ /**
232
+ * The inline script for the guest: the snapshot and aliases, then
233
+ * `GUEST_BOOTSTRAP_SCRIPT`. A React Native WebView can pass it as
234
+ * `injectedJavaScriptBeforeContentLoaded`.
235
+ */
236
+ export function artifactGuestScript(snapshot, options = {}) {
237
+ const aliases = options.stateGlobalAliases ?? [];
238
+ assertStateGlobalAliases(aliases);
239
+ return (`window.${ARTIFACT_SNAPSHOT_GLOBAL}=${embedJsonInScript(snapshot ?? {})};` +
240
+ `window.${ARTIFACT_ALIASES_GLOBAL}=${embedJsonInScript(aliases)};` +
241
+ GUEST_BOOTSTRAP_SCRIPT);
242
+ }
243
+ /** Put the CSP meta tag and the guest script at the start of the document's <head>, adding a <head> or a whole document when missing. */
244
+ export function wrapArtifactHtml(html, snapshot, options = {}) {
245
+ const headInject = `<meta http-equiv="Content-Security-Policy" content="${ARTIFACT_CSP}">` +
246
+ `<script>${artifactGuestScript(snapshot, options)}</script>`;
247
+ const headMatch = html.match(/<head[^>]*>/i);
248
+ if (headMatch && headMatch.index !== undefined) {
249
+ const insertAt = headMatch.index + headMatch[0].length;
250
+ return html.slice(0, insertAt) + headInject + html.slice(insertAt);
251
+ }
252
+ if (/<html/i.test(html)) {
253
+ return html.replace(/<html[^>]*>/i, (open) => `${open}<head>${headInject}</head>`);
254
+ }
255
+ return `<!doctype html><html><head>${headInject}<meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/></head><body>${html}</body></html>`;
256
+ }