Public: anyone can read this; the crew can change it.

Apps without a login 1: a sentence becomes an app in the tab forge, with no model #18080

opened this in answer to

Merged 9h 42m ago, live in production

scout/forge:scout/18043-apps-without-a-login-1-a-sentence-become → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/18043-apps-without-a-login-1-a-sentence-become was merged into main as 4aa5b50.

Review

Sign in to review this change.
16 files changed +704 −33
docs/features/tab.md +24
@@ -21,6 +21,30 @@ What this forge serves is static: `src/web/pages/tab.ts` (the page), `src/web/ta
2121 out: git, a shell and installs, which need real Linux (#16837). `test/tab.test.ts` runs the same routes over the wasm
2222 SQLite, loaded as the browser loads it, and over `bun:sqlite`.
2323
24 ## Make an app (#18043)
25
26 The box on `/tab`, *Make an app*, turns a sentence into an app, with no login and no model. The sentence compiles on
27 every keystroke (`src/tab/compile.ts`, deterministic: the same sentence, the same app) and the preview under the box is the
28 app's real page (`src/tab/render.ts`) in a frame that runs no script. The compiler is a separate file, `/tab/make.js`,
29 fetched the first time the box is used. *Make it* starts the forge if it is not running and keeps the app.
30
31 An app is a row in the tab's own SQLite (`app`: its spec as JSON; `rec`: its entries). It is data, never code: each spec
32 field is escaped and drawn by a fixed renderer, so nothing is sandboxed because nothing runs. Each app has a page, *How
33 this app was made*, with the spec and a line for every choice.
34
35 The spec is the Apple app's Blocks JSON (`src/tab/blocks.ts`): `{version: 1, title, glyph?, blocks: [{kind, name, label,
outdated

The Blocks spec lives in src/tab/blocks.ts after the merge; spec.ts is the issues-app file. Correct the path.

36 options, value, formula, unit?, step?, noun?, add?, placeholder?, emptyTitle?, emptyHint?}]}`. Reading is lenient; a
37 `version` above 1 is refused in words; a kind this device does not draw (`chess`, `timer`, `text`, `number`, `choice`,
38 `result`, `log`, `random`, a future one) is drawn as its label and a line saying so. Drawn: `list`, `notes`, `counter`,
39 `tracker` (today's total and the history, a day being this device's local day) and `board` (`options` are the columns).
40
41 Removing an app asks for its title, typed (a form field, so it works with script off); an app whose spec cannot be read is listed, says so, and can be removed. There is no cap on apps or entries: the browser's storage is the limit.
42
43 Making an app is page-only: it needs the worker's database and the service worker, which exist only in a browser tab, and the terminal reaches the forge over SSH, so its palette entry only names the feature (`src/tui/screens/tab.ts`). Size: `/tab`'s script is held under a byte budget by `test/tab-apps.test.ts`.
44
45 Entries live on this device, in this browser, and are gone if the site's data is cleared. Left out: importing or exporting
46 the file, and a model filling the spec.
47
2448 ## Take an app with you (#18045)
2549
2650 The forge's home links its app as one file, `app.json` (`src/tab/spec.ts`): `{format: "forge-app", version: 1, kind: "issues", name, records?}`, a typed spec and never code, with the issues or without as the person chooses. Choosing the file (a multipart form the worker reads, `src/tab/wire.ts`) or pasting its text into *Import an app* validates it like a model's answer (shape, each field, no unknown keys, at most 200 records and 100,000 characters) and refuses one that does not fit in words, keeping nothing; one that fits sets the app's name and adds its records. The terminal says the same in `TAB_MOVE` (`src/tui/screens/tab.ts`). Tests: `test/tab.test.ts`.
src/tab/apps.ts added +128
@@ -0,0 +1,128 @@
1 /**
2 * Apps in the tab (#18043): an app is a row (its spec as JSON) and its records beside it, in the
3 * tab's own SQLite. Nothing is generated as code: a page is the spec drawn by `render.ts`. Every
4 * route returns a `TabReply`; a path it does not own returns null.
5 */
6 import { compile } from "./compile.ts";
7 import { esc } from "./escape.ts";
8 import type { TabDb, TabReply, TabRequest } from "./forge.ts";
9 import { ROOT, renderApp, type Rec } from "./render.ts";
10 import { shell } from "./shell.ts";
11 import { decodeApp, entryText, SPEC_VERSION, type BlockApp } from "./blocks.ts";
12
13 export const SAY_MAX = 300;
14
outdated

A cap added where removing would do (also RECORDS_MAX). Remove, or justify in the pull.

15 export function migrateApps(db: TabDb): void {
16 db.run("CREATE TABLE IF NOT EXISTS made (id INTEGER PRIMARY KEY, title TEXT NOT NULL, spec TEXT NOT NULL, why TEXT NOT NULL, created INTEGER NOT NULL)");
17 db.run("CREATE TABLE IF NOT EXISTS rec (id INTEGER PRIMARY KEY, app INTEGER NOT NULL, block INTEGER NOT NULL, text TEXT NOT NULL, n REAL NOT NULL, col INTEGER NOT NULL, day TEXT NOT NULL, created INTEGER NOT NULL)");
18 db.run("CREATE INDEX IF NOT EXISTS rec_app ON rec (app)");
19 }
20
21 /** The device's local day, `YYYY-MM-DD`. */
22 export const dayOf = (ms: number): string => {
23 const d = new Date(ms);
24 return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
25 };
26
27 interface Stored {
28 readonly id: number;
29 readonly app: BlockApp;
30 readonly why: readonly string[];
31 }
32
33 function load(db: TabDb, id: number): Stored | null {
34 const row = db.all("SELECT id, spec, why FROM made WHERE id = ?", [id])[0];
35 if (row === undefined) return null;
36 const decoded = decodeApp(String(row.spec));
37 if (!decoded.ok) return null;
38 let why: string[] = [];
39 try { why = (JSON.parse(String(row.why)) as unknown[]).map(String); } catch { /* a damaged note is shown as none */ }
40 return { id: Number(row.id), app: decoded.app, why };
41 }
42
43 export function appRows(db: TabDb): { id: number; title: string; glyph: string; broken: boolean }[] {
44 return db.all("SELECT id, title, spec FROM made ORDER BY id DESC").map((r) => {
45 const d = decodeApp(String(r.spec));
46 return { id: Number(r.id), title: String(r.title), glyph: d.ok ? (d.app.glyph ?? "") : "", broken: !d.ok };
47 });
48 }
49
50 /** The home page's list of apps, with the sentence that makes one when script is off. */
51 export function appsHome(db: TabDb): string {
52 const apps = appRows(db);
53 const list = apps.length === 0 ? "" : `<ul class="items">${apps.map((a) => `<li><a href="${ROOT}/apps/${a.id}">${esc(a.glyph)} ${esc(a.title)}</a>${a.broken ? ' <span class="muted">cannot be drawn</span>' : ""}</li>`).join("")}</ul>`;
54 return `<h2>Your apps</h2>${list}<form method="post" action="${ROOT}/apps" class="add"><input name="say" maxlength="${SAY_MAX}" required placeholder="Track my water, a shopping list…" aria-label="Make an app"><button>Make an app</button></form>`;
55 }
56
57 const records = (db: TabDb, app: number): Rec[] =>
58 db.all("SELECT id, block, text, n, col, day FROM rec WHERE app = ? ORDER BY id", [app]).map((r) => ({ id: Number(r.id), block: Number(r.block), text: String(r.text), n: Number(r.n), col: Number(r.col), day: String(r.day) }));
59
60 const notFound = (): TabReply => shell("Not found", "<p>No such app.</p>", 404);
61 const back = (id: number): TabReply => ({ status: 303, html: "", location: `${ROOT}/apps/${id}` });
62 const refuse = (why: string): TabReply => shell("Not saved", `<p>${esc(why)}</p>`, 422);
63
64 function source(s: Stored): string {
65 const spec = JSON.stringify(s.app, null, 2);
66 return `<p class="muted">This app is data, not code: a fixed page draws this spec. Nothing in it runs. The same file opens in the Apple app (format version ${SPEC_VERSION}).</p><h2>Why each choice</h2><ul>${s.why.map((w) => `<li>${esc(w)}</li>`).join("")}</ul><h2>The spec</h2><pre class="spec">${esc(spec)}</pre>`;
67 }
68
69 /**
70 * Removing an app drops its entries too, so it asks for the title, typed (works with script off).
71 */
72 const removeForm = (id: number, title: string): string =>
73 `<form method="post" action="${ROOT}/apps/${id}/delete" class="remove"><label>Type “${esc(title)}” to remove this app and its entries<input name="confirm" autocomplete="off" required></label><button class="danger">Remove this app</button></form>`;
74
75 export function handleApps(db: TabDb, req: TabRequest, path: string, now: number): TabReply | null {
76 if (!path.startsWith("/apps")) return null;
77 const parts = path.split("/").slice(2);
78 if (req.method === "POST" && parts.length === 0) {
79 const say = (req.form.say ?? "").trim();
80 if (say === "" || say.length > SAY_MAX) return refuse(`Say what the app should do, in up to ${SAY_MAX} characters.`);
81 const made = compile(say);
82 db.run("INSERT INTO made (title, spec, why, created) VALUES (?, ?, ?, ?)", [made.app.title, JSON.stringify(made.app), JSON.stringify(made.why), now]);
83 return back(Number(db.all("SELECT max(id) AS id FROM made")[0]?.id));
84 }
85 const id = /^\d{1,9}$/.test(parts[0] ?? "") ? Number(parts[0]) : 0;
86 const row = id === 0 ? undefined : db.all("SELECT title FROM made WHERE id = ?", [id])[0];
87 if (row === undefined) return notFound();
88 const title = String(row.title);
89 const found = load(db, id);
outdated

Never: deleting the app and all its entries has no typed-name confirmation. Require the app's title typed in a field, in a red button form, checked here.

90 if (req.method === "GET" && parts.length === 1)
91 return found === null
92 ? shell(title, `<h1>${esc(title)}</h1><p>This app's spec cannot be read, so it cannot be drawn. It can still be removed.</p>${removeForm(id, title)}`)
93 : shell(found.app.title, `${renderApp(found.app, { appId: id, records: records(db, id), today: dayOf(now) })}<p><a href="${ROOT}/apps/${id}/source">How this app was made</a></p>${removeForm(id, title)}`, 200, false);
94 if (req.method === "GET" && parts[1] === "source" && parts.length === 2) return found === null ? notFound() : shell(`${found.app.title}: why`, source(found));
95 if (req.method !== "POST") return shell("Not allowed", "<p>That is not something this forge does.</p>", 405);
96 if (parts[1] === "delete" && parts.length === 2) {
97 if ((req.form.confirm ?? "").trim() !== title.trim()) return refuse("Type the app's title exactly to remove it and its entries. Nothing was removed.");
98 db.run("DELETE FROM rec WHERE app = ?", [id]);
99 db.run("DELETE FROM made WHERE id = ?", [id]);
100 return { status: 303, html: "", location: `${ROOT}/` };
101 }
102 if (found === null) return notFound();
103 const block = /^\d{1,2}$/.test(parts[1] ?? "") ? Number(parts[1]) : -1;
104 const b = found.app.blocks[block];
105 const op = parts[2] ?? "";
106 if (b === undefined || parts.length !== 3) return notFound();
107 const rid = /^\d{1,9}$/.test(req.form.id ?? "") ? Number(req.form.id) : 0;
108 const mine = rid === 0 ? undefined : db.all("SELECT id, col FROM rec WHERE id = ? AND app = ? AND block = ?", [rid, id, block])[0];
109 const columns = b.options.length > 0 ? b.options.length : 3;
110 if (op === "add" && ["list", "notes", "board"].includes(b.kind)) {
111 const text = entryText(req.form.text);
112 if (text === "") return refuse("An entry needs some text.");
113 db.run("INSERT INTO rec (app, block, text, n, col, day, created) VALUES (?, ?, ?, 0, 0, ?, ?)", [id, block, text, dayOf(now), now]);
114 } else if (op === "tap" && (b.kind === "counter" || b.kind === "tracker")) {
115 const n = Number(req.form.n);
116 if (req.form.n === undefined || req.form.n.trim() === "" || !Number.isFinite(n) || Math.abs(n) > 1e9) return refuse("An amount is a number.");
117 db.run("INSERT INTO rec (app, block, text, n, col, day, created) VALUES (?, ?, '', ?, 0, ?, ?)", [id, block, n, dayOf(now), now]);
118 } else if (op === "toggle" && b.kind === "list" && mine !== undefined) {
119 db.run("UPDATE rec SET col = ? WHERE id = ?", [Number(mine.col) === 1 ? 0 : 1, rid]);
120 } else if (op === "move" && b.kind === "board" && mine !== undefined) {
121 const to = Number(req.form.to);
122 if (!Number.isInteger(to) || to < 0 || to >= columns) return refuse("That column does not exist.");
123 db.run("UPDATE rec SET col = ? WHERE id = ?", [to, rid]);
124 } else if (op === "del" && mine !== undefined) {
125 db.run("DELETE FROM rec WHERE id = ?", [rid]);
126 } else return notFound();
127 return back(id);
128 }
src/tab/blocks.ts added +75
@@ -0,0 +1,75 @@
1 /**
2 * The app format, shared with the Apple app's `Blocks.swift` (#18043): one versioned JSON, a `kind`
3 * per block. Plain data in, plain data out. Reading is lenient (a missing field takes its default,
4 * an unknown field is ignored); an unknown `kind` is kept, so an old reader never loses a newer
5 * app's block.
6 */
7
8 export const SPEC_VERSION = 1;
9
10 export interface Block {
11 readonly kind: string;
12 readonly name: string;
13 readonly label: string;
14 readonly options: readonly string[];
15 readonly value: number;
16 readonly formula: string;
17 readonly unit?: string;
18 readonly step?: number;
19 readonly noun?: string;
20 readonly add?: string;
21 readonly placeholder?: string;
22 readonly emptyTitle?: string;
23 readonly emptyHint?: string;
24 }
25
26 export interface BlockApp {
27 readonly version: number;
28 readonly title: string;
29 readonly glyph?: string;
30 readonly blocks: readonly Block[];
31 }
32
33 export const LIMITS = { title: 80, text: 120, options: 12, blocks: 12, entry: 500, json: 20000 } as const;
34
35 const clip = (v: unknown, max: number): string => (typeof v === "string" ? v.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max) : "");
36 const num = (v: unknown, fallback: number): number => (typeof v === "number" && Number.isFinite(v) ? v : fallback);
37
38 /** Clean one entry the person typed: no control bytes, bounded. */
39 export const entryText = (v: unknown): string => clip(v, LIMITS.entry);
40
41 function decodeBlock(raw: unknown): Block | null {
42 if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
43 const r = raw as Record<string, unknown>;
44 const kind = clip(r.kind, 40);
45 if (kind === "") return null;
46 const optional = (key: "unit" | "noun" | "add" | "placeholder" | "emptyTitle" | "emptyHint"): Partial<Block> => {
47 const v = clip(r[key], LIMITS.text);
48 return v === "" ? {} : { [key]: v };
49 };
50 const options = Array.isArray(r.options) ? r.options.map((o) => clip(o, 40)).filter((o) => o !== "").slice(0, LIMITS.options) : [];
51 const step = typeof r.step === "number" && Number.isFinite(r.step) && r.step > 0 ? r.step : undefined;
52 return {
53 kind, name: clip(r.name, 40), label: clip(r.label, LIMITS.text), options, value: num(r.value, 0), formula: clip(r.formula, 200),
54 ...(step === undefined ? {} : { step }),
55 ...optional("unit"), ...optional("noun"), ...optional("add"), ...optional("placeholder"), ...optional("emptyTitle"), ...optional("emptyHint"),
56 };
57 }
58
59 export type Decoded = { readonly ok: true; readonly app: BlockApp } | { readonly ok: false; readonly why: string };
60
61 /** Read an app from JSON text or a parsed value; a newer major version is refused in words. */
62 export function decodeApp(input: unknown): Decoded {
63 let raw = input;
64 if (typeof input === "string") {
65 if (input.length > LIMITS.json) return { ok: false, why: "This app file is too large to open here." };
66 try { raw = JSON.parse(input); } catch { return { ok: false, why: "This is not an app file: it is not JSON." }; }
67 }
68 if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return { ok: false, why: "This is not an app file." };
69 const r = raw as Record<string, unknown>;
70 const version = num(r.version, SPEC_VERSION);
71 if (Math.floor(version) > SPEC_VERSION) return { ok: false, why: `This app is version ${Math.floor(version)}; this device reads version ${SPEC_VERSION}. Update to open it.` };
72 const blocks = (Array.isArray(r.blocks) ? r.blocks : []).slice(0, LIMITS.blocks).map(decodeBlock).filter((b): b is Block => b !== null);
73 const glyph = clip(r.glyph, 8);
74 return { ok: true, app: { version: SPEC_VERSION, title: clip(r.title, LIMITS.title) || "Untitled", ...(glyph === "" ? {} : { glyph }), blocks } };
75 }
src/tab/boot.ts +51 −5
@@ -13,7 +13,10 @@ interface Box {
1313 disabled: boolean;
1414 hidden: boolean;
1515 src: string;
16 addEventListener(type: "click", listener: () => void): void;
16 value: string;
17 srcdoc: string;
18 addEventListener(type: "click" | "input", listener: () => void): void;
19 addEventListener(type: "submit", listener: (e: { preventDefault(): void }) => void): void;
1720 }
1821 interface Registrations {
1922 addEventListener(type: "message", listener: (e: MessageEvent<{ forge?: TabRequest }>) => void): void;
@@ -39,12 +42,12 @@ navigator.serviceWorker?.addEventListener("message", (e: MessageEvent<{ forge?:
3942 });
4043 navigator.serviceWorker?.startMessages();
4144
42 async function start(button: Box): Promise<void> {
45 async function start(button: Box): Promise<boolean> {
4346 button.disabled = true;
4447 const workers = navigator.serviceWorker;
4548 if (workers === undefined || typeof Worker === "undefined" || navigator.storage?.getDirectory === undefined) {
4649 say("This browser cannot run a forge in a tab: it lacks service workers or private file storage.");
47 return;
50 return false;
4851 }
4952 say("Starting…");
5053 const worker = new Spawn(button.dataset.worker!, { type: "module" });
@@ -59,7 +62,7 @@ async function start(button: Box): Promise<void> {
5962 worker.terminate();
6063 say("The forge's storage could not open. Another tab of this browser may already hold the forge: use that one, or close it and press Start again.");
6164 button.disabled = false;
62 return;
65 return false;
6366 }
6467 holder = worker;
6568 try {
@@ -72,13 +75,23 @@ async function start(button: Box): Promise<void> {
7275 worker.terminate();
7376 say("The browser would not start the forge's server in this tab. Reload the page and press Start again; a private window may not allow it.");
7477 button.disabled = false;
75 return;
78 return false;
7679 }
7780 const frame = document.getElementById("tab-frame")!;
7881 frame.src = "/tab/f/";
7982 frame.hidden = false;
8083 document.documentElement.dataset.running = "1";
8184 say("Running in this tab.");
85 return true;
86 }
87
88 /** One request to the database worker, answered on its own port. */
89 function ask(req: TabRequest): Promise<{ status: number; location?: string }> {
90 return new Promise((resolve) => {
91 const channel = new MessageChannel();
92 channel.port1.onmessage = (e) => resolve(e.data);
93 holder!.postMessage({ req }, [channel.port2]);
94 });
8295 }
8396
8497 // Script runs, so the button can work: show it (it is hidden for a page without JavaScript).
@@ -89,3 +102,36 @@ if (button !== null && go !== null) {
89102 say("Not started.");
90103 button.addEventListener("click", () => void start(button));
91104 }
105
106 // "Make an app": the compiler is a separate file, fetched the first time the box is used, so the
107 // page stays small for a person who only reads it. The preview is the compiled app's own page in a
108 // frame that runs no script.
109 const make = document.getElementById("tab-make");
110 const sayBox = document.getElementById("tab-say");
111 const previewFrame = document.getElementById("tab-preview");
112 if (make !== null && sayBox !== null && previewFrame !== null && button !== null) {
113 make.hidden = false;
114 let compiler: Promise<{ preview(sentence: string): string }> | null = null;
115 const show = async (): Promise<void> => {
116 compiler ??= import(/* @vite-ignore */ make.dataset.make!);
117 const loaded = await compiler;
118 previewFrame.srcdoc = loaded.preview(sayBox.value);
119 previewFrame.hidden = false;
120 };
121 sayBox.addEventListener("input", () => void show());
122 make.addEventListener("submit", (e) => {
123 e.preventDefault();
124 void (async () => {
125 const sentence = sayBox.value.trim();
126 if (sentence === "") return;
127 if (holder === null && !(await start(button))) return;
128 const done = await ask({ method: "POST", path: "/apps", form: { say: sentence } });
129 if (done.location !== undefined) {
130 document.getElementById("tab-frame")!.src = done.location;
131 previewFrame.hidden = true;
132 sayBox.value = "";
133 say("Made. It is kept on this device, in this browser.");
134 } else say("That could not be saved. Try a shorter sentence.");
135 })();
136 });
137 }
src/tab/compile.ts added +87
@@ -0,0 +1,87 @@
1 /**
2 * The deterministic compiler (#18043): a sentence in, a `BlockApp` and the reason for each choice
3 * out. No model, no network, the same sentence always gives the same app. It runs on every
4 * keystroke, so it is a few regexes.
5 */
6 import { SPEC_VERSION, type Block, type BlockApp } from "./blocks.ts";
7
8 export interface Compiled {
9 readonly app: BlockApp;
10 /** One line per choice, in plain words: what the page shows as "why". */
11 readonly why: readonly string[];
12 }
13
14 const word = (s: string, words: string): string | null => new RegExp(`\\b(?:${words})\\b`, "i").exec(s)?.[0].toLowerCase() ?? null;
15
16 const GLYPHS: readonly [string, string][] = [
17 ["water|drink|hydrat", "💧"], ["coffee|tea", "☕"], ["run|walk|steps|km|miles|jog", "👟"], ["read|book|pages", "📖"], ["shop|grocer|buy", "🛒"],
18 ["pack|trip|travel", "🧳"], ["idea|note|journal|diary", "📝"], ["bug|task|project|kanban|sprint", "📋"], ["gym|workout|push|reps|lift", "💪"],
19 ["sleep", "😴"], ["job|hire|applic", "💼"], ["movie|film|watch", "🎬"],
20 ];
21
22 // What a tap adds, and its unit, for what people track.
23 const UNITS: readonly [string, string, number][] = [
24 ["water", "glasses", 1], ["coffee", "cups", 1], ["tea", "cups", 1], ["steps", "steps", 1000], ["pages|reading|read", "pages", 10],
25 ["run|running|walk|walking", "km", 1], ["push-?ups?|pull-?ups?|reps|workout", "reps", 10], ["sleep", "hours", 1], ["calories|kcal", "kcal", 100],
26 ];
27 const KNOWN_UNIT = /\b(\d+(?:\.\d+)?)\s*(ml|l|km|mi|miles|pages|steps|minutes|min|hours|cups|glasses|kg|lb|reps|kcal)\b/i;
28
29 const NOUNS: readonly [string, string][] = [["bugs?", "bug"], ["tasks?|todos?|to-?dos?", "task"], ["jobs?|applications?", "application"], ["leads?", "lead"], ["stories|story", "story"], ["ideas?", "idea"], ["recipes?", "recipe"]];
30
31 /**
32 * The text of the sentence made into a title: no leading "make me an app to", capitalised, bounded.
33 */
34 function titleOf(say: string): string {
35 const t = say.replace(/^(?:please\s+)?(?:make|build|create|i\s+(?:want|need))\s+(?:me\s+)?(?:an?\s+|the\s+)?(?:app\s+)?(?:to|for|that|which|of)?\s*/i, "").replace(/^(?:an?|my|the)\s+/i, "").replace(/[.!?]+$/, "").trim();
36 const cut = (t === "" ? say.trim() : t).slice(0, 40).trim();
37 return cut === "" ? "My app" : cut.charAt(0).toUpperCase() + cut.slice(1);
38 }
39
40 function columnsOf(say: string): string[] | null {
41 const m = /\b(?:columns?|lanes?|stages?|with|into)\s*:?\s+(?:(?:columns?|lanes?|stages?)\s*:?\s+)?([a-z][\w' -]*(?:\s*(?:,|\/|->|→|>)\s*[a-z][\w' -]*){1,5})/i.exec(say);
42 if (m?.[1] === undefined) return null;
43 const names = m[1].split(/\s*(?:,|\/|->|→|>)\s*/).map((s) => s.replace(/^(?:and|then)\s+/i, "").trim()).filter((s) => s !== "");
44 return names.length >= 2 ? names.map((n) => n.charAt(0).toUpperCase() + n.slice(1)) : null;
45 }
46
47 /**
48 * Compile one sentence. An empty sentence compiles to an empty list, so the preview is never blank.
49 */
50 export function compile(sentence: string): Compiled {
51 const say = sentence.replace(/\s+/g, " ").trim().slice(0, 300);
52 const why: string[] = [];
53 const title = titleOf(say);
54 why.push(say === "" ? "Nothing said yet, so the title is “My app”." : `The title is your sentence without its opening words: “${title}”.`);
55 const glyph = GLYPHS.find(([re]) => new RegExp(`\\b(?:${re})`, "i").test(say))?.[1];
56 if (glyph !== undefined) why.push(`${glyph} fits a word you used.`);
57
58 let block: Block;
59 const base = { name: "main", options: [] as string[], value: 0, formula: "" };
60 const board = word(say, "board|kanban|pipeline|sprint|columns?|lanes?|stages?|to-?do,? doing,? (?:and )?done");
61 const tracker = word(say, "track(?:er|ing)?|log|habit|daily|each day|every day|per day|history") ?? (KNOWN_UNIT.test(say) ? "a number with a unit" : null);
62 const counter = word(say, "count(?:er|ing)?|tally|clicks?|score");
63 const notes = word(say, "notes?|journal|diary|ideas?|thoughts?|memos?|jot");
64 if (board !== null) {
65 const cols = columnsOf(say) ?? ["To do", "Doing", "Done"];
66 const noun = NOUNS.find(([re]) => word(say, re) !== null)?.[1] ?? "card";
67 block = { ...base, kind: "board", label: title, options: cols, noun, add: `Add a ${noun}` };
68 why.push(`“${board}” means cards that move, so it is a board.`, columnsOf(say) === null ? "No columns named, so: To do, Doing, Done." : `Columns are the ones you named: ${cols.join(", ")}.`, `A card is called a ${noun}.`);
69 } else if (tracker !== null && counter === null) {
70 const unitHit = KNOWN_UNIT.exec(say);
71 const known = UNITS.find(([re]) => word(say, re) !== null);
72 const unit = unitHit?.[2]?.toLowerCase() ?? known?.[1] ?? "";
73 const step = unitHit?.[1] !== undefined ? Number(unitHit[1]) : (known?.[2] ?? 1);
74 block = { ...base, kind: "tracker", label: title, ...(unit === "" ? {} : { unit }), step, value: step, add: "Add" };
75 why.push(`“${tracker}” means a number each day, so it is a tracker.`, unit === "" ? "No unit named, so it counts plain numbers." : `The unit is ${unit}.`, `One tap adds ${step}${unit === "" ? "" : ` ${unit}`}.`);
76 } else if (counter !== null) {
77 block = { ...base, kind: "counter", label: title, step: 1, value: 0 };
78 why.push(`“${counter}” means one number that goes up and down, so it is a counter.`);
79 } else if (notes !== null) {
80 block = { ...base, kind: "notes", label: title, placeholder: "Write a note", add: "Save", emptyTitle: "No notes yet", emptyHint: "Write the first one above." };
81 why.push(`“${notes}” means free text, newest first, so it is notes.`);
82 } else {
83 block = { ...base, kind: "list", label: title, placeholder: "Add an item", add: "Add", emptyTitle: "Nothing here yet", emptyHint: "Add the first item above." };
84 why.push(say === "" ? "A list is where an empty sentence starts." : "No word asked for anything else, so it is a list you can tick off.");
85 }
86 return { app: { version: SPEC_VERSION, title, ...(glyph === undefined ? {} : { glyph }), blocks: [block] }, why };
87 }
src/tab/escape.ts added +3
@@ -0,0 +1,3 @@
1 /** Every value that reaches a tab page passes through here: the one escape. */
2 const ESCAPES: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
3 export const esc = (s: string | number | undefined): string => String(s ?? "").replace(/[&<>"']/g, (c) => ESCAPES[c]!);
src/tab/forge.ts +11 −14
@@ -1,11 +1,15 @@
1 import { BODY_MAX, makeSpec, NAME_MAX, parseSpec, RECORDS_CAP, SPEC_MAX, TITLE_MAX } from "./spec.ts";
2
31 /**
42 * The forge in the tab, as a function: a request and a database in, a page out. It runs in the
53 * browser's database worker over SQLite wasm and, in tests, over bun:sqlite; it imports nothing
64 * from the server, so the same file serves both.
75 */
86
7 import { appsHome, handleApps, migrateApps } from "./apps.ts";
8 import { esc } from "./escape.ts";
9 import { ROOT } from "./render.ts";
10 import { shell } from "./shell.ts";
11 import { BODY_MAX, makeSpec, NAME_MAX, parseSpec, RECORDS_CAP, SPEC_MAX, TITLE_MAX } from "./spec.ts";
12
913 /** The two things it asks of a database. */
1014 export interface TabDb {
1115 run(sql: string, bind?: readonly (string | number)[]): void;
@@ -36,20 +40,11 @@ export function migrate(db: TabDb): void {
3640 );
3741 db.run("CREATE TABLE IF NOT EXISTS app (id INTEGER PRIMARY KEY CHECK (id = 1), name TEXT NOT NULL)");
3842 db.run("INSERT OR IGNORE INTO app (id, name) VALUES (1, 'Your forge')");
43 migrateApps(db);
3944 }
4045
4146 const appName = (db: TabDb): string => String(db.all("SELECT name FROM app WHERE id = 1")[0]?.name ?? "Your forge");
4247
43 const ESCAPES: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
44 export const esc = (s: string | number | undefined): string => String(s ?? "").replace(/[&<>"']/g, (c) => ESCAPES[c]!);
45
46 const ROOT = "/tab/f";
47
48 function shell(title: string, body: string, status = 200): TabReply {
49 const nav = `<nav><a href="${ROOT}/">Home</a> <a href="${ROOT}/issues">Issues</a></nav>`;
50 return { status, html: `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title><link rel="stylesheet" href="/tab/f.css"></head><body><main>${nav}<h1>${esc(title)}</h1>${body}</main></body></html>` };
51 }
52
5348 const rows = (db: TabDb, limit: number) => db.all("SELECT id, title, created FROM issue ORDER BY id DESC LIMIT ?", [limit]);
5449
5550 function list(items: ReturnType<typeof rows>): string {
@@ -71,12 +66,14 @@ const move = (issues: number): string => {
7166
7267 const FORM = `<form method="post" action="${ROOT}/issues"><label>Title <input name="title" maxlength="${TITLE_MAX}" required></label><label>Description <textarea name="body" maxlength="${BODY_MAX}"></textarea></label><button>Open issue</button></form>`;
7368
74 export function handle(db: TabDb, req: TabRequest): TabReply {
69 export function handle(db: TabDb, req: TabRequest, now = Date.now()): TabReply {
7570 const path = req.path.replace(/\/+$/, "") || "/";
71 const app = handleApps(db, req, path, now);
72 if (app !== null) return app;
7673 if (req.method === "GET") {
7774 if (path === "/") {
7875 const n = Number(db.all("SELECT count(*) AS n FROM issue")[0]?.n ?? 0);
79 return shell(appName(db), `<p>${n} ${n === 1 ? "issue" : "issues"}, kept on this device.</p>${list(rows(db, 5))}${FORM}${move(n)}`);
76 return shell(appName(db), `<p>${n} ${n === 1 ? "issue" : "issues"}, kept on this device.</p>${list(rows(db, 5))}${FORM}${move(n)}${appsHome(db)}`);
8077 }
8178 if (path === "/app.json") {
8279 const withRecords = ["1", "true"].includes(new URLSearchParams(req.query ?? "").get("records") ?? "");
src/tab/make.ts added +8
@@ -0,0 +1,8 @@
1 /**
2 * The compiler's browser entry, loaded by `boot.ts` only when the "Make an app" box is used
3 * (#18043): a sentence in, the real app's page out, with no network and no model.
4 */
5 import { compile } from "./compile.ts";
6 import { previewDocument } from "./render.ts";
7
8 export const preview = (sentence: string): string => previewDocument(compile(sentence).app);
src/tab/render.ts added +107
@@ -0,0 +1,107 @@
1 /**
2 * The fixed renderers (#18043): a `BlockApp` and its records in, escaped HTML out. One function per
3 * kind; an app is data, so nothing the spec says is ever run. With `appId` null the app is drawn as
4 * a preview: the same markup, no forms.
5 */
6 import { esc } from "./escape.ts";
7 import type { Block, BlockApp } from "./blocks.ts";
8
9 export interface Rec {
10 readonly id: number;
11 readonly block: number;
12 readonly text: string;
13 readonly n: number;
14 /** A list item's done flag (0 or 1) or a board card's column index. */
15 readonly col: number;
16 /** The local day a tracker entry was made, `YYYY-MM-DD`. */
17 readonly day: string;
18 }
19
20 export interface View {
21 /** The stored app's id, or null for a preview. */
22 readonly appId: number | null;
23 readonly records: readonly Rec[];
24 readonly today: string;
25 }
26
27 export const ROOT = "/tab/f";
28
29 /** A whole page, the one template both the forge's pages and a preview use. */
30 export function pageOf(title: string, body: string, nav = ""): string {
31 return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title><link rel="stylesheet" href="/tab/f.css"></head><body><main>${nav}${body}</main></body></html>`;
32 }
33
34 const form = (v: View, block: number, op: string, fields: string, label: string, cls = ""): string =>
35 v.appId === null
36 ? `<span class="act ${cls}" aria-hidden="true">${label}</span>`
37 : `<form method="post" action="${ROOT}/apps/${v.appId}/${block}/${op}" class="${cls}">${fields}<button>${label}</button></form>`;
38 const hidden = (name: string, value: string | number): string => `<input type="hidden" name="${name}" value="${esc(value)}">`;
39 const empty = (b: Block, title: string, hint: string): string => `<p class="muted"><strong>${esc(b.emptyTitle ?? title)}</strong> ${esc(b.emptyHint ?? hint)}</p>`;
40 const ofBlock = (v: View, i: number): Rec[] => v.records.filter((r) => r.block === i);
41 const addBox = (v: View, i: number, b: Block): string =>
42 v.appId === null
43 ? `<p class="field">${esc(b.placeholder ?? "")}</p>`
44 : `<form method="post" action="${ROOT}/apps/${v.appId}/${i}/add" class="add"><input name="text" maxlength="500" required placeholder="${esc(b.placeholder ?? "")}" aria-label="${esc(b.placeholder || b.label)}"><button>${esc(b.add ?? "Add")}</button></form>`;
45
46 function list(v: View, i: number, b: Block): string {
47 const items = ofBlock(v, i).sort((a, c) => a.col - c.col || a.id - c.id);
48 const li = items.map((r) => `<li class="${r.col === 1 ? "done" : ""}">${form(v, i, "toggle", hidden("id", r.id), r.col === 1 ? "☑" : "☐", "tick")}<span>${esc(r.text)}</span>${form(v, i, "del", hidden("id", r.id), "Remove", "quiet")}</li>`).join("");
49 return `${addBox(v, i, b)}${items.length === 0 ? empty(b, "Nothing here yet", "Add the first item above.") : `<ul class="items">${li}</ul>`}`;
50 }
51
52 function notes(v: View, i: number, b: Block): string {
53 const items = ofBlock(v, i).sort((a, c) => c.id - a.id);
54 return `${addBox(v, i, b)}${items.length === 0 ? empty(b, "No notes yet", "Write the first one above.") : items.map((r) => `<p class="note">${esc(r.text)}</p>`).join("")}`;
55 }
56
57 const sum = (rs: readonly Rec[]): number => Math.round(rs.reduce((t, r) => t + r.n, 0) * 1000) / 1000;
58
59 function counter(v: View, i: number, b: Block): string {
60 const step = b.step ?? 1;
61 const total = sum(ofBlock(v, i)) + b.value;
62 return `<p class="big" aria-live="polite">${esc(total)}</p><div class="pair">${form(v, i, "tap", hidden("n", -step), `−${esc(step)}`)}${form(v, i, "tap", hidden("n", step), `+${esc(step)}`)}</div>`;
63 }
64
65 function tracker(v: View, i: number, b: Block): string {
66 const step = b.step ?? 1;
67 const amount = b.value > 0 ? b.value : step;
68 const unit = b.unit === undefined ? "" : ` ${esc(b.unit)}`;
69 const rs = ofBlock(v, i);
70 const days = new Map<string, number>();
71 for (const r of [...rs].sort((a, c) => c.id - a.id)) days.set(r.day, (days.get(r.day) ?? 0) + r.n);
72 const today = sum(rs.filter((r) => r.day === v.today));
73 const history = [...days].slice(0, 14).map(([d, n]) => `<li><span>${esc(d)}</span><span>${esc(Math.round(n * 1000) / 1000)}${unit}</span></li>`).join("");
74 const add = v.appId === null
75 ? `<span class="act">+${esc(amount)}${unit}</span>`
76 : `<form method="post" action="${ROOT}/apps/${v.appId}/${i}/tap" class="add"><input name="n" type="number" step="any" inputmode="decimal" value="${esc(amount)}" required aria-label="Amount${unit}"><button>${esc(b.add ?? "Add")}</button></form>`;
77 return `<p class="muted">Today</p><p class="big" aria-live="polite">${esc(Math.round(today * 1000) / 1000)}${unit}</p>${add}${history === "" ? empty(b, "No entries yet", "Add the first one above.") : `<ul class="items history">${history}</ul>`}`;
78 }
79
80 function board(v: View, i: number, b: Block): string {
81 const cols = b.options.length > 0 ? b.options : ["To do", "Doing", "Done"];
82 const noun = b.noun ?? "card";
83 const rs = ofBlock(v, i);
84 const lanes = cols.map((name, c) => {
85 const cards = rs.filter((r) => Math.min(Math.max(r.col, 0), cols.length - 1) === c).sort((a, d) => a.id - d.id);
86 const items = cards.map((r) => `<li>${esc(r.text)}<span class="pair">${c > 0 ? form(v, i, "move", hidden("id", r.id) + hidden("to", c - 1), "←", "quiet") : ""}${c < cols.length - 1 ? form(v, i, "move", hidden("id", r.id) + hidden("to", c + 1), "→", "quiet") : ""}${form(v, i, "del", hidden("id", r.id), "Remove", "quiet")}</span></li>`).join("");
87 return `<section class="lane"><h3>${esc(name)} <span class="muted">${cards.length}</span></h3>${cards.length === 0 ? `<p class="muted">No ${esc(noun)}s</p>` : `<ul class="items">${items}</ul>`}</section>`;
88 });
89 return `${addBox(v, i, { ...b, placeholder: b.placeholder ?? `New ${noun}`, add: b.add ?? `Add a ${noun}` })}<div class="lanes">${lanes.join("")}</div>`;
90 }
91
92 const DRAW: Record<string, (v: View, i: number, b: Block) => string> = { list, notes, counter, tracker, board };
93
94 function one(v: View, i: number, b: Block): string {
95 const label = b.label === "" ? b.name : b.label;
96 const draw = Object.hasOwn(DRAW, b.kind) ? DRAW[b.kind] : undefined;
97 const inner = draw === undefined ? `<p class="muted">This device cannot show a “${esc(b.kind)}” block yet.</p>` : draw(v, i, b);
98 return `<section class="block block-${draw === undefined ? "unknown" : esc(b.kind)}"><h2>${esc(label)}</h2>${inner}</section>`;
99 }
100
101 /** The app: its title and each block, drawn. */
102 export function renderApp(app: BlockApp, v: View): string {
103 return `<h1>${app.glyph === undefined ? "" : `<span aria-hidden="true">${esc(app.glyph)}</span> `}${esc(app.title)}</h1>${app.blocks.map((b, i) => one(v, i, b)).join("")}`;
104 }
105
106 /** The preview the box shows: the same app, empty, with no forms. */
107 export const previewDocument = (app: BlockApp): string => pageOf(app.title, renderApp(app, { appId: null, records: [], today: "" }));
src/tab/shell.ts added +9
@@ -0,0 +1,9 @@
1 /** The tab forge's page frame: navigation, title, status. Plain data out. */
2 import type { TabReply } from "./forge.ts";
3 import { esc } from "./escape.ts";
4 import { pageOf, ROOT } from "./render.ts";
5
6 export function shell(title: string, body: string, status = 200, heading = true): TabReply {
7 const nav = `<nav><a href="${ROOT}/">Home</a> <a href="${ROOT}/issues">Issues</a></nav>`;
8 return { status, html: pageOf(title, `${heading ? `<h1>${esc(title)}</h1>` : ""}${body}`, nav) };
9 }
src/tab/words.ts +2 −1
@@ -8,6 +8,7 @@ export const TAB_TITLE = "A forge in this tab";
88 export const TAB_FACTS: readonly string[] = [
99 "It lives on this device: its database is a SQLite file in this browser's private storage.",
1010 "It stops when the tab closes: the tab is its server, so nothing answers while it is shut.",
11 "It is gone if this site's data is cleared in the browser: nothing is kept anywhere else, so clear it only when you mean to.",
1112 "Others cannot reach it: it has no address on the network, and the forge that served this page holds none of it.",
1213 ];
1314
@@ -18,4 +19,4 @@ export const TAB_LEFT_OUT = "No git, shell or installs here: those need a real L
1819 export const TAB_MOVE = "An app is one JSON file: download it from the forge's home (with its issues or without) and choose it (or paste it) in another tab forge, which refuses a file that does not fit.";
1920
2021 /** The terminal's one sentence: the facts and where the page is. */
21 export const tabLine = (): string => `${TAB_FACTS.join(" ")} ${TAB_LEFT_OUT} ${TAB_MOVE} Open /tab in a browser to start it.`;
22 export const tabLine = (): string => `${TAB_FACTS.join(" ")} ${TAB_LEFT_OUT} ${TAB_MOVE} Open /tab in a browser to start it and to make an app from a sentence.`;
src/tui/screens/tab.ts +1 −1
@@ -7,7 +7,7 @@ export const entry: PaletteEntry = {
77 rank: 910,
88 id: "tab-forge",
99 title: "A forge in a browser tab",
10 hint: "where it lives, when it stops, who can reach it",
10 hint: "where it lives, when it stops, who can reach it, make an app from a sentence",
1111 offered: () => true,
1212 run: (_session, ctx) => ctx.toast(tabLine(), "default"),
1313 };
src/web/pages/tab.ts +6
@@ -17,6 +17,12 @@ export async function tabPage(ctx: Ctx): Promise<Response> {
1717 const boot = await tabScript("boot");
1818 const body = html`${pageHead(TAB_TITLE, { sub: TAB_LEFT_OUT })}
1919 <div id="tab-facts">${rowList(TAB_FACTS.map((fact) => row({ title: fact })))}</div>
20 <form id="tab-make" action="/tab" method="get" hidden data-make="/tab/make.js">
21 <label for="tab-say"><strong>Make an app</strong></label>
22 <input id="tab-say" name="say" maxlength="300" autocomplete="off" placeholder="Track my water, a shopping list, a board for my bugs…">
23 <button class="btn" type="submit">Make it</button>
24 <iframe id="tab-preview" class="tab-frame" title="Preview of your app" sandbox="" src="about:blank" hidden></iframe>
25 </form>
2026 <noscript><p>A forge in a tab needs JavaScript: it runs in this page's scripts.</p></noscript>
2127 <p id="tab-go" hidden>
2228 <button id="tab-start" class="btn" type="button" data-worker="/tab/worker.js" data-sw="/tab/sw.js" data-sqlite="${sqliteModulePath()}">
src/web/tab-asset.ts +28 −8
@@ -2,7 +2,8 @@
22 * The files the forge in a tab is made of, all static: nothing here costs the serving forge more
33 * than a file read.
44 *
5 * - `/tab/worker.js` and `/tab/sw.js`: `src/tab/worker.ts` and `src/tab/sw.ts`, bundled by
5 * - `/tab/worker.js`, `/tab/sw.js` and `/tab/make.js` (the compiler, fetched only when the "Make an
6 * app" box is used): `src/tab/worker.ts`, `src/tab/sw.ts` and `src/tab/make.ts`, bundled by
67 * `Bun.build` at first use. Fixed paths (a service worker's scope comes from its path), answered
78 * with a validator and `no-cache`.
89 * - `/tab/v/<hash>/sqlite3.mjs` and `sqlite3.wasm`: the vendored SQLite wasm
@@ -13,13 +14,29 @@
1314
1415 import { readFileSync } from "node:fs";
1516 import { join } from "node:path";
17 import { THEMES } from "../design/themes.ts";
1618 import { sha256 } from "../kernel/hash.ts";
1719 import { bundleEntry, staticResponse, type BuiltAsset } from "./asset.ts";
1820 import { noneMatch } from "../http/conditional.ts";
1921
2022 const VENDOR = join(import.meta.dir, "vendor", "sqlite-wasm");
2123
22 const STYLE = `:root{color-scheme:light dark}body{margin:0;font:15px/1.5 system-ui,sans-serif}main{max-width:36rem;margin:0 auto;padding:16px}nav{display:flex;gap:12px}nav a{display:inline-flex;align-items:center;min-height:44px}h1{font-size:20px;margin:.75rem 0}h2{font-size:16px;margin:1.5rem 0 .5rem}main{overflow-wrap:anywhere}label{display:grid;gap:4px}input,textarea{width:100%}.muted{opacity:.7}form{display:grid;gap:8px;margin-top:16px}input,textarea,button{font:inherit;font-size:16px;padding:6px 10px;min-height:44px;box-sizing:border-box}textarea{min-height:5rem}.body{white-space:pre-wrap}`;
24 const light = THEMES.light.tokens;
25 const dark = THEMES.dark.tokens;
26 const tokens = (t: typeof light): string => `--bg:${t.bg};--fg:${t.fg};--muted-fg:${t["muted-fg"]};--accent:${t.accent};--border:${t.border};--danger:${t.danger}`;
27 /**
28 * The forge's own tokens (design/themes.ts), inlined: this sheet is served apart from the forge's.
29 */
30 const STYLE = `:root{color-scheme:light dark;${tokens(light)}}@media(prefers-color-scheme:dark){:root{${tokens(dark)}}}
31 body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}main{max-width:36rem;margin:0 auto;padding:16px;overflow-wrap:anywhere}a{color:var(--accent)}
32 nav{display:flex;gap:12px}nav a{display:inline-flex;align-items:center;min-height:44px}h1{font-size:20px;margin:.75rem 0}h2{font-size:16px;margin:1.5rem 0 .5rem}.muted{color:var(--muted-fg)}
33 form{display:grid;gap:8px;margin-top:16px}label{display:grid;gap:4px}input,textarea,button{font:inherit;font-size:16px;padding:6px 10px;min-height:44px;box-sizing:border-box;color:inherit;background:var(--bg);border:1px solid var(--border);border-radius:6px}input,textarea{width:100%}textarea{min-height:5rem}button{cursor:pointer}
34 .block{border-top:1px solid var(--border);margin-top:24px;padding-top:4px}.block h2{margin:8px 0}
35 .items{list-style:none;margin:8px 0 0;padding:0}.items li{display:flex;align-items:center;gap:8px;justify-content:space-between;padding:4px 0}.items li.done span{text-decoration:line-through;color:var(--muted-fg)}
36 .items form,.pair form{display:block;margin:0}.pair{display:flex;gap:8px}.add{grid-template-columns:1fr auto}.quiet{background:none;border-color:transparent;color:var(--muted-fg)}.tick{margin:0}
37 .big{font-size:20px;font-weight:700;margin:4px 0}.note{white-space:pre-wrap;margin:12px 0}.field,.act{display:inline-block;color:var(--muted-fg)}
38 .lanes{display:grid;gap:16px;margin-top:12px}.lane h3{font-size:14px;margin:0}.spec{overflow:auto;font-size:13px}
39 .remove{margin-top:32px}button.danger{background:var(--danger);border-color:var(--danger);color:var(--bg)}`;
2340
2441 /** The worker runs wasm, fetches the module and its binary from this origin, and nothing else. */
2542 const WORKER_CSP = "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self'";
@@ -49,7 +66,7 @@ export function sqliteVendor(): Vendor {
4966
5067 export const sqliteModulePath = (): string => `/tab/v/${sqliteVendor().hash}/sqlite3.mjs`;
5168
52 type Name = "boot" | "worker" | "sw";
69 type Name = "boot" | "worker" | "sw" | "make";
5370 let building: Promise<Record<Name, BuiltAsset | null>> | null = null;
5471 /**
5572 * One of the tab's scripts, all three built once per process (the paths are literal so the tree
@@ -58,12 +75,13 @@ let building: Promise<Record<Name, BuiltAsset | null>> | null = null;
5875 export async function tabScript(name: Name): Promise<BuiltAsset | null> {
5976 building ??= (async () => {
6077 const at = (url: URL) => Bun.fileURLToPath(url);
61 const [boot, worker, sw] = await Promise.all([
78 const [boot, worker, sw, make] = await Promise.all([
6279 bundleEntry(at(new URL("../tab/boot.ts", import.meta.url)), "tab-boot", "web.tab_asset_failed"),
6380 bundleEntry(at(new URL("../tab/worker.ts", import.meta.url)), "tab-worker", "web.tab_asset_failed"),
6481 bundleEntry(at(new URL("../tab/sw.ts", import.meta.url)), "tab-sw", "web.tab_asset_failed"),
82 bundleEntry(at(new URL("../tab/make.ts", import.meta.url)), "tab-make", "web.tab_asset_failed"),
6583 ]);
66 return { boot, worker, sw };
84 return { boot, worker, sw, make };
6785 })();
6886 return (await building)[name];
6987 }
@@ -80,9 +98,11 @@ function validated(request: Request, body: string, type: string, csp: string): R
8098 /** GET /tab/:name: the worker, the service worker or the stylesheet. */
8199 export async function tabFile(request: Request, name: string): Promise<Response> {
82100 if (name === "f.css") return validated(request, STYLE, "text/css; charset=utf-8", PLAIN_CSP);
83 if (name !== "worker.js" && name !== "sw.js") return missing();
84 const built = await tabScript(name === "sw.js" ? "sw" : "worker");
85 return built === null ? unavailable() : validated(request, built.code, "text/javascript; charset=utf-8", name === "sw.js" ? PLAIN_CSP : WORKER_CSP);
101 const scripts: Record<string, Name> = { "worker.js": "worker", "sw.js": "sw", "make.js": "make" };
102 const script = Object.hasOwn(scripts, name) ? scripts[name] : undefined;
103 if (script === undefined) return missing();
104 const built = await tabScript(script);
105 return built === null ? unavailable() : validated(request, built.code, "text/javascript; charset=utf-8", name === "worker.js" ? WORKER_CSP : PLAIN_CSP);
86106 }
87107
88108 /** GET /tab/v/:hash/:file: the vendored SQLite, immutable. */
test/palette-roster.test.ts +4 −4
@@ -253,7 +253,7 @@ test("a site-admin person is offered the whole roster", () => {
253253 ["design-gallery", "Component gallery", "every component the design names"],
254254 ["domains", "Failure domains", "failure domains and their last drill"],
255255 ["feed", "Feed", "what happened, ranked; r replies on a post about an issue or pull, l likes, h who liked, p its permalink, o a run's log"],
256 ["tab-forge", "A forge in a browser tab", "where it lives, when it stops, who can reach it"],
256 ["tab-forge", "A forge in a browser tab", "where it lives, when it stops, who can reach it, make an app from a sentence"],
257257 ["feature-review", "Menu entries to review", "absorbed apps whose declared name or page changed: accept them"],
258258 ["feature-feed", "Feature feeds", "the feed items about an absorbed app, as Settings › Features shows them"],
259259 ["features", "Features", "apps that declare a feature: absorb one, change its settings"],
@@ -379,7 +379,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
379379 ["games", "Games", "game servers on your cloud: state, start, stop, restart"],
380380 ["design-gallery", "Component gallery", "every component the design names"],
381381 ["feed", "Feed", "what happened, ranked; r replies on a post about an issue or pull, l likes, h who liked, p its permalink, o a run's log"],
382 ["tab-forge", "A forge in a browser tab", "where it lives, when it stops, who can reach it"],
382 ["tab-forge", "A forge in a browser tab", "where it lives, when it stops, who can reach it, make an app from a sentence"],
383383 ["feature-feed", "Feature feeds", "the feed items about an absorbed app, as Settings › Features shows them"],
384384 ["front", "Front page", "the apps a first visitor sees, ranked; an admin pins or hides"],
385385 ["forges", "Forges you sent", "each forge sent, claimed or not, and its apps"],
@@ -507,7 +507,7 @@ test("a member person is offered the signed-in roster without the admin entries"
507507 ["origins", "Connected accounts", "the hosts your mirrors come from"],
508508 ["design-gallery", "Component gallery", "every component the design names"],
509509 ["feed", "Feed", "what happened, ranked; r replies on a post about an issue or pull, l likes, h who liked, p its permalink, o a run's log"],
510 ["tab-forge", "A forge in a browser tab", "where it lives, when it stops, who can reach it"],
510 ["tab-forge", "A forge in a browser tab", "where it lives, when it stops, who can reach it, make an app from a sentence"],
511511 ["feature-feed", "Feature feeds", "the feed items about an absorbed app, as Settings › Features shows them"],
512512 ["front", "Front page", "the apps a first visitor sees, ranked; an admin pins or hides"],
513513 ["origin-ahead", "New commits upstream", "mirrors whose origin has moved on: take them"],
@@ -575,7 +575,7 @@ test("signed out, the palette offers sign-in and the public entries", () => {
575575 ["registry-items", "Component registry", "the forge's parts; install one into an app"],
576576 ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"],
577577 ["design-gallery", "Component gallery", "every component the design names"],
578 ["tab-forge", "A forge in a browser tab", "where it lives, when it stops, who can reach it"],
578 ["tab-forge", "A forge in a browser tab", "where it lives, when it stops, who can reach it, make an app from a sentence"],
579579 ["front", "Front page", "the apps a first visitor sees, ranked; an admin pins or hides"],
580580 ["origin-ahead", "New commits upstream", "mirrors whose origin has moved on: take them"],
581581 ["security", "Security", "what the forge enforces for everyone, and how to report a problem"],
test/tab-apps.test.ts added +160
@@ -0,0 +1,160 @@
1 /**
2 * Apps in the tab (#18043): a sentence compiles to a spec, a fixed renderer draws it, and the
3 * records stay.
4 */
5 import { Database } from "bun:sqlite";
6 import { describe, expect, test } from "bun:test";
7 import { compile } from "../src/tab/compile.ts";
8 import { handle, migrate, type TabDb } from "../src/tab/forge.ts";
9 import { preview } from "../src/tab/make.ts";
10 import { renderApp } from "../src/tab/render.ts";
11 import { decodeApp } from "../src/tab/blocks.ts";
12 import { TAB_FACTS } from "../src/tab/words.ts";
13
14 const open = (): TabDb => {
15 const db = new Database(":memory:");
16 const tab: TabDb = {
17 run: (sql, bind) => void db.query(sql).run(...(bind ?? [])),
18 all: (sql, bind) => db.query(sql).all(...(bind ?? [])) as Record<string, string | number>[],
19 };
20 migrate(tab);
21 return tab;
22 };
23 const NOW = new Date(2026, 11, 4, 12).getTime();
24 const post = (db: TabDb, path: string, form: Record<string, string>) => handle(db, { method: "POST", path, form }, NOW);
25 const get = (db: TabDb, path: string) => handle(db, { method: "GET", path, form: {} }, NOW);
26
27 describe("the compiler", () => {
28 test("each sentence becomes the block kind its words ask for, with a reason", () => {
29 const kind = (s: string) => compile(s).app.blocks[0]!.kind;
30 expect(kind("track my water")).toBe("tracker");
31 expect(kind("a kanban board for my bugs")).toBe("board");
32 expect(kind("count the laps")).toBe("counter");
33 expect(kind("a journal")).toBe("notes");
34 expect(kind("shopping list")).toBe("list");
35 expect(kind("")).toBe("list");
36 const water = compile("track my water").app;
37 expect(water.blocks[0]).toMatchObject({ unit: "glasses", step: 1 });
38 expect(water.glyph).toBe("💧");
39 expect(compile("track 250 ml of water").app.blocks[0]).toMatchObject({ unit: "ml", step: 250 });
40 expect(compile("a board for bugs with columns open, fixing, shipped").app.blocks[0]).toMatchObject({ options: ["Open", "Fixing", "Shipped"], noun: "bug" });
41 expect(compile("track my water").why.length).toBeGreaterThan(2);
42 });
43
44 test("it is deterministic, bounded, and its output is a spec this reader accepts", () => {
45 const a = compile("x".repeat(5000));
46 expect(JSON.stringify(a)).toBe(JSON.stringify(compile("x".repeat(5000))));
47 expect(a.app.title.length).toBeLessThanOrEqual(40);
48 const back = decodeApp(JSON.stringify(a.app));
49 expect(back.ok && back.app).toEqual(a.app);
50 });
51 });
52
53 describe("the format", () => {
54 test("decoding is lenient, keeps an unknown kind, and refuses a newer major version in words", () => {
55 const got = decodeApp({ version: 1, title: "T", extra: 1, blocks: [{ kind: "chess", name: "c", label: "Chess", surprise: true }, 7, { kind: "" }] });
56 expect(got.ok && got.app.blocks.map((b) => b.kind)).toEqual(["chess"]);
57 const unknown = got.ok ? renderApp(got.app, { appId: 1, records: [], today: "" }) : "";
58 expect(unknown).toContain("This device cannot show a “chess” block yet.");
59 const newer = decodeApp({ version: 2, title: "T", blocks: [] });
60 expect(!newer.ok && newer.why).toContain("version 2");
61 expect(decodeApp("{nope").ok).toBe(false);
62 expect(decodeApp([]).ok).toBe(false);
63 });
64 });
65
66 describe("the preview and the stored app", () => {
67 test("the preview is the app's page with no form, and escapes the sentence", () => {
68 const html = preview("track <img src=x onerror=alert(1)> water");
69 expect(html).not.toContain("<img");
70 expect(html).not.toContain("<form");
71 expect(html).toContain("&lt;img");
72 });
73
74 test("a tracker made from a sentence keeps three entries across a reload", () => {
75 const db = open();
76 const made = post(db, "/apps", { say: "track my water" });
77 expect(made).toMatchObject({ status: 303, location: "/tab/f/apps/1" });
78 for (const n of ["1", "2", "0.5"]) expect(post(db, "/apps/1/0/tap", { n }).status).toBe(303);
79 migrate(db);
80 const page = get(db, "/apps/1").html;
81 expect(page).toContain("3.5 glasses");
82 expect(page).toContain("2026-12-04");
83 expect(get(db, "/").html).toContain("Track my water</a>");
84 const why = get(db, "/apps/1/source").html;
85 expect(why).toContain("Why each choice");
86 expect(why).toContain("&quot;kind&quot;: &quot;tracker&quot;");
87 });
88
89 test("list, notes, counter and board each keep and change their records", () => {
90 const db = open();
91 post(db, "/apps", { say: "shopping list" });
92 post(db, "/apps/1/0/add", { text: "milk <b>" });
93 expect(get(db, "/apps/1").html).toContain("milk &lt;b&gt;");
94 post(db, "/apps/1/0/toggle", { id: "1" });
95 expect(get(db, "/apps/1").html).toContain('class="done"');
96 post(db, "/apps/1/0/del", { id: "1" });
97 expect(get(db, "/apps/1").html).toContain("Nothing here yet");
98 post(db, "/apps", { say: "my journal" });
99 post(db, "/apps/2/0/add", { text: "first" });
100 post(db, "/apps/2/0/add", { text: "second" });
101 expect(get(db, "/apps/2").html.indexOf("second")).toBeLessThan(get(db, "/apps/2").html.indexOf("first"));
102 post(db, "/apps", { say: "count laps" });
103 post(db, "/apps/3/0/tap", { n: "1" });
104 post(db, "/apps/3/0/tap", { n: "1" });
105 expect(get(db, "/apps/3").html).toContain('aria-live="polite">2<');
106 post(db, "/apps", { say: "a board for tasks" });
107 post(db, "/apps/4/0/add", { text: "write" });
108 post(db, "/apps/4/0/move", { id: "5", to: "1" });
109 expect(post(db, "/apps/4/0/move", { id: "5", to: "9" }).status).toBe(422);
110 expect(get(db, "/apps/4").html).toMatch(/Doing <span class="muted">1<\/span>/);
111 });
112
113 test("bad input is refused, other apps' records are untouchable, and an app can be removed", () => {
114 const db = open();
115 expect(post(db, "/apps", { say: " " }).status).toBe(422);
116 expect(post(db, "/apps", { say: "x".repeat(301) }).status).toBe(422);
117 post(db, "/apps", { say: "shopping list" });
118 post(db, "/apps", { say: "my journal" });
119 post(db, "/apps/1/0/add", { text: "a" });
120 post(db, "/apps/2/0/del", { id: "1" });
121 expect(get(db, "/apps/1").html).toContain("<span>a</span>");
122 expect(post(db, "/apps/1/0/tap", { n: "abc" }).status).toBe(404);
123 expect(post(db, "/apps/1/9/add", { text: "a" }).status).toBe(404);
124 expect(get(db, "/apps/1; DROP").status).toBe(404);
125 expect(get(db, "/apps/99").status).toBe(404);
126 expect(handle(db, { method: "DELETE", path: "/apps/1", form: {} }, NOW).status).toBe(405);
127 const refused = post(db, "/apps/1/delete", { confirm: "wrong" });
128 expect(refused.status).toBe(422);
129 expect(get(db, "/apps/1").status).toBe(200);
130 expect(post(db, "/apps/1/delete", {}).status).toBe(422);
131 expect(get(db, "/apps/1").html).toContain('name="confirm"');
132 expect(post(db, "/apps/1/delete", { confirm: String(db.all("SELECT title FROM made WHERE id = 1")[0]!.title) }).location).toBe("/tab/f/");
133 expect(get(db, "/apps/1").status).toBe(404);
134 expect(db.all("SELECT count(*) AS n FROM rec WHERE app = 1")[0]!.n).toBe(0);
135 });
136
137 test("the compiler is not in the page's script, and the page says what holds", async () => {
138 const boot = await Bun.file(`${import.meta.dir}/../src/tab/boot.ts`).text();
139 expect(boot).not.toContain("compile.ts");
140 expect(boot).toContain("make.dataset.make");
141 expect(TAB_FACTS.join(" ")).toContain("gone if this site's data is cleared");
142 });
143
144 test("an app whose spec cannot be read is listed, says so, and can be removed by its title", () => {
145 const db = open();
146 db.run("INSERT INTO made (title, spec, why, created) VALUES ('Broken', '{nope', '[]', 1)");
147 expect(get(db, "/").html).toContain("cannot be drawn");
148 const page = get(db, "/apps/1");
149 expect(page.status).toBe(200);
150 expect(page.html).toContain("cannot be read");
151 expect(post(db, "/apps/1/delete", { confirm: "Broken" }).status).toBe(303);
152 expect(get(db, "/apps/1").status).toBe(404);
153 });
154
155 test("/tab's script stays under its size budget", async () => {
156 const { tabScript } = await import("../src/web/tab-asset.ts");
157 const built = await tabScript("boot");
158 expect(Buffer.byteLength(built!.code)).toBeLessThan(4096);
159 });
160 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs