sayshape-mcp 0.2.1 → 0.2.2

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/dist/server.js CHANGED
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { readFile } from "node:fs/promises";
2
+ import { mkdir, stat as stat$1, utimes, writeFile, rename, readdir, unlink, readFile, access } from "node:fs/promises";
3
+ import { constants } from "node:fs";
3
4
  import { fileURLToPath } from "node:url";
4
- import { basename } from "node:path";
5
+ import { resolve, join, basename } from "node:path";
5
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
7
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
8
  import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE, getUiCapability } from "@modelcontextprotocol/ext-apps/server";
8
9
  import { z } from "zod";
9
10
  import { createRequire } from "node:module";
11
+ import { createHash } from "node:crypto";
10
12
  import { createServer as createServer$1 } from "node:http";
11
13
  import { isIP } from "node:net";
12
14
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
@@ -18,7 +20,14 @@ const base = {
18
20
  mono: '"IBM Plex Mono", ui-monospace, Menlo, Consolas, monospace'
19
21
  },
20
22
  text: { caption: 12, body: 14, lead: 16, title: 20, display: 30 },
21
- control: { height: 40 }
23
+ control: { height: 40 },
24
+ slide: {
25
+ space: { xs: 6, sm: 12, md: 22, lg: 34, xl: 48 },
26
+ radius: { sm: 10, md: 12, lg: 18 },
27
+ text: { caption: 18, body: 24, lead: 28, title: 34, display: 52 },
28
+ control: { height: 56 },
29
+ heading: { cover: 64, slide: 44 }
30
+ }
22
31
  };
23
32
  const lightTheme = {
24
33
  name: "light",
@@ -90,7 +99,14 @@ const studioBase = {
90
99
  mono: '"IBM Plex Mono", ui-monospace, Menlo, Consolas, monospace'
91
100
  },
92
101
  text: { caption: 12, body: 14, lead: 16, title: 20, display: 32 },
93
- control: { height: 40 }
102
+ control: { height: 40 },
103
+ slide: {
104
+ space: { xs: 6, sm: 12, md: 22, lg: 36, xl: 48 },
105
+ radius: { sm: 12, md: 14, lg: 22 },
106
+ text: { caption: 18, body: 24, lead: 28, title: 34, display: 54 },
107
+ control: { height: 56 },
108
+ heading: { cover: 66, slide: 44 }
109
+ }
94
110
  };
95
111
  const studioLightTheme = {
96
112
  name: "studio-light",
@@ -348,6 +364,7 @@ function parseViewArgs(args) {
348
364
  if (args.includes("--no-copy-text")) out.copyText = false;
349
365
  if (args.includes("--scene")) out.scene = true;
350
366
  if (args.includes("--behavior")) out.behavior = true;
367
+ if (args.includes("--slides")) out.slides = true;
351
368
  const at2 = args.indexOf("--theme");
352
369
  if (at2 >= 0) {
353
370
  const name2 = args[at2 + 1];
@@ -370,8 +387,28 @@ function parseViewArgs(args) {
370
387
  }
371
388
  out.imageHosts = hosts;
372
389
  }
390
+ const logoAt = args.indexOf("--logo");
391
+ if (logoAt >= 0) {
392
+ const raw = args[logoAt + 1];
393
+ const logo = raw && !raw.startsWith("--") ? logoAddress(raw) : null;
394
+ if (!logo) throw new Error(`--logo needs the https address of an image, such as https://cdn.example.com/logo.png${raw && !raw.startsWith("--") ? `; got "${raw}"` : ""}.`);
395
+ const host = new URL(logo).hostname;
396
+ const hosts = [.../* @__PURE__ */ new Set([...out.imageHosts ?? [], host])];
397
+ if (hosts.length > MAX_IMAGE_HOSTS) throw new Error(`--logo's host, ${host}, would be one more than the ${MAX_IMAGE_HOSTS} hosts --image-hosts allows.`);
398
+ out.logo = logo;
399
+ out.imageHosts = hosts;
400
+ }
373
401
  return out;
374
402
  }
403
+ function logoAddress(raw) {
404
+ try {
405
+ const u = new URL(raw);
406
+ if (u.protocol !== "https:" || u.username || u.password || !HOST.test(u.hostname) || u.hostname.includes("*")) return null;
407
+ return u.href.length <= 500 ? u.href : null;
408
+ } catch {
409
+ return null;
410
+ }
411
+ }
375
412
  function accentNotes(o) {
376
413
  if (!o.accent) return [];
377
414
  const modes = ["light", "dark"].map((scheme) => {
@@ -383,7 +420,7 @@ function accentNotes(o) {
383
420
  function encodeViewOptions(o) {
384
421
  const images = o.imageHosts?.length ? `&images=${o.imageHosts.join(",")}` : "";
385
422
  const accent = o.accent ? `&accent=${o.accent.slice(1)}` : "";
386
- return `picker=${o.themePicker ? 1 : 0}&theme=${o.theme}${accent}&save=${o.saveImage ? 1 : 0}&copy=${o.copyText ? 1 : 0}${o.scene ? "&scene=1" : ""}${o.behavior ? "&behavior=1" : ""}${images}`;
423
+ return `picker=${o.themePicker ? 1 : 0}&theme=${o.theme}${accent}&save=${o.saveImage ? 1 : 0}&copy=${o.copyText ? 1 : 0}${o.scene ? "&scene=1" : ""}${o.behavior ? "&behavior=1" : ""}${o.slides ? "&slides=1" : ""}${o.logo ? `&logo=${encodeURIComponent(o.logo)}` : ""}${images}`;
387
424
  }
388
425
  function withViewOptions(html, o) {
389
426
  const tag = `<meta name="${META}" content="${encodeViewOptions(o)}">`;
@@ -395,17 +432,17 @@ const MAX_DATA_VALUES = 1e4;
395
432
  const MAX_HOST_VALUES = 1e6;
396
433
  class DataError extends Error {
397
434
  }
398
- const made = /* @__PURE__ */ new WeakSet();
435
+ const made$2 = /* @__PURE__ */ new WeakSet();
399
436
  function record(entries) {
400
437
  const r = /* @__PURE__ */ Object.create(null);
401
438
  for (const [k2, v] of entries) r[k2] = v;
402
439
  Object.freeze(r);
403
- made.add(r);
440
+ made$2.add(r);
404
441
  return r;
405
442
  }
406
443
  function list$2(items) {
407
444
  Object.freeze(items);
408
- made.add(items);
445
+ made$2.add(items);
409
446
  return items;
410
447
  }
411
448
  function isList(v) {
@@ -415,7 +452,7 @@ function isRecord(v) {
415
452
  return typeof v === "object" && v !== null && !Array.isArray(v);
416
453
  }
417
454
  function isData(v) {
418
- return isScalar(v) || typeof v === "object" && v !== null && made.has(v);
455
+ return isScalar(v) || typeof v === "object" && v !== null && made$2.has(v);
419
456
  }
420
457
  function toNumber(v) {
421
458
  if (typeof v === "number") return v;
@@ -430,7 +467,7 @@ function toData(v) {
430
467
  if (typeof v === "number" && !Number.isFinite(v)) throw new DataError(`${v} isn't a usable number`);
431
468
  return v;
432
469
  }
433
- if (typeof v === "object" && v !== null && made.has(v)) return v;
470
+ if (typeof v === "object" && v !== null && made$2.has(v)) return v;
434
471
  let count = 0;
435
472
  const seen = /* @__PURE__ */ new Set();
436
473
  const copy = (x, depth, where) => {
@@ -440,7 +477,7 @@ function toData(v) {
440
477
  return x;
441
478
  }
442
479
  if (typeof x !== "object" || x === null) throw new DataError(`${where} is a ${typeof x}; only numbers, text, true/false, null, lists and records can be data`);
443
- if (made.has(x)) return x;
480
+ if (made$2.has(x)) return x;
444
481
  if (depth >= MAX_DATA_DEPTH) throw new DataError(`${where} is nested more than ${MAX_DATA_DEPTH} levels deep`);
445
482
  if (seen.has(x)) throw new DataError(`${where} refers back to itself`);
446
483
  seen.add(x);
@@ -579,7 +616,7 @@ function readField(v, key) {
579
616
  return { error: `Text only has a length, not "${String(key)}"` };
580
617
  }
581
618
  if (isRecord(v)) {
582
- if (typeof key === "string" && made.has(v) && Object.prototype.hasOwnProperty.call(v, key)) return { value: v[key] };
619
+ if (typeof key === "string" && made$2.has(v) && Object.prototype.hasOwnProperty.call(v, key)) return { value: v[key] };
583
620
  return { error: `No field "${String(key)}"` };
584
621
  }
585
622
  return { error: `${v === null ? "null" : typeof v} has no "${String(key)}"` };
@@ -1134,7 +1171,7 @@ function run(n2, scope) {
1134
1171
  }
1135
1172
  throw new ExprError("Bad expression");
1136
1173
  }
1137
- const cache = /* @__PURE__ */ new Map();
1174
+ const cache$1 = /* @__PURE__ */ new Map();
1138
1175
  const extraCaches = /* @__PURE__ */ new WeakMap();
1139
1176
  const hasArrow = (src) => /=>/.test(src.replace(/'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g, ""));
1140
1177
  const NO_ARROWS = "SayShape has no arrow functions (x => …): list functions take a field name and a value instead, like filter(list, 'priority', 'High'), count(list, 'done') or sort(list, 'price', 'desc')";
@@ -1144,7 +1181,7 @@ function quotedTemplate(src) {
1144
1181
  return m && /\{[^{}]*\}/.test(m[2]) ? m[2] : null;
1145
1182
  }
1146
1183
  function compile(src, fns) {
1147
- let store = cache;
1184
+ let store = cache$1;
1148
1185
  if (fns) {
1149
1186
  let own = extraCaches.get(fns);
1150
1187
  if (!own) extraCaches.set(fns, own = /* @__PURE__ */ new Map());
@@ -1291,7 +1328,7 @@ function bareExpression(raw) {
1291
1328
  }
1292
1329
  const stateLocate = (name2) => ({ key: name2, steps: [] });
1293
1330
  const PATH = /^[A-Za-z_]\w*(\.[A-Za-z_]\w*)*$/;
1294
- function placeOf(path2, locate2) {
1331
+ function placeOf$1(path2, locate2) {
1295
1332
  if (!PATH.test(path2)) return null;
1296
1333
  const [first2, ...rest] = path2.split(".");
1297
1334
  const base2 = locate2(first2);
@@ -1557,24 +1594,24 @@ function defOf(type, registry2) {
1557
1594
  return type === "if" ? IF_BLOCK : registry2.get(type);
1558
1595
  }
1559
1596
  const MAX_DERIVED = 200;
1560
- function tokenizeLine(body) {
1597
+ function tokenizeLine(body2) {
1561
1598
  const out = { type: "", props: /* @__PURE__ */ Object.create(null), quoted: /* @__PURE__ */ new Set(), problems: [] };
1562
1599
  let i = 0;
1563
- const n2 = body.length;
1600
+ const n2 = body2.length;
1564
1601
  const skipWs = () => {
1565
- while (i < n2 && /\s/.test(body[i])) i++;
1602
+ while (i < n2 && /\s/.test(body2[i])) i++;
1566
1603
  };
1567
1604
  const readQuoted = () => {
1568
- const q = body[i];
1605
+ const q = body2[i];
1569
1606
  let j = i + 1, s = "";
1570
- while (j < n2 && body[j] !== q) {
1571
- if (body[j] === "\\" && j + 1 < n2) {
1607
+ while (j < n2 && body2[j] !== q) {
1608
+ if (body2[j] === "\\" && j + 1 < n2) {
1572
1609
  j++;
1573
- s += body[j];
1610
+ s += body2[j];
1574
1611
  j++;
1575
1612
  continue;
1576
1613
  }
1577
- s += body[j];
1614
+ s += body2[j];
1578
1615
  j++;
1579
1616
  }
1580
1617
  if (j >= n2) return null;
@@ -1584,7 +1621,7 @@ function tokenizeLine(body) {
1584
1621
  const readGroup = () => {
1585
1622
  let depth = 0, j = i, quote2 = "";
1586
1623
  for (; j < n2; j++) {
1587
- const c2 = body[j];
1624
+ const c2 = body2[j];
1588
1625
  if (quote2) {
1589
1626
  if (c2 === "\\") j++;
1590
1627
  else if (c2 === quote2) quote2 = "";
@@ -1595,30 +1632,30 @@ function tokenizeLine(body) {
1595
1632
  else if ((c2 === "}" || c2 === "]") && --depth === 0) break;
1596
1633
  }
1597
1634
  if (depth !== 0 || j >= n2) return null;
1598
- const s = body.slice(i, j + 1);
1635
+ const s = body2.slice(i, j + 1);
1599
1636
  i = j + 1;
1600
1637
  return s;
1601
1638
  };
1602
1639
  const readBare = () => {
1603
1640
  let s = "";
1604
- while (i < n2 && !/\s/.test(body[i])) {
1605
- if (body[i] === "{" || body[i] === "[") {
1641
+ while (i < n2 && !/\s/.test(body2[i])) {
1642
+ if (body2[i] === "{" || body2[i] === "[") {
1606
1643
  const b = readGroup();
1607
1644
  if (b === null) {
1608
- s += body.slice(i);
1645
+ s += body2.slice(i);
1609
1646
  i = n2;
1610
1647
  break;
1611
1648
  }
1612
1649
  s += b;
1613
1650
  } else {
1614
- s += body[i];
1651
+ s += body2[i];
1615
1652
  i++;
1616
1653
  }
1617
1654
  }
1618
1655
  return s;
1619
1656
  };
1620
1657
  skipWs();
1621
- const m = /^[A-Za-z][\w-]*/.exec(body.slice(i));
1658
+ const m = /^[A-Za-z][\w-]*/.exec(body2.slice(i));
1622
1659
  if (!m) {
1623
1660
  out.problems.push(`Expected an element name at the start of the line`);
1624
1661
  return out;
@@ -1628,7 +1665,7 @@ function tokenizeLine(body) {
1628
1665
  while (i < n2) {
1629
1666
  skipWs();
1630
1667
  if (i >= n2) break;
1631
- const c2 = body[i];
1668
+ const c2 = body2[i];
1632
1669
  if (c2 === '"' || c2 === "'") {
1633
1670
  const s = readQuoted();
1634
1671
  if (s === null) {
@@ -1639,17 +1676,17 @@ function tokenizeLine(body) {
1639
1676
  else out.problems.push(`Extra text "${s}" ignored; an element takes one quoted text`);
1640
1677
  continue;
1641
1678
  }
1642
- const key = /^[A-Za-z_][\w-]*(?==)/.exec(body.slice(i));
1679
+ const key = /^[A-Za-z_][\w-]*(?==)/.exec(body2.slice(i));
1643
1680
  if (key) {
1644
1681
  i += key[0].length + 1;
1645
1682
  const start = i;
1646
1683
  let v;
1647
- const quoted = body[i] === '"' || body[i] === "'";
1684
+ const quoted = body2[i] === '"' || body2[i] === "'";
1648
1685
  if (quoted) v = readQuoted();
1649
- else if (body[i] === "{" || body[i] === "[") v = readGroup() ?? null;
1686
+ else if (body2[i] === "{" || body2[i] === "[") v = readGroup() ?? null;
1650
1687
  else v = readBare();
1651
1688
  if (v === null) {
1652
- const what = body[start] === "[" ? `its "[" isn't closed with "]"` : body[start] === "{" ? `its "{" isn't closed with "}"` : "its quote isn't closed";
1689
+ const what = body2[start] === "[" ? `its "[" isn't closed with "]"` : body2[start] === "{" ? `its "{" isn't closed with "}"` : "its quote isn't closed";
1653
1690
  out.problems.push(`Unclosed value for "${key[0]}": ${what} on this line`);
1654
1691
  break;
1655
1692
  }
@@ -1664,8 +1701,8 @@ function tokenizeLine(body) {
1664
1701
  }
1665
1702
  return out;
1666
1703
  }
1667
- function parseStateLine(body, line2, diags, skipped) {
1668
- const t2 = tokenizeLine("state " + body);
1704
+ function parseStateLine(body2, line2, diags, skipped) {
1705
+ const t2 = tokenizeLine("state " + body2);
1669
1706
  for (const p of t2.problems) {
1670
1707
  diags.push({ line: line2, severity: "warning", message: p });
1671
1708
  const unclosed = /^Unclosed value for "([^"]+)"/.exec(p);
@@ -1704,12 +1741,12 @@ function dragProblems(props, fixed) {
1704
1741
  return out;
1705
1742
  }
1706
1743
  const RULE_PROPS = /* @__PURE__ */ new Set(["if", "do", "on"]);
1707
- function parseRuleLine(body, line2, diags) {
1744
+ function parseRuleLine(body2, line2, diags) {
1708
1745
  const skip = (message) => {
1709
1746
  diags.push({ line: line2, severity: "error", message: `${message}. This rule was skipped` });
1710
1747
  return null;
1711
1748
  };
1712
- const m = /^every\s+(\d+(?:\.\d+)?|\.\d+)\s*(ms|s)(?=\s|$)(.*)$/.exec(body);
1749
+ const m = /^every\s+(\d+(?:\.\d+)?|\.\d+)\s*(ms|s)(?=\s|$)(.*)$/.exec(body2);
1713
1750
  if (!m) return skip("A rule starts with every and how often, like every 1s or every 250ms, then if={…} and do=…");
1714
1751
  const every = Number(m[1]) * (m[2] === "s" ? 1e3 : 1);
1715
1752
  if (!(every > 0)) return skip("A rule's interval must be more than 0, like every 1s");
@@ -1756,8 +1793,8 @@ function checkRules(rules, controls, dialogs, diags) {
1756
1793
  }
1757
1794
  return kept;
1758
1795
  }
1759
- function parseDeriveLine(body, line2, diags) {
1760
- const bare = /^([A-Za-z_]\w*)\s*=\s*(?!\{)(\S.*)$/.exec(body.trim());
1796
+ function parseDeriveLine(body2, line2, diags) {
1797
+ const bare = /^([A-Za-z_]\w*)\s*=\s*(?!\{)(\S.*)$/.exec(body2.trim());
1761
1798
  if (bare && !RESERVED.has(bare[1]) && (checkSyntax(bare[2].trim()) !== null || identifiers(bare[2].trim()).length > 0)) {
1762
1799
  const expr = bare[2].trim();
1763
1800
  const err = checkSyntax(expr);
@@ -1767,7 +1804,7 @@ function parseDeriveLine(body, line2, diags) {
1767
1804
  return [];
1768
1805
  }
1769
1806
  }
1770
- const t2 = tokenizeLine("derive " + body);
1807
+ const t2 = tokenizeLine("derive " + body2);
1771
1808
  for (const p of t2.problems) diags.push({ line: line2, severity: "warning", message: p });
1772
1809
  if (t2.text !== void 0) diags.push({ line: line2, severity: "warning", message: `derive lines take name={expression} pairs, not quoted text, like derive total={price * qty}` });
1773
1810
  const out = [];
@@ -1864,19 +1901,19 @@ const CODE_WORDS = {
1864
1901
  document: "SayShape can't run code. Write only SayShape lines: elements, state and derive",
1865
1902
  window: "SayShape can't run code. Write only SayShape lines: elements, state and derive"
1866
1903
  };
1867
- function isClosingLine(body) {
1868
- if (!/^[}\])]/.test(body)) return false;
1869
- return /^(?:\s*else\b.*)?$/.test(body.slice(1).replace(/^\s*[,;)\]}]*/, ""));
1904
+ function isClosingLine(body2) {
1905
+ if (!/^[}\])]/.test(body2)) return false;
1906
+ return /^(?:\s*else\b.*)?$/.test(body2.slice(1).replace(/^\s*[,;)\]}]*/, ""));
1870
1907
  }
1871
- function isSentence(body) {
1872
- return /^[A-Z][a-z]*\s+\w+\s+\w/.test(body) && /^[\s\w,.:;'!?-]*$/.test(body);
1908
+ function isSentence(body2) {
1909
+ return /^[A-Z][a-z]*\s+\w+\s+\w/.test(body2) && /^[\s\w,.:;'!?-]*$/.test(body2);
1873
1910
  }
1874
- function codeLineMessage(body) {
1875
- if (/^(\/\/|\/\*|\*\/|--\s)/.test(body)) return "Comments start with #, like # Totals";
1876
- if (isClosingLine(body)) return "SayShape has no braces around blocks: the lines under an if= or each line are indented under it instead, and nothing closes it";
1877
- const word = /^([A-Za-z_]\w*)/.exec(body)?.[1];
1911
+ function codeLineMessage(body2) {
1912
+ if (/^(\/\/|\/\*|\*\/|--\s)/.test(body2)) return "Comments start with #, like # Totals";
1913
+ if (isClosingLine(body2)) return "SayShape has no braces around blocks: the lines under an if= or each line are indented under it instead, and nothing closes it";
1914
+ const word = /^([A-Za-z_]\w*)/.exec(body2)?.[1];
1878
1915
  if (word && Object.prototype.hasOwnProperty.call(CODE_WORDS, word)) return CODE_WORDS[word];
1879
- if (isSentence(body)) {
1916
+ if (isSentence(body2)) {
1880
1917
  return "Only SayShape lines go in a spec. Leave explanations out, or start them with # as comments";
1881
1918
  }
1882
1919
  return void 0;
@@ -1979,19 +2016,19 @@ function parse(src, registry2, opts = {}) {
1979
2016
  lines.forEach((raw, idx) => {
1980
2017
  const lineNo = idx + 1;
1981
2018
  const expanded = raw.replace(/\t/g, " ");
1982
- const body = expanded.trim();
1983
- if (!body || body.startsWith("#")) return;
2019
+ const body2 = expanded.trim();
2020
+ if (!body2 || body2.startsWith("#")) return;
1984
2021
  const indent2 = expanded.length - expanded.trimStart().length;
1985
2022
  if (skipDeeperThan !== null) {
1986
2023
  if (indent2 > skipDeeperThan) return;
1987
2024
  skipDeeperThan = null;
1988
2025
  }
1989
- if (opts.behavior && /^every(\s|$)/.test(body)) {
2026
+ if (opts.behavior && /^every(\s|$)/.test(body2)) {
1990
2027
  if (indent2 > 0 && stack2.some((n2) => n2.type === "each" && n2.indent < indent2)) {
1991
2028
  diagnostics.push({ line: lineNo, severity: "warning", message: `Rules can't go inside each: a rule belongs to the whole screen, not one item, so this one was skipped. Write it unindented, at the top` });
1992
2029
  return;
1993
2030
  }
1994
- const rule = parseRuleLine(body, lineNo, diagnostics);
2031
+ const rule = parseRuleLine(body2, lineNo, diagnostics);
1995
2032
  if (rule) {
1996
2033
  rules.push(rule);
1997
2034
  for (const n2 of actionTargets(rule.actions)) {
@@ -2004,7 +2041,7 @@ function parse(src, registry2, opts = {}) {
2004
2041
  }
2005
2042
  return;
2006
2043
  }
2007
- if (/^derive(\s|$)/.test(body)) {
2044
+ if (/^derive(\s|$)/.test(body2)) {
2008
2045
  if (indent2 > 0) {
2009
2046
  if (stack2.some((n2) => n2.type === "each" && n2.indent < indent2)) {
2010
2047
  diagnostics.push({ line: lineNo, severity: "warning", message: `derive lines can't go inside each: a derived value is one for the whole screen, not one per item, so this one was skipped. Work it out in the text that shows it, like {item.price * item.qty}` });
@@ -2012,27 +2049,27 @@ function parse(src, registry2, opts = {}) {
2012
2049
  return;
2013
2050
  }
2014
2051
  }
2015
- derivedLines.push(...parseDeriveLine(body.slice(6), lineNo, diagnostics));
2052
+ derivedLines.push(...parseDeriveLine(body2.slice(6), lineNo, diagnostics));
2016
2053
  return;
2017
2054
  }
2018
- if (/^state(\s|$)/.test(body)) {
2019
- state.push(...parseStateLine(body.slice(5), lineNo, diagnostics, skippedState));
2020
- openState = openBrackets(body) > 0 ? { line: lineNo, reported: false } : null;
2055
+ if (/^state(\s|$)/.test(body2)) {
2056
+ state.push(...parseStateLine(body2.slice(5), lineNo, diagnostics, skippedState));
2057
+ openState = openBrackets(body2) > 0 ? { line: lineNo, reported: false } : null;
2021
2058
  return;
2022
2059
  }
2023
- const early = /^([}\])]|\/\/|\/\*|\*\/|--\s)/.test(body) ? codeLineMessage(body) : /^if\s*\(/.test(body) ? "Write a line holding only if={…}, like if={count > 0}, and indent the lines it shows under it" : void 0;
2060
+ const early = /^([}\])]|\/\/|\/\*|\*\/|--\s)/.test(body2) ? codeLineMessage(body2) : /^if\s*\(/.test(body2) ? "Write a line holding only if={…}, like if={count > 0}, and indent the lines it shows under it" : void 0;
2024
2061
  if (early && !openState) {
2025
2062
  diagnostics.push({ line: lineNo, severity: "error", message: `${early}. This line and anything under it were skipped` });
2026
2063
  skipDeeperThan = indent2;
2027
2064
  return;
2028
2065
  }
2029
- if (/^[{<]/.test(body) && !openState) {
2066
+ if (/^[{<]/.test(body2) && !openState) {
2030
2067
  diagnostics.push({ line: lineNo, severity: "warning", message: `Lines start with an element name. SayShape has no JSX or code; to repeat elements for each item, use each items=list as=x and put the elements under it` });
2031
2068
  skipDeeperThan = indent2;
2032
2069
  return;
2033
2070
  }
2034
- const elseLine = /^else(\s+if=(.*))?$/.exec(body);
2035
- let line2 = body;
2071
+ const elseLine = /^else(\s+if=(.*))?$/.exec(body2);
2072
+ let line2 = body2;
2036
2073
  if (elseLine && !openState) {
2037
2074
  let p = stack2.length - 1;
2038
2075
  while (p > 0 && stack2[p].indent >= indent2) p--;
@@ -2053,11 +2090,11 @@ function parse(src, registry2, opts = {}) {
2053
2090
  line2 = `if if={${cond}}`;
2054
2091
  pendingChain = own === void 0 ? null : [...before, own];
2055
2092
  }
2056
- const loneProp = elseLine ? null : /^([A-Za-z_][\w-]*)=/.exec(body);
2093
+ const loneProp = elseLine ? null : /^([A-Za-z_][\w-]*)=/.exec(body2);
2057
2094
  if (loneProp && !openState) {
2058
- const block = tokenizeLine(`if ${body}`);
2095
+ const block = tokenizeLine(`if ${body2}`);
2059
2096
  if (loneProp[1] === "if" && !block.problems.length && block.text === void 0 && Object.keys(block.props).join() === "if") {
2060
- line2 = `if ${body}`;
2097
+ line2 = `if ${body2}`;
2061
2098
  } else {
2062
2099
  const name2 = loneProp[1];
2063
2100
  if (name2 === "elif" || name2 === "elseif") {
@@ -2084,7 +2121,7 @@ function parse(src, registry2, opts = {}) {
2084
2121
  skipDeeperThan = indent2;
2085
2122
  return;
2086
2123
  }
2087
- const code2 = tok.type && !defOf(tok.type, registry2) ? codeLineMessage(body) : void 0;
2124
+ const code2 = tok.type && !defOf(tok.type, registry2) ? codeLineMessage(body2) : void 0;
2088
2125
  if (code2) {
2089
2126
  diagnostics.push({ line: lineNo, severity: "error", message: `${code2}. This line and anything under it were skipped` });
2090
2127
  skipDeeperThan = indent2;
@@ -3025,10 +3062,10 @@ function paintPremiumBar(ctx, rect2, color2, _direction, hover = 0) {
3025
3062
  g.restore();
3026
3063
  }
3027
3064
  }
3028
- function barPath(g, x, y, w2, h2, r, up) {
3065
+ function barPath(g, x, y, w2, h2, r, up2) {
3029
3066
  const rr = Math.max(0, Math.min(r, w2 / 2, h2));
3030
3067
  g.beginPath();
3031
- if (up) {
3068
+ if (up2) {
3032
3069
  g.moveTo(x, y + h2);
3033
3070
  g.lineTo(x, y + rr);
3034
3071
  g.arcTo(x, y, x + rr, y, rr);
@@ -3420,9 +3457,9 @@ function paintLayers(ctx, d, ox, oy, colorAt, reveal) {
3420
3457
  for (const r of L.rules) {
3421
3458
  const y = oy + r.y;
3422
3459
  const w2 = g.measureText(r.text).width + padX * 2;
3423
- const up = y - 3 - plateH, down = y + 3;
3460
+ const up2 = y - 3 - plateH, down = y + 3;
3424
3461
  const fits = (py2) => py2 >= top && py2 + plateH <= bottom;
3425
- const spots = [[right - w2, up], [right - w2, down], [left, up], [left, down]];
3462
+ const spots = [[right - w2, up2], [right - w2, down], [left, up2], [left, down]];
3426
3463
  const [px, py] = spots.find(([sx, sy]) => fits(sy) && !covers2(sx, sy, w2)) ?? spots.find(([, sy]) => fits(sy)) ?? spots[0];
3427
3464
  g.beginPath();
3428
3465
  ctx.roundRect(px, py, w2, plateH, theme.radius.sm / 2);
@@ -5035,7 +5072,7 @@ stat label="Total" value="\${price*qty}"`,
5035
5072
  },
5036
5073
  layout(box, ctx) {
5037
5074
  const p = ctx.props(box.node);
5038
- const d = statLayout(p.str("label"), p.str("value"), box.w, ctx.theme, ctx.measure);
5075
+ const d = statLayout(p.str("label"), p.str("value"), box.w, ctx.theme, ctx.measure, statHint.get(box.node));
5039
5076
  if (!p.has("change") && !p.has("spark") && !p.has("trend")) {
5040
5077
  box.data = { ...d };
5041
5078
  box.h = d.height;
@@ -5132,12 +5169,47 @@ function statSizes(theme) {
5132
5169
  const top = Math.min(STAT_SIZES[0], theme.text.display);
5133
5170
  return [top, ...STAT_SIZES.filter((s) => s < top)];
5134
5171
  }
5172
+ const statHint = /* @__PURE__ */ new WeakMap();
5173
+ const statZoom = (t2) => t2.zoom !== void 0 && t2.zoom > 1 ? t2.zoom : 1;
5174
+ {
5175
+ const layoutAt = stat.layout, paintAt = stat.paint, loadingAt = stat.paintLoading, minAt = stat.minWidth;
5176
+ stat.layout = (box, ctx) => {
5177
+ const z2 = statZoom(ctx.theme);
5178
+ if (z2 === 1 || !layoutAt) {
5179
+ layoutAt?.(box, ctx);
5180
+ return;
5181
+ }
5182
+ const inner = { ...box, w: box.w / z2 };
5183
+ layoutAt(inner, ctx);
5184
+ box.data = inner.data;
5185
+ box.h = inner.h * z2;
5186
+ };
5187
+ const zoomed = (draw) => draw && ((box, ctx) => {
5188
+ const z2 = statZoom(ctx.theme);
5189
+ if (z2 === 1) {
5190
+ draw(box, ctx);
5191
+ return;
5192
+ }
5193
+ const g = ctx.g;
5194
+ g.save();
5195
+ g.translate(box.x, box.y);
5196
+ g.scale(z2, z2);
5197
+ g.translate(-box.x, -box.y);
5198
+ draw({ ...box, w: box.w / z2, h: box.h / z2 }, ctx);
5199
+ g.restore();
5200
+ });
5201
+ stat.paint = zoomed(paintAt);
5202
+ stat.paintLoading = zoomed(loadingAt);
5203
+ if (typeof minAt === "function") stat.minWidth = (node, ctx) => minAt(node, ctx) * statZoom(ctx.theme);
5204
+ }
5135
5205
  const STAT_WEIGHT = 600;
5136
5206
  const STAT_LABEL = 13, STAT_LABEL_LH = 17;
5137
- function statLayout(label2, value, width, theme, m) {
5207
+ function statLayout(label2, value, width, theme, m, like) {
5138
5208
  const w2 = Math.max(20, width);
5139
5209
  const labelLines2 = label2 ? fitLines(label2, w2, themeFont(theme, 400, STAT_LABEL), m, 2) : [];
5140
- const sizes = statSizes(theme);
5210
+ const all = statSizes(theme);
5211
+ const capped = like?.size ? all.filter((s) => s <= like.size) : all;
5212
+ const sizes = capped.length ? capped : [all[all.length - 1]];
5141
5213
  let size = sizes[sizes.length - 1];
5142
5214
  let lines = null;
5143
5215
  for (const s of sizes) {
@@ -5149,7 +5221,7 @@ function statLayout(label2, value, width, theme, m) {
5149
5221
  }
5150
5222
  lines ??= fitLines(value, w2, themeFont(theme, STAT_WEIGHT, size), m, 3);
5151
5223
  const valueLH = Math.round(size * 1.3);
5152
- const valueTop = 12 + Math.max(0, labelLines2.length - 1) * STAT_LABEL_LH;
5224
+ const valueTop = 12 + Math.max(0, Math.max(labelLines2.length, like?.labelLines ?? 0) - 1) * STAT_LABEL_LH;
5153
5225
  return { label: labelLines2, value: lines, size, valueLH, valueTop, height: valueTop + lines.length * valueLH + 6 };
5154
5226
  }
5155
5227
  const STAT_CHANGE_GAP = 8;
@@ -5164,7 +5236,32 @@ function changeDirection(text2) {
5164
5236
  if (!m) return null;
5165
5237
  const n2 = Number(m[2].replace(/,/g, ""));
5166
5238
  if (!Number.isFinite(n2) || n2 === 0) return "flat";
5167
- return m[1] === "-" || m[1] === "−" ? "down" : "up";
5239
+ if (m[1]) return m[1] === "+" ? "up" : "down";
5240
+ if (/\b(below|under|down|behind|short|less|fewer|lower)\b/i.test(text2)) return "down";
5241
+ return "up";
5242
+ }
5243
+ function changeFigure(text2) {
5244
+ const m = /[+\-−]?\s*[$€£¥]?\s*(?:\d[\d,]*(?:\.\d+)?|\.\d+)\s?(?:%|(?:days?|hours?|hrs?|mins?|minutes?|weeks?|months?|years?|points?|pts)(?![A-Za-z])|[A-Za-z]{1,3}(?![A-Za-z]))?/i.exec(text2);
5245
+ return m ? m[0].trim() : null;
5246
+ }
5247
+ const CHANGE_SHORT_FROM = 1e5;
5248
+ function roundChange(text2) {
5249
+ const m = /(\d[\d,]*(?:\.\d+)?|\.\d+)/.exec(text2);
5250
+ if (!m) return text2;
5251
+ const n2 = Number(m[1].replace(/,/g, ""));
5252
+ if (!Number.isFinite(n2)) return text2;
5253
+ const after = text2.slice(m.index + m[1].length);
5254
+ let shown2 = null;
5255
+ if (n2 >= CHANGE_SHORT_FROM && !/^\s?(?:[KMBT]|k|bn|mn)(?![A-Za-z])/.test(after)) {
5256
+ try {
5257
+ shown2 = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }).format(n2);
5258
+ } catch {
5259
+ shown2 = null;
5260
+ }
5261
+ } else if (/\.\d{3,}$/.test(m[1])) {
5262
+ shown2 = String(Math.round(n2 * 100) / 100);
5263
+ }
5264
+ return shown2 === null ? text2 : text2.slice(0, m.index) + shown2 + after;
5168
5265
  }
5169
5266
  const ARROWS = { up: "▲", down: "▼", flat: "" };
5170
5267
  function statExtras(box, d, ctx) {
@@ -5182,11 +5279,15 @@ function statExtras(box, d, ctx) {
5182
5279
  if (p.has("change") && (raw || loading)) {
5183
5280
  const font = themeFont(t2, 600, STAT_PILL_TEXT);
5184
5281
  const arrow = dir ? ARROWS[dir] : "";
5185
- const full = raw ? arrow ? `${arrow} ${raw}` : raw : "";
5282
+ const rounded2 = roundChange(raw);
5283
+ const full = rounded2 ? arrow ? `${arrow} ${rounded2}` : rounded2 : "";
5186
5284
  const valueW = loading ? Math.min(w2, Math.max(56, d.size * 3.2)) : m.width(d.value[0] ?? "", themeFont(t2, STAT_WEIGHT, d.size));
5187
5285
  const natural = loading ? 48 : m.width(full, font) + STAT_PILL_X * 2;
5188
5286
  const inline = d.value.length === 1 && w2 >= STAT_INLINE_MIN && valueW + STAT_CHANGE_GAP + natural <= w2;
5189
- const text2 = inline ? full : ellipsize(full, w2 - STAT_PILL_X * 2, font, m);
5287
+ const room = w2 - STAT_PILL_X * 2;
5288
+ const figure = !inline && raw && m.width(full, font) > room ? changeFigure(rounded2) : null;
5289
+ const short2 = figure ? arrow ? `${arrow} ${figure}` : figure : full;
5290
+ const text2 = inline ? full : ellipsize(short2, room, font, m);
5190
5291
  const width = loading ? natural : m.width(text2, font) + STAT_PILL_X * 2;
5191
5292
  if (inline) change = { text: text2, width, valueW, inline, y: bottom - d.size * 0.36 };
5192
5293
  else {
@@ -5739,6 +5840,15 @@ const STACK_UNDER = 360;
5739
5840
  const HEADROOM = 1.15;
5740
5841
  function pairText(actual, target, format) {
5741
5842
  const a = valueText(actual, format), t2 = valueText(target, format);
5843
+ const short2 = (v) => Math.abs(v) >= 1e5 && Math.abs(v) < 1e15;
5844
+ if (short2(actual) !== short2(target) && Math.abs(actual) < 1e15 && Math.abs(target) < 1e15 && Math.min(Math.abs(actual), Math.abs(target)) >= 1e3) {
5845
+ try {
5846
+ const nf = formatter(format, { notation: "compact", minimumFractionDigits: 0, maximumFractionDigits: 1 });
5847
+ const as = nf.format(actual), ts = nf.format(target);
5848
+ if (as !== ts) return `${as} of ${ts}`;
5849
+ } catch {
5850
+ }
5851
+ }
5742
5852
  if (a !== t2 || actual === target) return `${a} of ${t2}`;
5743
5853
  const opts = { notation: "compact", maximumSignificantDigits: 3 };
5744
5854
  try {
@@ -7039,11 +7149,11 @@ const stacked = {
7039
7149
  const slots = d.slots.map((s, i) => {
7040
7150
  const { cx, shownLabel, labelX } = placed[i];
7041
7151
  const segs = [];
7042
- let up = 0, down = 0;
7152
+ let up2 = 0, down = 0;
7043
7153
  s.values.forEach((v, k2) => {
7044
7154
  if (v === null || v === 0) return;
7045
- const from = v > 0 ? up : down, to = from + v;
7046
- if (v > 0) up = to;
7155
+ const from = v > 0 ? up2 : down, to = from + v;
7156
+ if (v > 0) up2 = to;
7047
7157
  else down = to;
7048
7158
  const y1 = y(from), y2 = y(to);
7049
7159
  segs.push({ series: k2, rect: { x: cx - barW / 2, y: Math.min(y1, y2), w: barW, h: Math.abs(y2 - y1) }, end: false, up: v > 0 });
@@ -7278,14 +7388,14 @@ const waterfall = {
7278
7388
  const bar = w2.bars[i];
7279
7389
  if (!full || !bar) return;
7280
7390
  const color2 = bar.tone === "total" ? c2.accent : bar.tone === "down" ? c2.bad : c2.good;
7281
- const up = bar.rising;
7391
+ const up2 = bar.rising;
7282
7392
  const grow = reveal < 1 ? staggered(reveal, i, n2) : 1;
7283
7393
  const h2 = ctx.tween(box.node, `waterfall:${i}`, full.h, 440) * grow;
7284
7394
  if (h2 <= 0.25) return;
7285
- const b = { x: full.x, y: up ? full.y + full.h - h2 : full.y, w: full.w, h: h2 };
7286
- barPath(g, ox + b.x, oy + b.y, b.w, b.h, Math.min(5, b.w / 2, b.h), up);
7395
+ const b = { x: full.x, y: up2 ? full.y + full.h - h2 : full.y, w: full.w, h: h2 };
7396
+ barPath(g, ox + b.x, oy + b.y, b.w, b.h, Math.min(5, b.w / 2, b.h), up2);
7287
7397
  const over2 = !!hot && hot.x - ox >= full.x && hot.x - ox <= full.x + full.w && hot.y - oy >= full.y && hot.y - oy <= full.y + full.h;
7288
- paintPremiumBar(ctx, {}, color2, up ? "up" : "down", ctx.tween(box.node, `waterfall:hover:${i}`, over2 ? 1 : 0, 165));
7398
+ paintPremiumBar(ctx, {}, color2, up2 ? "up" : "down", ctx.tween(box.node, `waterfall:hover:${i}`, over2 ? 1 : 0, 165));
7289
7399
  if (bar.label) {
7290
7400
  g.save();
7291
7401
  g.globalAlpha = base2 * fade * 0.9;
@@ -7293,7 +7403,7 @@ const waterfall = {
7293
7403
  g.textAlign = "center";
7294
7404
  g.textBaseline = "middle";
7295
7405
  g.fillStyle = c2.muted;
7296
- const outside = up ? oy + b.y - 9 : oy + b.y + b.h + 9;
7406
+ const outside = up2 ? oy + b.y - 9 : oy + b.y + b.h + 9;
7297
7407
  const inPlot = outside >= oy + d.plot.y + 4 && outside <= oy + d.plot.y + d.plot.h - 4;
7298
7408
  if (inPlot) g.fillText(bar.label, ox + b.x + b.w / 2, outside);
7299
7409
  g.restore();
@@ -8126,11 +8236,11 @@ chart "Revenue vs last year" kind=line items=sales x=month y=revenue,last_year l
8126
8236
  const grow = reveal < 1 ? staggered(reveal, i, d.slots.length) : 1;
8127
8237
  (s.bars ?? []).forEach((full, k2) => {
8128
8238
  if (!full || full.h <= 0) return;
8129
- const up = full.y + full.h / 2 < zero;
8239
+ const up2 = full.y + full.h / 2 < zero;
8130
8240
  const h2 = ctx.tween(box.node, `bar:${i}:${k2}`, full.h, 440) * grow;
8131
8241
  if (h2 <= 0.25) return;
8132
- const b = { x: full.x, y: up ? full.y + full.h - h2 : full.y, w: full.w, h: h2 };
8133
- barPath(g, ox + b.x, oy + b.y, b.w, b.h, Math.min(7, b.w / 2, b.h), up);
8242
+ const b = { x: full.x, y: up2 ? full.y + full.h - h2 : full.y, w: full.w, h: h2 };
8243
+ barPath(g, ox + b.x, oy + b.y, b.w, b.h, Math.min(7, b.w / 2, b.h), up2);
8134
8244
  const hover = ctx.tween(
8135
8245
  box.node,
8136
8246
  `bar:highlight:${i}:${k2}`,
@@ -8141,7 +8251,7 @@ chart "Revenue vs last year" kind=line items=sales x=month y=revenue,last_year l
8141
8251
  ctx,
8142
8252
  {},
8143
8253
  colorOf2(k2),
8144
- up ? "up" : "down",
8254
+ up2 ? "up" : "down",
8145
8255
  hover
8146
8256
  );
8147
8257
  if (showLabels && k2 === 0 && s.values[0] !== null) {
@@ -8149,10 +8259,10 @@ chart "Revenue vs last year" kind=line items=sales x=month y=revenue,last_year l
8149
8259
  g.save();
8150
8260
  g.font = ctx.font(600, 11);
8151
8261
  const slotRoom = pw / d.slots.length - 8;
8152
- const outside = up ? b.y - 9 : b.y + b.h + 9;
8262
+ const outside = up2 ? b.y - 9 : b.y + b.h + 9;
8153
8263
  const roomOutside = outside >= d.plot.y + 8 && outside <= d.plot.y + d.plot.h - 8;
8154
8264
  const inside2 = !roomOutside && b.h >= 30;
8155
- const labelY = roomOutside ? outside : up ? b.y + 14 : b.y + b.h - 14;
8265
+ const labelY = roomOutside ? outside : up2 ? b.y + 14 : b.y + b.h - 14;
8156
8266
  const room = inside2 ? b.w - 6 : slotRoom;
8157
8267
  if (inside2 && g.measureText(label2).width >= room) label2 = shortValueText(s.values[0], format);
8158
8268
  if ((roomOutside || inside2) && g.measureText(label2).width < room) {
@@ -10802,8 +10912,8 @@ accordion "Shipping" bind=shipping
10802
10912
  }
10803
10913
  };
10804
10914
  const RATIOS = ["16:9", "4:3", "3:2", "1:1", "2:3", "3:4"];
10805
- const FITS = ["cover", "contain"];
10806
- const FADE_MS = 200;
10915
+ const FITS$1 = ["cover", "contain"];
10916
+ const FADE_MS$1 = 200;
10807
10917
  function ratioValue(r) {
10808
10918
  const [w2, h2] = r.split(":").map(Number);
10809
10919
  return w2 / h2;
@@ -10856,7 +10966,7 @@ const image = {
10856
10966
  props: {
10857
10967
  src: { type: "string", required: true, description: "The image URL. Only the app's own site and hosts it allows will load." },
10858
10968
  ratio: { type: "enum", values: RATIOS, default: "16:9", description: "Width to height: 16:9, 4:3, 3:2, 1:1, 2:3 or 3:4. The space is kept while the image loads." },
10859
- fit: { type: "enum", values: FITS, default: "cover", description: "cover fills the space and crops the edges; contain shows the whole image." }
10969
+ fit: { type: "enum", values: FITS$1, default: "cover", description: "cover fills the space and crops the edges; contain shows the whole image." }
10860
10970
  },
10861
10971
  example: `image "Ridgeline trail runners, side view" src="/images/ridgeline.jpg" ratio=4:3`,
10862
10972
  semantics(box, ctx) {
@@ -10875,11 +10985,11 @@ const image = {
10875
10985
  g.clip();
10876
10986
  if (state.status === "ready" && state.image) {
10877
10987
  const img = state.image;
10878
- const fit2 = p.oneOf("fit", FITS, "cover");
10988
+ const fit2 = p.oneOf("fit", FITS$1, "cover");
10879
10989
  if (fit2 === "contain") fillTint(g, theme.colors.line, 0.4);
10880
10990
  const age = ctx.now - (state.readyAt ?? 0);
10881
- if (ctx.motion && age < FADE_MS) {
10882
- g.globalAlpha *= Math.max(0, age / FADE_MS);
10991
+ if (ctx.motion && age < FADE_MS$1) {
10992
+ g.globalAlpha *= Math.max(0, age / FADE_MS$1);
10883
10993
  ctx.requestFrame();
10884
10994
  }
10885
10995
  const r = fitRect(img.width || 1, img.height || 1, box.w, box.h, fit2);
@@ -11284,8 +11394,8 @@ function measure(box, ctx) {
11284
11394
  const lines = text2 ? wrapText(text2, width, font, ctx.measure) : [""];
11285
11395
  const detailText = p.str("detail");
11286
11396
  const detail2 = detailText ? wrapText(detailText, width, detailFont, ctx.measure) : loading && p.has("detail") ? [""] : [];
11287
- const body = lines.length * lh + (detail2.length ? t2.space.xs + detail2.length * detailLH : 0);
11288
- return { lines, detail: detail2, font, detailFont, lh, detailLH, padX, padY, textX, icon: icon2, height: padY * 2 + Math.max(body, icon2 ? ICON$1 : 0) };
11397
+ const body2 = lines.length * lh + (detail2.length ? t2.space.xs + detail2.length * detailLH : 0);
11398
+ return { lines, detail: detail2, font, detailFont, lh, detailLH, padX, padY, textX, icon: icon2, height: padY * 2 + Math.max(body2, icon2 ? ICON$1 : 0) };
11289
11399
  }
11290
11400
  function paintPanel(box, ctx, color2) {
11291
11401
  const { g, theme } = ctx;
@@ -11693,11 +11803,11 @@ text "Showing the {lower(view)}" tone=muted`,
11693
11803
  };
11694
11804
  const BAR_H = 32, BAR_GAP = 10, ARROW = 32, DOT = 6, DOT_GAP = 8;
11695
11805
  const pagesOf = /* @__PURE__ */ new WeakMap();
11696
- function pageOf(raw, pages) {
11806
+ function pageOf$1(raw, pages) {
11697
11807
  const n2 = Math.round(toNumber(raw));
11698
11808
  return Number.isFinite(n2) ? Math.min(Math.max(0, n2), Math.max(0, pages - 1)) : 0;
11699
11809
  }
11700
- function goTo(ctx, page) {
11810
+ function goTo$1(ctx, page) {
11701
11811
  const key = ctx.props(ctx.target.node).raw("bind");
11702
11812
  if (!key) return;
11703
11813
  ctx.set(key, page);
@@ -11751,7 +11861,7 @@ carousel bind=page
11751
11861
  const per = Math.max(1, Math.floor((box.w + gap) / (min + gap)));
11752
11862
  const cw = (box.w - gap * (per - 1)) / per;
11753
11863
  const pages = Math.max(1, Math.ceil(kids.length / per));
11754
- const page = pageOf(p.bound(), pages);
11864
+ const page = pageOf$1(p.bound(), pages);
11755
11865
  pagesOf.set(box.node, pages);
11756
11866
  let tallest = 0;
11757
11867
  kids.forEach((k2, i) => {
@@ -11799,14 +11909,14 @@ carousel bind=page
11799
11909
  const d = ctx.target.detail;
11800
11910
  if (typeof d !== "string") return;
11801
11911
  const n2 = Number(d.split(":")[1]);
11802
- if (Number.isFinite(n2)) goTo(ctx, n2);
11912
+ if (Number.isFinite(n2)) goTo$1(ctx, n2);
11803
11913
  },
11804
11914
  key(ctx, k2) {
11805
11915
  if (k2 !== "ArrowLeft" && k2 !== "ArrowRight") return false;
11806
11916
  const node = ctx.target.node;
11807
11917
  const pages = pagesOf.get(node) ?? 1;
11808
- const page = pageOf(ctx.props(node).bound(), pages);
11809
- goTo(ctx, Math.min(pages - 1, Math.max(0, page + (k2 === "ArrowRight" ? 1 : -1))));
11918
+ const page = pageOf$1(ctx.props(node).bound(), pages);
11919
+ goTo$1(ctx, Math.min(pages - 1, Math.max(0, page + (k2 === "ArrowRight" ? 1 : -1))));
11810
11920
  return true;
11811
11921
  }
11812
11922
  };
@@ -12030,8 +12140,8 @@ function parseBands(raw) {
12030
12140
  return nums;
12031
12141
  }
12032
12142
  function zonesFor(bands, good) {
12033
- const up = bands.length === 1 ? ["bad", "good"] : ["bad", "warn", "good"];
12034
- return good === "up" ? up : [...up].reverse();
12143
+ const up2 = bands.length === 1 ? ["bad", "good"] : ["bad", "warn", "good"];
12144
+ return good === "up" ? up2 : [...up2].reverse();
12035
12145
  }
12036
12146
  function meterText(v, min, max, format) {
12037
12147
  if (v === null) return "—";
@@ -15308,7 +15418,7 @@ const DRAG_SLOP$1 = 4;
15308
15418
  function scrollHeight(controlHeight, size) {
15309
15419
  return controlHeight * { sm: 6, md: 9, lg: 12 }[size];
15310
15420
  }
15311
- const dataOf$1 = (b) => b.data;
15421
+ const dataOf$3 = (b) => b.data;
15312
15422
  const maxOf = (d) => Math.max(0, d.content - d.view);
15313
15423
  function scrollTo(v, d, y) {
15314
15424
  const before = v.y ?? 0;
@@ -15349,11 +15459,11 @@ scroll "Recent activity" size=sm
15349
15459
  box.data = data2;
15350
15460
  },
15351
15461
  clipChildren(box) {
15352
- const d = dataOf$1(box);
15462
+ const d = dataOf$3(box);
15353
15463
  return d && maxOf(d) > 0 ? { x: box.x, y: box.y, w: box.w, h: box.h } : null;
15354
15464
  },
15355
15465
  revealChild(box, view, rect2) {
15356
- const d = dataOf$1(box);
15466
+ const d = dataOf$3(box);
15357
15467
  if (!d) return false;
15358
15468
  const y = view.y ?? 0, pad2 = 8;
15359
15469
  if (rect2.y < box.y || rect2.h > box.h) return scrollTo(view, d, y - (box.y - rect2.y) - (rect2.h > box.h ? 0 : pad2));
@@ -15361,12 +15471,12 @@ scroll "Recent activity" size=sm
15361
15471
  return false;
15362
15472
  },
15363
15473
  paint(box, ctx) {
15364
- const d = dataOf$1(box);
15474
+ const d = dataOf$3(box);
15365
15475
  if (!d || maxOf(d) <= 0) return;
15366
15476
  ctx.addHit(box, { detail: SCROLL });
15367
15477
  },
15368
15478
  paintOver(box, ctx) {
15369
- const d = dataOf$1(box);
15479
+ const d = dataOf$3(box);
15370
15480
  if (!d || maxOf(d) <= 0) return;
15371
15481
  const { g, theme } = ctx;
15372
15482
  const c2 = theme.colors;
@@ -15388,12 +15498,12 @@ scroll "Recent activity" size=sm
15388
15498
  hitTest: (_box, _x, _y, detail2) => ({ detail: detail2 }),
15389
15499
  cursor: () => "default",
15390
15500
  wheel(ctx) {
15391
- const d = dataOf$1(ctx.target.box);
15501
+ const d = dataOf$3(ctx.target.box);
15392
15502
  if (!d || !maxOf(d) || !ctx.deltaY) return false;
15393
15503
  return scrollTo(ctx.view(ctx.target.node), d, (ctx.view(ctx.target.node).y ?? 0) + ctx.deltaY);
15394
15504
  },
15395
15505
  key(ctx, key) {
15396
- const d = dataOf$1(ctx.target.box);
15506
+ const d = dataOf$3(ctx.target.box);
15397
15507
  if (!d || !maxOf(d)) return false;
15398
15508
  const v = ctx.view(ctx.target.node);
15399
15509
  const y = v.y ?? 0;
@@ -15404,7 +15514,7 @@ scroll "Recent activity" size=sm
15404
15514
  },
15405
15515
  drag(ctx) {
15406
15516
  const v = ctx.view(ctx.target.node);
15407
- const d = dataOf$1(ctx.target.box);
15517
+ const d = dataOf$3(ctx.target.box);
15408
15518
  if (ctx.phase === "start") {
15409
15519
  v.dragY = ctx.y;
15410
15520
  v.dragFrom = v.y ?? 0;
@@ -15423,7 +15533,7 @@ scroll "Recent activity" size=sm
15423
15533
  return false;
15424
15534
  },
15425
15535
  semantics(box, ctx) {
15426
- const d = dataOf$1(box);
15536
+ const d = dataOf$3(box);
15427
15537
  const name2 = ctx.props(box.node).text() || void 0;
15428
15538
  if (!d || maxOf(d) <= 0) return name2 ? { role: "group", name: name2 } : null;
15429
15539
  return { role: "region", name: name2 ?? "Scrolling area", detail: SCROLL };
@@ -15534,7 +15644,7 @@ const PAD = 6;
15534
15644
  const ROW_PAD = 12;
15535
15645
  const ICON = 18;
15536
15646
  const TONES = ["default", "bad"];
15537
- const dataOf = (b) => b.data ?? { items: [], more: 0 };
15647
+ const dataOf$2 = (b) => b.data ?? { items: [], more: 0 };
15538
15648
  const usable = (it) => !!it && !it.disabled;
15539
15649
  function readItems(node, kids, props) {
15540
15650
  const all = kids.filter((k2) => k2.type === "menu-item");
@@ -15613,7 +15723,7 @@ const menu = {
15613
15723
  const p = ctx.props(box.node);
15614
15724
  const { g, theme } = ctx;
15615
15725
  const c2 = theme.colors;
15616
- const disabled = p.cond("disabled") || !dataOf(box).items.some(usable);
15726
+ const disabled = p.cond("disabled") || !dataOf$2(box).items.some(usable);
15617
15727
  const primary = p.oneOf("variant", ["secondary", "primary"], "secondary") === "primary" && !disabled;
15618
15728
  const open2 = ctx.isPopupOpen(box.node);
15619
15729
  const hover = ctx.tween(box.node, "menu:hover", !disabled && ctx.isHovered(box.node) ? 1 : 0, MOTION.hover);
@@ -15671,13 +15781,13 @@ const menu = {
15671
15781
  },
15672
15782
  key(ctx, key) {
15673
15783
  if (key !== "ArrowDown" && key !== "ArrowUp" && key !== "Enter" && key !== " ") return false;
15674
- const items = dataOf(ctx.target.box).items;
15784
+ const items = dataOf$2(ctx.target.box).items;
15675
15785
  ctx.openPopup({ highlight: idAt(items, key === "ArrowUp" ? last(items) : first(items)) });
15676
15786
  return true;
15677
15787
  },
15678
15788
  semantics(box, ctx) {
15679
15789
  const p = ctx.props(box.node);
15680
- const { items } = dataOf(box);
15790
+ const { items } = dataOf$2(box);
15681
15791
  const open2 = ctx.popupOpen;
15682
15792
  const hi = items[hiOf(items, ctx.popup)];
15683
15793
  const disabled = p.cond("disabled") || !items.some(usable) || void 0;
@@ -15687,7 +15797,7 @@ const menu = {
15687
15797
  },
15688
15798
  popup: {
15689
15799
  measure(owner, ctx) {
15690
- const { items } = dataOf(owner);
15800
+ const { items } = dataOf$2(owner);
15691
15801
  if (!items.length || ctx.props(owner.node).cond("disabled")) return null;
15692
15802
  const widest = Math.max(...items.map((it) => textWidth(ctx, it.label, 500, 14) + (it.icon ? ICON + 10 : 0)));
15693
15803
  const w2 = Math.min(320, Math.max(180, Math.ceil(widest) + 2 * ROW_PAD + 2 * PAD));
@@ -15695,7 +15805,7 @@ const menu = {
15695
15805
  return { w: w2, h: h2, minH: Math.min(h2, 3 * ROW_H + 2 * PAD), ownWidth: true, alignEnd: owner.x + owner.w / 2 > ctx.screenWidth() / 2 };
15696
15806
  },
15697
15807
  paint(owner, area2, ctx, state) {
15698
- const { items } = dataOf(owner);
15808
+ const { items } = dataOf$2(owner);
15699
15809
  const { g, theme } = ctx;
15700
15810
  const c2 = theme.colors;
15701
15811
  const hi = hiOf(items, state);
@@ -15725,15 +15835,15 @@ const menu = {
15725
15835
  },
15726
15836
  point(ctx, detail2) {
15727
15837
  const id = idOfDetail(detail2);
15728
- if (id && dataOf(ctx.target.box).items.some((x) => x.node.id === id && usable(x))) ctx.popup.highlight = id;
15838
+ if (id && dataOf$2(ctx.target.box).items.some((x) => x.node.id === id && usable(x))) ctx.popup.highlight = id;
15729
15839
  },
15730
15840
  press(ctx) {
15731
15841
  const id = idOfDetail(ctx.target.detail);
15732
- const it = dataOf(ctx.target.box).items.find((x) => x.node.id === id);
15842
+ const it = dataOf$2(ctx.target.box).items.find((x) => x.node.id === id);
15733
15843
  if (usable(it)) choose(ctx, it);
15734
15844
  },
15735
15845
  key(ctx, key) {
15736
- const items = dataOf(ctx.target.box).items;
15846
+ const items = dataOf$2(ctx.target.box).items;
15737
15847
  const hi = hiOf(items, ctx.popup);
15738
15848
  const go = (i) => {
15739
15849
  ctx.popup.highlight = idAt(items, i);
@@ -26436,7 +26546,7 @@ function drawEach(node, scope, f) {
26436
26546
  const items = r.value;
26437
26547
  const rec = f.press;
26438
26548
  const outer = rec?.locate;
26439
- const listPlace = outer && PATH.test(expr.trim()) ? placeOf(expr.trim(), outer) : null;
26549
+ const listPlace = outer && PATH.test(expr.trim()) ? placeOf$1(expr.trim(), outer) : null;
26440
26550
  const keyExpr = node.props.key === void 0 ? void 0 : wholeExpression(node.props.key) ?? node.props.key;
26441
26551
  const seen = /* @__PURE__ */ new Set();
26442
26552
  for (let i = 0; i < items.length && f.steps <= MAX_SCENE_STEPS; i++) {
@@ -27574,6 +27684,495 @@ function dragSemantics(r, name2, detail2) {
27574
27684
  ...r.selected !== void 0 ? { pressed: r.selected } : {}
27575
27685
  };
27576
27686
  }
27687
+ const FALLBACK_SCALE = 1.6;
27688
+ const up = (o) => Object.fromEntries(Object.entries(o).map(([k2, v]) => [k2, Math.round(v * FALLBACK_SCALE)]));
27689
+ function slideTokens(t2) {
27690
+ return t2.slide ?? {
27691
+ space: up(t2.space),
27692
+ radius: up(t2.radius),
27693
+ text: up(t2.text),
27694
+ control: up(t2.control),
27695
+ heading: { cover: Math.round(t2.text.display * FALLBACK_SCALE * 1.25), slide: Math.round(t2.text.display * FALLBACK_SCALE * 0.85) }
27696
+ };
27697
+ }
27698
+ const made$1 = /* @__PURE__ */ new WeakMap();
27699
+ function slideTheme(t2) {
27700
+ let s = made$1.get(t2);
27701
+ if (!s) {
27702
+ const k2 = slideTokens(t2);
27703
+ s = { ...t2, space: k2.space, radius: k2.radius, text: k2.text, control: k2.control, zoom: k2.text.body / Math.max(1, t2.text.body) };
27704
+ made$1.set(t2, s);
27705
+ made$1.set(s, s);
27706
+ }
27707
+ return s;
27708
+ }
27709
+ const DESIGN_W = 960;
27710
+ const DESIGN_H = 540;
27711
+ const MIN_FIT = 0.6;
27712
+ const FITS = [0.95, 0.9, 0.85, 0.8, 0.75, 0.7, 0.65, MIN_FIT];
27713
+ const LAYOUTS = ["title", "content", "agenda"];
27714
+ const MAX_AGENDA = 6;
27715
+ const placeOf = /* @__PURE__ */ new WeakMap();
27716
+ const fadeOf = /* @__PURE__ */ new WeakMap();
27717
+ const dataOf$1 = (b) => b.data;
27718
+ const hinted = /* @__PURE__ */ new WeakMap();
27719
+ function alignStats(slide2) {
27720
+ let changed = false;
27721
+ const mine = hinted.get(slide2.node) ?? [];
27722
+ const gather = (b, into, depth) => {
27723
+ for (const c2 of b.children) {
27724
+ if (c2.node.type === "stat") into.push(c2);
27725
+ else if (depth < 2 && c2.node.type !== "grid" && c2.node.type !== "row") gather(c2, into, depth + 1);
27726
+ }
27727
+ };
27728
+ const visit = (b) => {
27729
+ if (b.node.type === "grid" || b.node.type === "row") {
27730
+ const stats = [];
27731
+ gather(b, stats, 0);
27732
+ const sized = stats.map((s) => s.data).filter((d) => typeof d?.size === "number");
27733
+ if (stats.length > 1 && sized.length === stats.length) {
27734
+ const size = Math.min(...sized.map((d) => d.size));
27735
+ const labelLines2 = Math.max(...sized.map((d) => d.label?.length ?? 0));
27736
+ if (sized.some((d) => d.size !== size || (d.label?.length ?? 0) !== labelLines2)) {
27737
+ for (const s of stats) {
27738
+ const had = statHint.get(s.node);
27739
+ if (had?.size !== size || had?.labelLines !== labelLines2) changed = true;
27740
+ statHint.set(s.node, { size, labelLines: labelLines2 });
27741
+ if (!mine.includes(s.node)) mine.push(s.node);
27742
+ }
27743
+ }
27744
+ }
27745
+ }
27746
+ b.children.forEach(visit);
27747
+ };
27748
+ slide2.children.forEach(visit);
27749
+ hinted.set(slide2.node, mine);
27750
+ return changed;
27751
+ }
27752
+ function layoutChildren(box, ctx, x, y, w2, gap) {
27753
+ let at2 = y;
27754
+ const kids = ctx.visibleChildren(box.node);
27755
+ kids.forEach((k2, i) => {
27756
+ const kb = ctx.layout(k2, x, at2, w2);
27757
+ box.children.push(kb);
27758
+ at2 += kb.h + (i < kids.length - 1 ? gap : 0);
27759
+ });
27760
+ return kids.length ? at2 - y : 0;
27761
+ }
27762
+ const slide = {
27763
+ type: "slide",
27764
+ category: "layout",
27765
+ description: `One 16:9 slide in a deck, with its title drawn large at the top and the slide's content under it: keep each to one idea, and write the title as the point it makes, not a label. What doesn't fit is shrunk, then cut off, and a table or list shows about five rows, so show the top few with take() and sort(), a total or a chart in place of every row; write money one way through the deck, and a stat's change= as a short signed figure such as change="+1.4 h", with good=down where lower is better (costs, reply time).`,
27766
+ text: { description: "The slide's title, e.g. Three numbers that sum up the quarter." },
27767
+ props: {
27768
+ layout: { type: "enum", values: LAYOUTS, default: "content", description: "title for the opening slide (a large title with its children under it, centred on the slide), content for the rest (title at the top, children below), agenda for a slide that lists the other slides' titles by itself." },
27769
+ eyebrow: { type: "string", description: `A few words above the title, in the accent color, e.g. eyebrow="Q3 2026" or the section's name.` },
27770
+ subtitle: { type: "string", description: 'A quieter line under the title, e.g. subtitle="Prepared for the board".' },
27771
+ appendix: { type: "boolean", default: false, description: "true for a backup slide after the main ones: it's left out of the slide count and the agenda, and numbered as Appendix." }
27772
+ },
27773
+ children: "any",
27774
+ parents: ["deck"],
27775
+ example: `slide "What we do next"
27776
+ list
27777
+ list-item "Hire two in support"
27778
+ list-item "Open the Denver office"`,
27779
+ theme: slideTheme,
27780
+ layout(box, ctx) {
27781
+ const p = ctx.props(box.node);
27782
+ const t2 = ctx.theme;
27783
+ const k2 = slideTokens(t2);
27784
+ const layout = p.oneOf("layout", LAYOUTS, "content");
27785
+ const scale2 = box.w / DESIGN_W;
27786
+ box.h = box.w * (DESIGN_H / DESIGN_W);
27787
+ const pad2 = t2.space.xl;
27788
+ const width = DESIGN_W - pad2 * 2;
27789
+ const cover = layout === "title";
27790
+ const size = cover ? k2.heading.cover : k2.heading.slide;
27791
+ const font = `${cover ? 700 : 600} ${size}px ${t2.font.family}`;
27792
+ const lineHeight = Math.round(size * 1.15);
27793
+ const text2 = p.text().trim();
27794
+ const lines = text2 ? fitLines(text2, width, font, ctx.measure, cover ? 3 : 2) : [];
27795
+ const titleOnlyH = lines.length * lineHeight;
27796
+ const gap = t2.space.lg;
27797
+ const eyebrowText = p.has("eyebrow") ? ellipsize(p.str("eyebrow").trim(), width, `600 ${t2.text.caption}px ${t2.font.family}`, ctx.measure) : "";
27798
+ const eyebrow = { text: eyebrowText, font: `600 ${t2.text.caption}px ${t2.font.family}`, height: eyebrowText ? Math.round(t2.text.caption * 1.4) + t2.space.xs : 0 };
27799
+ const subFont = `400 ${t2.text.lead}px ${t2.font.family}`;
27800
+ const subLines = p.has("subtitle") && p.str("subtitle").trim() ? fitLines(p.str("subtitle").trim(), width, subFont, ctx.measure, 2) : [];
27801
+ const subLH = Math.round(t2.text.lead * 1.35);
27802
+ const subH = subLines.length ? t2.space.sm + subLines.length * subLH : 0;
27803
+ const titleH = eyebrow.height + titleOnlyH + subH;
27804
+ const afterTitle = titleH ? cover ? t2.space.md : gap : 0;
27805
+ const place = placeOf.get(box.node);
27806
+ const agendaFont = `500 ${t2.text.lead}px ${t2.font.family}`;
27807
+ const rowHeight = Math.round(t2.text.lead * 1.75);
27808
+ const titles = layout === "agenda" ? place?.agenda ?? [] : [];
27809
+ const listed = titles.length > MAX_AGENDA ? titles.slice(0, MAX_AGENDA - 1) : titles;
27810
+ const rows = listed.map((s, i) => ellipsize(`${i + 1} ${s}`, width, agendaFont, ctx.measure));
27811
+ if (titles.length > listed.length) rows.push(`and ${titles.length - listed.length} more`);
27812
+ const agendaH = rows.length * rowHeight;
27813
+ const footFont = `500 ${t2.text.caption}px ${t2.font.family}`;
27814
+ const label2 = place?.numbers ? place.label ?? `${place.index + 1} / ${place.count}` : "";
27815
+ const beside = (label2 ? ctx.measure.width(label2, footFont) + t2.space.md : 0) + (t2.deck?.logo ? DESIGN_W / 5 + t2.space.sm : 0);
27816
+ const foot = { label: label2, footer: place?.footer ? ellipsize(place.footer, Math.max(0, width - beside), footFont, ctx.measure) : "" };
27817
+ const x0 = box.x + pad2;
27818
+ const agendaTop = pad2 + titleH + afterTitle;
27819
+ const top = agendaTop + (agendaH ? agendaH + gap : 0);
27820
+ for (const n2 of hinted.get(box.node) ?? []) statHint.delete(n2);
27821
+ hinted.delete(box.node);
27822
+ const lay = (f) => {
27823
+ const once = () => {
27824
+ box.children.length = 0;
27825
+ return layoutChildren(box, ctx, x0, box.y + top, width / f, gap);
27826
+ };
27827
+ const h2 = once();
27828
+ return alignStats(box) ? once() : h2;
27829
+ };
27830
+ let content = lay(1);
27831
+ const usable2 = DESIGN_H - pad2 * 2;
27832
+ const room = Math.max(0, DESIGN_H - pad2 - top);
27833
+ let titleTop = pad2, shiftY = 0, fit2 = 1;
27834
+ const offX = 0;
27835
+ if (!(cover && titleH + afterTitle + content <= usable2) && content > room) {
27836
+ fit2 = MIN_FIT;
27837
+ let found = false;
27838
+ for (const f of FITS) {
27839
+ const h2 = lay(f);
27840
+ if (h2 * f <= room + 0.5) {
27841
+ fit2 = f;
27842
+ content = h2;
27843
+ found = true;
27844
+ break;
27845
+ }
27846
+ }
27847
+ if (!found) content = lay(MIN_FIT);
27848
+ }
27849
+ if (cover && titleH + afterTitle + content <= usable2) {
27850
+ titleTop = pad2 + (usable2 - titleH - afterTitle - content) / 2;
27851
+ shiftY = titleTop - pad2;
27852
+ } else if (content <= room) shiftY = cover || agendaH ? 0 : (room - content) / 2;
27853
+ const clipped = content * fit2 > room + 0.5;
27854
+ if (clipped) {
27855
+ const name2 = text2 ? `"${text2}"` : "without a title";
27856
+ ctx.warn?.(`slide ${name2} on line ${box.node.line} has too much on it to fit, even at ${Math.round(MIN_FIT * 100)}% size, so its bottom is cut off. Split it into two slides`);
27857
+ }
27858
+ const cy0 = box.y + top;
27859
+ const transform = {
27860
+ scale: scale2 * fit2,
27861
+ dx: box.x + scale2 * (x0 + offX - fit2 * x0 - box.x),
27862
+ dy: box.y + scale2 * (cy0 + shiftY - fit2 * cy0 - box.y)
27863
+ };
27864
+ const data2 = {
27865
+ layout,
27866
+ scale: scale2,
27867
+ fit: fit2,
27868
+ transform,
27869
+ content,
27870
+ room,
27871
+ clipped,
27872
+ place,
27873
+ title: { lines, font, size, lineHeight, top: titleTop + eyebrow.height },
27874
+ headTop: titleTop,
27875
+ eyebrow,
27876
+ subtitle: { lines: subLines, font: subFont, lineHeight: subLH, top: titleTop + eyebrow.height + titleOnlyH + t2.space.sm },
27877
+ agenda: { rows, font: agendaFont, rowHeight, top: agendaTop },
27878
+ foot,
27879
+ clipBottom: (DESIGN_H - pad2) * scale2
27880
+ };
27881
+ box.data = data2;
27882
+ },
27883
+ childTransform: (box) => dataOf$1(box)?.transform ?? null,
27884
+ clipChildren: (box) => ({ x: box.x, y: box.y, w: box.w, h: dataOf$1(box)?.clipBottom ?? box.h }),
27885
+ semantics(box, ctx) {
27886
+ const d = dataOf$1(box);
27887
+ const name2 = ctx.text(box.node) || void 0;
27888
+ const p = ctx.props(box.node);
27889
+ const said = [
27890
+ d?.place ? `Slide ${d.place.label ? d.place.label.replace(" / ", " of ") : `${d.place.index + 1} of ${d.place.count}`}` : "",
27891
+ p.has("eyebrow") ? p.str("eyebrow").trim() : "",
27892
+ p.has("subtitle") ? p.str("subtitle").trim() : "",
27893
+ ...d?.agenda.rows ?? []
27894
+ ].filter(Boolean).join(". ");
27895
+ return { role: "group", roleDescription: "slide", ...name2 ? { name: name2 } : {}, ...said ? { description: said } : {} };
27896
+ },
27897
+ paint(box, ctx) {
27898
+ const d = dataOf$1(box);
27899
+ if (!d) return;
27900
+ const { g, theme } = ctx;
27901
+ const c2 = theme.colors;
27902
+ const pad2 = theme.space.xl;
27903
+ const s = d.scale;
27904
+ g.save();
27905
+ g.transform(s, 0, 0, s, box.x * (1 - s), box.y * (1 - s));
27906
+ const square = theme.deck?.square === true;
27907
+ if (square) {
27908
+ g.beginPath();
27909
+ g.rect(box.x, box.y, DESIGN_W, DESIGN_H);
27910
+ } else ctx.roundRect(box.x, box.y, DESIGN_W, DESIGN_H, theme.radius.lg);
27911
+ g.fillStyle = c2.raised;
27912
+ g.fill();
27913
+ if (!square) {
27914
+ g.lineWidth = 1 / s;
27915
+ g.strokeStyle = c2.line;
27916
+ g.stroke();
27917
+ }
27918
+ const t2 = d.title;
27919
+ const place = d.place;
27920
+ if (place?.progress !== void 0) {
27921
+ g.save();
27922
+ if (square) {
27923
+ g.beginPath();
27924
+ g.rect(box.x, box.y, DESIGN_W, DESIGN_H);
27925
+ } else ctx.roundRect(box.x, box.y, DESIGN_W, DESIGN_H, theme.radius.lg);
27926
+ g.clip();
27927
+ g.fillStyle = c2.accent;
27928
+ g.fillRect(box.x, box.y + DESIGN_H - theme.space.xs, DESIGN_W * Math.min(1, Math.max(0, place.progress)), theme.space.xs);
27929
+ g.restore();
27930
+ }
27931
+ if (d.layout === "title" && t2.lines.length) {
27932
+ ctx.roundRect(box.x + pad2, box.y + d.headTop - theme.space.lg, theme.space.xl * 1.5, theme.space.xs, theme.space.xs / 2);
27933
+ g.fillStyle = c2.accent;
27934
+ g.fill();
27935
+ }
27936
+ g.textAlign = "left";
27937
+ g.textBaseline = "middle";
27938
+ if (d.eyebrow.text) {
27939
+ g.fillStyle = c2.accent;
27940
+ g.font = d.eyebrow.font;
27941
+ g.fillText(d.eyebrow.text, box.x + pad2, box.y + d.headTop + (d.eyebrow.height - theme.space.xs) / 2);
27942
+ }
27943
+ g.fillStyle = c2.ink;
27944
+ g.font = t2.font;
27945
+ t2.lines.forEach((line2, i) => g.fillText(line2, box.x + pad2, box.y + t2.top + t2.lineHeight * (i + 0.5)));
27946
+ g.fillStyle = c2.muted;
27947
+ g.font = d.subtitle.font;
27948
+ d.subtitle.lines.forEach((line2, i) => g.fillText(line2, box.x + pad2, box.y + d.subtitle.top + d.subtitle.lineHeight * (i + 0.5)));
27949
+ if (d.agenda.rows.length) {
27950
+ g.font = d.agenda.font;
27951
+ d.agenda.rows.forEach((row2, i) => {
27952
+ const y = box.y + d.agenda.top + d.agenda.rowHeight * (i + 0.5);
27953
+ g.fillStyle = c2.ink;
27954
+ g.fillText(row2, box.x + pad2, y);
27955
+ if (i < d.agenda.rows.length - 1) {
27956
+ g.fillStyle = c2.line;
27957
+ g.fillRect(box.x + pad2, box.y + d.agenda.top + d.agenda.rowHeight * (i + 1) - 0.5, DESIGN_W - pad2 * 2, 1);
27958
+ }
27959
+ });
27960
+ }
27961
+ const baseY = box.y + DESIGN_H - pad2 / 2;
27962
+ let leftX = box.x + pad2;
27963
+ const logo = theme.deck?.logo ? ctx.image(theme.deck.logo) : null;
27964
+ if (logo?.status === "ready" && logo.image) {
27965
+ const h2 = Math.round(pad2 * 0.5);
27966
+ const w2 = Math.min(DESIGN_W / 5, h2 * logo.image.width / Math.max(1, logo.image.height));
27967
+ g.drawImage(logo.image.source, leftX, baseY - h2 / 2, w2, h2);
27968
+ leftX += w2 + theme.space.sm;
27969
+ }
27970
+ g.fillStyle = c2.muted;
27971
+ g.font = ctx.font(500, theme.text.caption);
27972
+ if (d.foot.footer) g.fillText(d.foot.footer, leftX, baseY);
27973
+ if (d.foot.label) {
27974
+ g.textAlign = "right";
27975
+ g.fillText(d.foot.label, box.x + DESIGN_W - pad2, baseY);
27976
+ }
27977
+ g.restore();
27978
+ },
27979
+ // A slide that has just been moved to fades in: its own surface over it, clearing (the deck's transition=fade).
27980
+ paintOver(box, ctx) {
27981
+ const d = dataOf$1(box);
27982
+ const cover = fadeOf.get(box.node) ?? 0;
27983
+ if (!d || cover <= 0) return;
27984
+ const { g, theme } = ctx;
27985
+ const s = d.scale;
27986
+ g.save();
27987
+ g.transform(s, 0, 0, s, box.x * (1 - s), box.y * (1 - s));
27988
+ g.globalAlpha *= Math.min(1, cover);
27989
+ if (theme.deck?.square) {
27990
+ g.beginPath();
27991
+ g.rect(box.x, box.y, DESIGN_W, DESIGN_H);
27992
+ } else ctx.roundRect(box.x, box.y, DESIGN_W, DESIGN_H, theme.radius.lg);
27993
+ g.fillStyle = theme.colors.raised;
27994
+ g.fill();
27995
+ g.restore();
27996
+ }
27997
+ };
27998
+ const countOf = /* @__PURE__ */ new WeakMap();
27999
+ const swipeFrom = /* @__PURE__ */ new WeakMap();
28000
+ const SWIPE_DISTANCE = 48;
28001
+ const TRANSITIONS = ["fade", "none"];
28002
+ const FADE_MS = 260;
28003
+ const dataOf = (b) => b.data;
28004
+ function pageOf(raw, count) {
28005
+ const n2 = Math.round(toNumber(raw));
28006
+ return Number.isFinite(n2) ? Math.min(Math.max(0, n2), Math.max(0, count - 1)) : 0;
28007
+ }
28008
+ function goTo(ctx, page) {
28009
+ const node = ctx.target.node;
28010
+ const p = ctx.props(node);
28011
+ const key = p.raw("bind");
28012
+ const count = countOf.get(node) ?? 1;
28013
+ const to = Math.min(Math.max(0, page), Math.max(0, count - 1));
28014
+ if (!key || to === pageOf(p.bound(), count)) return;
28015
+ ctx.set(key, to);
28016
+ runOn(ctx);
28017
+ }
28018
+ const deck = {
28019
+ type: "deck",
28020
+ category: "layout",
28021
+ description: "A slide deck: slides shown one at a time, with arrows and dots to move between them (and a sideways swipe on a touch screen), for presenting a story in a few steps, like a business review; put a slide per step inside it. State is shared by every slide, so one control, such as a segmented for the region, can change what all of them show, and a button with on=set:page:3 jumps to the fourth slide.",
28022
+ props: {
28023
+ bind: { type: "state", required: true, description: "The state name holding the slide shown, starting at 0." },
28024
+ numbers: { type: "boolean", default: true, description: "Show the slide's number, like 2 / 4, in its corner." },
28025
+ footer: { type: "string", description: 'A short line in the bottom left of every slide, e.g. footer="Northwind · Confidential".' },
28026
+ progress: { type: "boolean", default: false, description: "true draws a thin bar along the bottom of each slide showing how far through the deck it is." },
28027
+ transition: { type: "enum", values: TRANSITIONS, default: "fade", description: "fade (a slide fades in when moved to) or none." },
28028
+ on: onProp("after the slide changes")
28029
+ },
28030
+ children: ["slide"],
28031
+ picks: [
28032
+ { for: "a presentation or slide deck, one idea per slide", write: "deck bind=page" }
28033
+ ],
28034
+ example: `state page=0
28035
+ deck bind=page
28036
+ slide "Q3 business review" layout=title
28037
+ text "Revenue is up 18% on last year" style=lead tone=muted
28038
+ slide "Three numbers that sum up the quarter"
28039
+ grid min=220
28040
+ stat label="Revenue" value="$4.82M" change="+18%"
28041
+ stat label="New customers" value="312" change="+9%"`,
28042
+ minWidth: () => 240,
28043
+ layout(box, ctx) {
28044
+ const p = ctx.props(box.node);
28045
+ const t2 = ctx.theme;
28046
+ const slides = ctx.visibleChildren(box.node);
28047
+ const count = slides.length;
28048
+ const page = pageOf(p.bound(), count);
28049
+ countOf.set(box.node, count);
28050
+ const numbers = p.bool("numbers", true);
28051
+ const titles = slides.map((s) => ctx.props(s).text());
28052
+ const shown2 = slides[page];
28053
+ let h2 = 0;
28054
+ if (shown2) {
28055
+ const backup = slides.map((s) => ctx.props(s).bool("appendix", false));
28056
+ const mainCount = backup.filter((b) => !b).length, backupCount = count - mainCount;
28057
+ const before = backup.slice(0, page + 1).filter((b) => b === backup[page]).length;
28058
+ const label2 = backup[page] ? `Appendix ${before} / ${backupCount}` : `${before} / ${mainCount}`;
28059
+ const agenda = slides.filter((s, i) => !backup[i] && !["title", "agenda"].includes(ctx.props(s).str("layout")) && ctx.props(s).text().trim()).map((s) => ctx.props(s).text().trim());
28060
+ const footer = p.has("footer") ? p.str("footer").trim() : "";
28061
+ placeOf.set(shown2, {
28062
+ index: page,
28063
+ count,
28064
+ numbers,
28065
+ label: label2,
28066
+ agenda,
28067
+ ...footer ? { footer } : {},
28068
+ ...p.bool("progress", false) && mainCount > 1 && !backup[page] ? { progress: before / mainCount } : {}
28069
+ });
28070
+ const sb = ctx.layout(shown2, box.x, box.y, box.w);
28071
+ box.children.push(sb);
28072
+ h2 = sb.h;
28073
+ }
28074
+ const barH = count > 1 ? t2.control.height : 0;
28075
+ const barY = box.y + h2 + (barH ? t2.space.sm : 0);
28076
+ const data2 = { page, count, titles, barY, barH };
28077
+ box.data = data2;
28078
+ box.h = barY - box.y + barH;
28079
+ },
28080
+ semantics(box) {
28081
+ const d = dataOf(box);
28082
+ if (!d || !d.count) return null;
28083
+ const title = d.titles[d.page] || `Slide ${d.page + 1}`;
28084
+ if (d.count <= 1) return { role: "region", roleDescription: "slide deck", name: title, description: `Slide 1 of 1` };
28085
+ return {
28086
+ role: "region",
28087
+ roleDescription: "slide deck",
28088
+ name: title,
28089
+ description: `Slide ${d.page + 1} of ${d.count}`,
28090
+ parts: [
28091
+ { detail: "prev", role: "button", name: "Previous slide", ...d.page <= 0 ? { disabled: true } : {} },
28092
+ ...d.titles.map((tt, i) => ({ detail: `slide:${i}`, role: "button", name: `Slide ${i + 1}${tt ? `: ${tt}` : ""}`, ...i === d.page ? { current: true } : {} })),
28093
+ { detail: "next", role: "button", name: "Next slide", ...d.page >= d.count - 1 ? { disabled: true } : {} }
28094
+ ]
28095
+ };
28096
+ },
28097
+ paint(box, ctx) {
28098
+ const d = dataOf(box);
28099
+ if (!d) return;
28100
+ const shown2 = box.children[0];
28101
+ if (shown2) {
28102
+ const fade = ctx.props(box.node).oneOf("transition", TRANSITIONS, "fade") === "fade";
28103
+ const at2 = fade ? ctx.tween(box.node, "page", d.page, FADE_MS) : d.page;
28104
+ fadeOf.set(shown2.node, Math.min(1, Math.abs(at2 - d.page)));
28105
+ if (d.count > 1) ctx.addHit(partBox(box, shown2.x, shown2.y, shown2.w, shown2.h), { detail: "swipe", focusable: false });
28106
+ }
28107
+ if (!d.barH) return;
28108
+ const { g, theme } = ctx;
28109
+ const c2 = theme.colors;
28110
+ const size = d.barH, y = d.barY;
28111
+ const arrow = (x2, dir, enabled) => {
28112
+ const detail2 = dir === "left" ? "prev" : "next";
28113
+ g.beginPath();
28114
+ g.arc(x2 + size / 2, y + size / 2, size / 2 - 1, 0, Math.PI * 2);
28115
+ if (enabled && ctx.isHovered(box.node, detail2)) fillTint(g, c2.accent, 0.08);
28116
+ g.lineWidth = 1;
28117
+ g.strokeStyle = enabled ? c2.control : c2.line;
28118
+ g.stroke();
28119
+ const icon2 = size * 0.45;
28120
+ drawIcon(g, dir === "left" ? "arrow-left" : "arrow-right", x2 + (size - icon2) / 2, y + (size - icon2) / 2, icon2, enabled ? c2.ink : c2.control);
28121
+ ctx.addHit(partBox(box, x2, y, size, size), { detail: detail2, drags: false });
28122
+ };
28123
+ arrow(box.x, "left", d.page > 0);
28124
+ arrow(box.x + box.w - size, "right", d.page < d.count - 1);
28125
+ const dot = theme.space.sm, gap = theme.space.sm;
28126
+ const wide = dot * 2;
28127
+ const total = (d.count - 1) * (dot + gap) + wide;
28128
+ const room = box.w - size * 2 - gap * 2;
28129
+ if (total > room) return;
28130
+ let x = box.x + box.w / 2 - total / 2;
28131
+ for (let i = 0; i < d.count; i++) {
28132
+ const w2 = i === d.page ? wide : dot;
28133
+ const hovered = ctx.isHovered(box.node, `slide:${i}`);
28134
+ ctx.roundRect(x, y + size / 2 - dot / 2, w2, dot, dot / 2);
28135
+ g.fillStyle = i === d.page ? c2.accent : hovered ? c2.muted : c2.control;
28136
+ g.fill();
28137
+ ctx.addHit(partBox(box, x - gap / 2, y, w2 + gap, size), { detail: `slide:${i}`, drags: false });
28138
+ x += w2 + gap;
28139
+ }
28140
+ },
28141
+ press(ctx) {
28142
+ const d = ctx.target.detail;
28143
+ const node = ctx.target.node;
28144
+ const page = pageOf(ctx.props(node).bound(), countOf.get(node) ?? 1);
28145
+ if (d === "prev") goTo(ctx, page - 1);
28146
+ else if (d === "next") goTo(ctx, page + 1);
28147
+ else if (typeof d === "string" && d.startsWith("slide:")) goTo(ctx, Number(d.slice(6)));
28148
+ },
28149
+ // Only the slide's own area is dragged (the arrows and dots are pressed): a swipe far enough sideways moves a slide.
28150
+ drag(ctx) {
28151
+ const node = ctx.target.node;
28152
+ if (ctx.phase === "start") {
28153
+ swipeFrom.set(node, ctx.x);
28154
+ return;
28155
+ }
28156
+ if (ctx.phase !== "end") return;
28157
+ const from = swipeFrom.get(node);
28158
+ swipeFrom.delete(node);
28159
+ if (from === void 0 || ctx.cancelled) return;
28160
+ const moved = ctx.x - from;
28161
+ if (Math.abs(moved) < SWIPE_DISTANCE) return;
28162
+ const page = pageOf(ctx.props(node).bound(), countOf.get(node) ?? 1);
28163
+ goTo(ctx, moved < 0 ? page + 1 : page - 1);
28164
+ },
28165
+ key(ctx, k2) {
28166
+ const node = ctx.target.node;
28167
+ const count = countOf.get(node) ?? 1;
28168
+ const page = pageOf(ctx.props(node).bound(), count);
28169
+ const to = k2 === "ArrowLeft" ? page - 1 : k2 === "ArrowRight" ? page + 1 : k2 === "Home" ? 0 : k2 === "End" ? count - 1 : null;
28170
+ if (to === null) return false;
28171
+ goTo(ctx, to);
28172
+ return true;
28173
+ }
28174
+ };
28175
+ const slideComponents = [deck, slide];
27577
28176
  const PROFILES = {
27578
28177
  forms: ["card", "row", "text", "divider", "input", "select", "date-picker", "check", "switch", "radio", "stepper", "slider", "button", "link", "badge", "screen"],
27579
28178
  lists: ["card", "row", "grid", "text", "badge", "divider", "list", "list-item", "table", "each", "select", "check", "button", "link", "input", "empty", "progress", "stat"],
@@ -28394,22 +28993,653 @@ ${html}${fence}`;
28394
28993
  const PAGE_REPEAT_TEXT = "An earlier show_interface result already has the page for this exact interface, so there's no new page. Use that one, and don't call show_interface again unless the person asks for a change.";
28395
28994
  const PAGE_DATASETS_TEXT = "This chat app can't draw interfaces, and an interface that loads a dataset (the data argument) can only be shown by an app that can, because the rows never pass through the conversation. So nothing is showing, and there is no page to publish. Tell the person this chat app can't show interfaces with data from the database or imported results, and answer them in text.";
28396
28995
  const pageFixLead = (n2) => `${n2} problem${n2 === 1 ? "" : "s"} leave${n2 === 1 ? "s" : ""} part of this interface wrong or missing, and this chat app can't draw interfaces, so nothing is showing yet. Fix ${n2 === 1 ? "it" : "them"} and call show_interface again with the whole corrected spec; once there's nothing to fix, the result has a page to show the person:`;
28397
- const VERSION = "0.2.1";
28996
+ const WIDGET_MAX_BYTES = 1e6;
28997
+ const WIDGET_KEEP = 50;
28998
+ const WIDGET_FILE = /^sayshape-[0-9a-f]{16}\.html$/;
28999
+ function inertJson(value) {
29000
+ return scriptJson(value).replace(/(l)(ocalStorage)|(s)(essionStorage)|(i)(ndexedDB)|(o)(penDatabase)/gi, (_m, ...g) => {
29001
+ const at2 = [0, 2, 4, 6].find((i) => g[i] !== void 0);
29002
+ return `\\u00${g[at2].charCodeAt(0).toString(16)}${g[at2 + 1]}`;
29003
+ });
29004
+ }
29005
+ const inertSource = (code2) => code2.replace(/<\/(script)/gi, "<\\/$1").replace(/<!--/g, "<\\!--");
29006
+ const NO_UNPACK = "This chat app can't unpack the SayShape engine that draws this interface, so it can't be shown here.";
29007
+ const NO_START = "The SayShape engine didn't start in this chat app, so this interface can't be shown here.";
29008
+ const FONT = "15px/1.5 system-ui,-apple-system,'Segoe UI',sans-serif";
29009
+ function body(o, { id }) {
29010
+ const map2 = usesMap(o.spec);
29011
+ const themes = {
29012
+ light: resolveTheme(o.theme ?? "teal", "light", o.accent ?? null).theme,
29013
+ dark: resolveTheme(o.theme ?? "teal", "dark", o.accent ?? null).theme
29014
+ };
29015
+ if (o.logo) for (const t2 of [themes.light, themes.dark]) t2.deck = { ...t2.deck, logo: o.logo };
29016
+ const packs = [o.engine.engine.base64, ...map2 ? [o.engine.map.base64] : []];
29017
+ const components2 = "S.coreComponents" + (o.scenes ? ".concat(S.sceneComponents)" : "") + (o.slides ? ".concat(S.slideComponents)" : "") + (map2 ? ".concat(window.sayshapeMap ? window.sayshapeMap.mapComponents : [])" : "");
29018
+ const hostScript = o.host === void 0 ? "" : `<script>
29019
+ document.getElementById(${scriptJson(id)}).sayshapeHost = (
29020
+ ${inertSource(o.host)}
29021
+ );
29022
+ <\/script>
29023
+ `;
29024
+ const hosted = o.host === void 0 ? "" : `
29025
+ // A host (a chat app) hooks in here, once the interface is drawn; if it throws, nothing is lost.
29026
+ try { var made = box.sayshapeHost(ui, S, box); if (made && typeof made === "object") hooks = made; } catch (e) {}`;
29027
+ return `<div id="${id}" style="box-sizing:border-box;width:100%;max-width:760px;margin:0 auto;font:${FONT}">
29028
+ <canvas id="${id}-view" aria-label="An interface drawn by SayShape" style="display:block;max-width:100%"></canvas>
29029
+ <p id="${id}-note" hidden style="margin:20px"></p>
29030
+ ${hostScript}<script>
29031
+ (function () {
29032
+ var box = document.getElementById(${scriptJson(id)}), canvas = document.getElementById(${scriptJson(`${id}-view`)}), note = document.getElementById(${scriptJson(`${id}-note`)});
29033
+ var spec = ${inertJson(o.spec)};
29034
+ var themes = ${inertJson(themes)};
29035
+ var packs = ${scriptJson(packs)};
29036
+ var hooks = null;
29037
+ function fail(text) { canvas.style.display = "none"; note.textContent = text; note.hidden = false; }
29038
+ if (!(window.DecompressionStream && window.Blob && window.Response && window.atob && window.URL && URL.createObjectURL)) { fail(${scriptJson(NO_UNPACK)}); return; }
29039
+ // The engine is carried gzipped: unpack it and run it as a blob: script, so nothing is fetched.
29040
+ function load(b64) {
29041
+ var bin = atob(b64), bytes = new Uint8Array(bin.length);
29042
+ for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
29043
+ return new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"))).blob().then(function (code) {
29044
+ return new Promise(function (done, failed) {
29045
+ var url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
29046
+ var script = document.createElement("script");
29047
+ script.onload = function () { URL.revokeObjectURL(url); done(); };
29048
+ script.onerror = function () { URL.revokeObjectURL(url); failed(new Error("script")); };
29049
+ script.src = url;
29050
+ box.appendChild(script);
29051
+ });
29052
+ });
29053
+ }
29054
+ function start() {
29055
+ var S = window.sayshape, root = document.documentElement;
29056
+ if (!S) { fail(${scriptJson(NO_START)}); return; }
29057
+ var components = ${components2};
29058
+ var media = window.matchMedia ? window.matchMedia("(prefers-color-scheme: dark)") : null;
29059
+ function theme() {
29060
+ var chosen = root.getAttribute("data-theme");
29061
+ return chosen === "dark" || (chosen !== "light" && media && media.matches) ? themes.dark : themes.light;
29062
+ }
29063
+ var ui = new S.SayShape(canvas, { components: components, theme: theme(), imageHosts: ${scriptJson(o.imageHosts ?? [])}${o.behavior ? ", behavior: true" : ""} });
29064
+ function apply() {
29065
+ var t = theme();
29066
+ box.style.background = t.colors.surface;
29067
+ box.style.color = t.colors.ink;
29068
+ ui.setTheme(t);
29069
+ }
29070
+ apply();
29071
+ if (media && media.addEventListener) media.addEventListener("change", apply);
29072
+ if (window.MutationObserver) new MutationObserver(apply).observe(root, { attributes: true, attributeFilter: ["data-theme"] });
29073
+ // A link pressed in rich text opens in a new tab, https only, as on any web page. Any other action
29074
+ // goes to the host's emit, if it gave one; otherwise there is no chat to send it to.
29075
+ ui.on("action", function (a) {
29076
+ if (a.name === "link") {
29077
+ var url = null;
29078
+ try { url = new URL(String(a.value)); } catch (e) {}
29079
+ if (url && url.protocol === "https:") window.open(url.href, "_blank", "noopener,noreferrer");
29080
+ return;
29081
+ }
29082
+ if (hooks && typeof hooks.emit === "function") {
29083
+ try { hooks.emit(a); return; } catch (e) {}
29084
+ }
29085
+ ui.notify(${scriptJson(NOTHING_SENT)});
29086
+ });
29087
+ ui.setSpec(spec);${hosted}
29088
+ }
29089
+ var loading = load(packs[0]);
29090
+ for (var n = 1; n < packs.length; n++) loading = loading.then(load.bind(null, packs[n]));
29091
+ loading.then(start).then(null, function () { fail(${scriptJson(NO_START)}); });
29092
+ })();
29093
+ <\/script>
29094
+ </div>
29095
+ `;
29096
+ }
29097
+ function made(o) {
29098
+ const hash = createHash("sha256").update(body(o, { id: "" })).digest("hex");
29099
+ return { html: body(o, { id: `sw-${hash.slice(16, 28)}` }), name: `sayshape-${hash.slice(0, 16)}.html` };
29100
+ }
29101
+ async function writeWidget(dir, o) {
29102
+ const { html, name: name2 } = made(o);
29103
+ const bytes = Buffer.byteLength(html);
29104
+ if (bytes >= WIDGET_MAX_BYTES) {
29105
+ return { ok: false, bytes, reason: `it would be ${Math.round(bytes / 1024)} KB, and a widget has to be under 1 MB${usesMap(o.spec) ? " (the map's outlines are most of it)" : ""}` };
29106
+ }
29107
+ const path2 = resolve(dir, name2);
29108
+ try {
29109
+ await mkdir(dir, { recursive: true });
29110
+ let reused = false;
29111
+ try {
29112
+ reused = (await stat$1(path2)).size === bytes;
29113
+ } catch {
29114
+ }
29115
+ if (reused) {
29116
+ const now = /* @__PURE__ */ new Date();
29117
+ await utimes(path2, now, now);
29118
+ } else {
29119
+ const temp = join(dir, `.${name2}.${process.pid}.tmp`);
29120
+ await writeFile(temp, html);
29121
+ await rename(temp, path2);
29122
+ }
29123
+ await pruneWidgets(dir, WIDGET_KEEP, name2).catch(() => []);
29124
+ return { ok: true, path: path2, bytes, reused };
29125
+ } catch (e) {
29126
+ return { ok: false, reason: `the file couldn't be written to ${dir} (${e instanceof Error ? e.message : String(e)})` };
29127
+ }
29128
+ }
29129
+ async function pruneWidgets(dir, keep = WIDGET_KEEP, current) {
29130
+ const mine = [];
29131
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
29132
+ if (!entry.isFile() || !WIDGET_FILE.test(entry.name) || entry.name === current) continue;
29133
+ try {
29134
+ mine.push({ name: entry.name, at: (await stat$1(join(dir, entry.name))).mtimeMs });
29135
+ } catch {
29136
+ }
29137
+ }
29138
+ mine.sort((a, b) => b.at - a.at || (a.name < b.name ? 1 : -1));
29139
+ const removed = [];
29140
+ for (const old of mine.slice(Math.max(0, keep - (current ? 1 : 0)))) {
29141
+ try {
29142
+ await unlink(join(dir, old.name));
29143
+ removed.push(old.name);
29144
+ } catch {
29145
+ }
29146
+ }
29147
+ return removed;
29148
+ }
29149
+ function widgetText(path2, bytes) {
29150
+ return `This chat app can't draw interfaces itself, but it can show a widget made from a file, and the file for this interface is ready:
29151
+ ${path2}
29152
+ Create the widget from that file exactly as it is. Don't read it and don't edit it: it carries the whole engine (about ${Math.round(bytes / 1024)} KB), which would fill your context for nothing. Don't call show_interface again unless the person asks for a change.`;
29153
+ }
29154
+ const PRESSES_SAVED = "on=emit:name saves a press for your next turn: this chat app can't send it to you as it happens. After the person's next message, read the widget's state: its actions list holds what they pressed (name, value, time) and its state holds the interface's values. Don't wait for a press; also update the screen in the same on=, e.g. on=set:sel:{x.name};emit:pick:{x.name}.";
29155
+ const PRESSES_SAVED_RESULT = "This interface has buttons that use emit:. Presses are saved for your next turn, not sent now: after the person's next message, read the widget's state, where its actions list holds what they pressed.";
29156
+ const widgetFixLead = (n2) => `${n2} problem${n2 === 1 ? "" : "s"} leave${n2 === 1 ? "s" : ""} part of this interface wrong or missing, and this chat app can't draw interfaces, so nothing is showing yet. Fix ${n2 === 1 ? "it" : "them"} and call show_interface again with the whole corrected spec; once there's nothing to fix, the result names a file to make a widget from:`;
29157
+ const WIDGET_REPEAT_TEXT = "An earlier show_interface result already named the file for this exact interface, so there's no new file. Use that one, and don't call show_interface again unless the person asks for a change.";
29158
+ const widgetFailedText = (reason) => `The interface is written correctly, but this chat app can't draw interfaces and no file could be made for it: ${reason}. So nothing is showing. Tell the person, and answer them in text or with a smaller interface.`;
29159
+ const STATE_LIMIT = 8192;
29160
+ function museAdapter(ui, S, root, options) {
29161
+ const MUSE = {
29162
+ bridge: "hatchWidget",
29163
+ stateEvent: "hatch-widget-state",
29164
+ cssPrefix: "--hatch-widget-",
29165
+ colors: ["bg", "surface", "surface-muted", "text", "muted", "border", "accent", "on-accent", "focus", "shadow"]
29166
+ };
29167
+ const NOTICE = "Saved. Send a message to continue.";
29168
+ const o = options || {};
29169
+ const stateLimit = typeof o.stateLimit === "number" ? o.stateLimit : 8192;
29170
+ const saveEvery = typeof o.saveEvery === "number" ? o.saveEvery : 500;
29171
+ const maxActions = typeof o.maxActions === "number" ? o.maxActions : 20;
29172
+ const host = globalThis;
29173
+ const cleanups = [];
29174
+ const listen2 = (type, fn) => {
29175
+ if (typeof host.addEventListener !== "function") return;
29176
+ host.addEventListener(type, fn);
29177
+ cleanups.push(() => host.removeEventListener && host.removeEventListener(type, fn));
29178
+ };
29179
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
29180
+ const toJson = (v) => {
29181
+ try {
29182
+ const s = JSON.stringify(v);
29183
+ return s === void 0 ? null : JSON.parse(s);
29184
+ } catch (e) {
29185
+ return null;
29186
+ }
29187
+ };
29188
+ const bytes = (s) => host.TextEncoder ? new host.TextEncoder().encode(s).length : s.length;
29189
+ const passwordPaths = () => {
29190
+ const out = [];
29191
+ let unknown = false;
29192
+ const IDENT = /^[A-Za-z_]\w*(\.[A-Za-z_]\w*)*$/;
29193
+ const resolve2 = (raw, vars) => {
29194
+ if (raw === void 0) return null;
29195
+ const path2 = raw.trim().replace(/^\{\s*([\s\S]*?)\s*\}$/, "$1");
29196
+ if (!IDENT.test(path2)) return null;
29197
+ const parts = path2.split(".");
29198
+ const first2 = parts[0];
29199
+ if (Object.prototype.hasOwnProperty.call(vars, first2)) {
29200
+ const base2 = vars[first2];
29201
+ return base2 ? base2.concat(parts.slice(1)) : null;
29202
+ }
29203
+ if (ui.state.isDerived(first2)) return null;
29204
+ return parts;
29205
+ };
29206
+ const walk = (n2, vars) => {
29207
+ let inner = vars;
29208
+ if (n2.type === "each") {
29209
+ const list2 = resolve2(n2.props.items, vars);
29210
+ inner = Object.assign({}, vars);
29211
+ inner[n2.props.as || "item"] = list2 ? list2.concat(["*"]) : null;
29212
+ if (n2.props.index) inner[n2.props.index] = null;
29213
+ }
29214
+ const kind = n2.props.kind;
29215
+ if (n2.type === "input" && kind !== void 0 && (kind.trim() === "password" || kind.indexOf("{") >= 0)) {
29216
+ const where = n2.props.bind === void 0 ? [] : resolve2(n2.props.bind, vars);
29217
+ if (where === null) unknown = true;
29218
+ else if (where.length) out.push(where);
29219
+ }
29220
+ for (const c2 of n2.children) walk(c2, inner);
29221
+ };
29222
+ if (ui.tree) walk(ui.tree, {});
29223
+ return unknown ? null : out;
29224
+ };
29225
+ const scrub = (value, paths2, found) => {
29226
+ const visit = (at2, path2, i) => {
29227
+ const step2 = path2[i];
29228
+ if (step2 === void 0 || at2 === null || typeof at2 !== "object") return;
29229
+ const last2 = i === path2.length - 1;
29230
+ const keys = step2 === "*" ? Array.isArray(at2) ? at2.map((_x, k2) => k2) : [] : [step2];
29231
+ for (const k2 of keys) {
29232
+ const holder = at2;
29233
+ const v = holder[k2];
29234
+ if (v === void 0) continue;
29235
+ if (!last2) {
29236
+ visit(v, path2, i + 1);
29237
+ continue;
29238
+ }
29239
+ if (typeof v === "string" && v) found.push(v);
29240
+ if (i === 0) delete holder[k2];
29241
+ else holder[k2] = "";
29242
+ }
29243
+ };
29244
+ for (const p of paths2) visit(value, p, 0);
29245
+ };
29246
+ const bridge = host[MUSE.bridge];
29247
+ const hasBridge = !!bridge && typeof bridge.getState === "function" && typeof bridge.setState === "function";
29248
+ const spec = (() => {
29249
+ const text2 = ui.spec;
29250
+ let h2 = 2166136261;
29251
+ for (let i = 0; i < text2.length; i++) {
29252
+ h2 ^= text2.charCodeAt(i);
29253
+ h2 = Math.imul(h2, 16777619) >>> 0;
29254
+ }
29255
+ return ("0000000" + h2.toString(16)).slice(-8) + "-" + text2.length;
29256
+ })();
29257
+ const defaults = { spec, state: null, actions: [] };
29258
+ let current = defaults;
29259
+ let saved = "null";
29260
+ const recent = [];
29261
+ let ready = false;
29262
+ let applying = false;
29263
+ let dirty = false;
29264
+ let timer = null;
29265
+ let lastWrite = -Infinity;
29266
+ const waiting = [];
29267
+ const statePart = () => {
29268
+ const paths2 = passwordPaths();
29269
+ const value = toJson(ui.state.snapshot());
29270
+ if (!isObj(value)) return { json: "null", value: null, passwords: [] };
29271
+ if (!paths2) return { json: "password", value: null, note: "Not saved: the interface has a password field", passwords: null };
29272
+ const passwords = [];
29273
+ scrub(value, paths2, passwords);
29274
+ const json = JSON.stringify(value);
29275
+ if (bytes(json) > stateLimit) return { json, value: null, note: "Not saved: larger than " + stateLimit + " bytes", passwords };
29276
+ return { json, value, passwords };
29277
+ };
29278
+ const write = (next2) => {
29279
+ if (!bridge) return;
29280
+ try {
29281
+ bridge.setState(next2);
29282
+ } catch (e) {
29283
+ return;
29284
+ }
29285
+ current = next2;
29286
+ recent.push(JSON.stringify(next2.state === void 0 ? null : next2.state));
29287
+ if (recent.length > 8) recent.shift();
29288
+ lastWrite = Date.now();
29289
+ };
29290
+ const withState = (part2, extra) => {
29291
+ const next2 = Object.assign({}, current, { spec, state: part2.value }, extra || {});
29292
+ if (part2.note) next2.stateNote = part2.note;
29293
+ else delete next2.stateNote;
29294
+ return next2;
29295
+ };
29296
+ const saveNow = () => {
29297
+ if (timer !== null) {
29298
+ clearTimeout(timer);
29299
+ timer = null;
29300
+ }
29301
+ const part2 = statePart();
29302
+ if (part2.json === saved && current.spec === spec) return;
29303
+ saved = part2.json;
29304
+ write(withState(part2));
29305
+ };
29306
+ const scheduleSave = () => {
29307
+ if (!hasBridge || applying) return;
29308
+ if (!ready) {
29309
+ dirty = true;
29310
+ return;
29311
+ }
29312
+ if (timer !== null) return;
29313
+ timer = setTimeout(() => {
29314
+ timer = null;
29315
+ saveNow();
29316
+ }, Math.max(0, lastWrite + saveEvery - Date.now()));
29317
+ };
29318
+ const apply2 = (state) => {
29319
+ if (!isObj(state)) return;
29320
+ const now = ui.state.snapshot();
29321
+ applying = true;
29322
+ try {
29323
+ for (const key of Object.keys(state)) {
29324
+ if (JSON.stringify(now[key]) === JSON.stringify(state[key])) continue;
29325
+ try {
29326
+ ui.state.set(key, state[key]);
29327
+ } catch (e) {
29328
+ }
29329
+ }
29330
+ } finally {
29331
+ applying = false;
29332
+ }
29333
+ };
29334
+ const adopt = (st) => {
29335
+ current = isObj(st) ? st : defaults;
29336
+ if (current.spec === spec) {
29337
+ apply2(current.state === void 0 ? null : current.state);
29338
+ saved = JSON.stringify(current.state === void 0 ? null : current.state);
29339
+ } else {
29340
+ saved = "\0";
29341
+ }
29342
+ };
29343
+ const record2 = (action) => {
29344
+ const part2 = statePart();
29345
+ let value = toJson(action.value === void 0 ? null : action.value);
29346
+ if (part2.passwords === null) value = null;
29347
+ else if (part2.passwords.length) {
29348
+ const hide = (v) => {
29349
+ if (typeof v === "string") return part2.passwords && part2.passwords.indexOf(v) >= 0 ? "" : v;
29350
+ if (Array.isArray(v)) return v.map(hide);
29351
+ if (isObj(v)) {
29352
+ const r = {};
29353
+ for (const k2 of Object.keys(v)) r[k2] = hide(v[k2]);
29354
+ return r;
29355
+ }
29356
+ return v;
29357
+ };
29358
+ value = hide(value);
29359
+ }
29360
+ if (bytes(JSON.stringify(value)) > stateLimit / 4) value = null;
29361
+ const list2 = Array.isArray(current.actions) ? current.actions.slice() : [];
29362
+ list2.push({ name: action.name, value, at: (/* @__PURE__ */ new Date()).toISOString() });
29363
+ while (list2.length > maxActions) list2.shift();
29364
+ if (timer !== null) {
29365
+ clearTimeout(timer);
29366
+ timer = null;
29367
+ }
29368
+ saved = part2.json;
29369
+ write(withState(part2, { actions: list2 }));
29370
+ };
29371
+ const begin = (st) => {
29372
+ if (ready) return;
29373
+ adopt(st);
29374
+ ready = true;
29375
+ for (const a of waiting.splice(0)) record2(a);
29376
+ if (dirty || current.spec !== spec) {
29377
+ dirty = false;
29378
+ scheduleSave();
29379
+ }
29380
+ };
29381
+ if (hasBridge && bridge) {
29382
+ cleanups.push(ui.on("change", () => scheduleSave()));
29383
+ listen2(MUSE.stateEvent, (e) => {
29384
+ const detail2 = e.detail;
29385
+ const st = isObj(detail2) ? detail2.state : void 0;
29386
+ if (!isObj(st)) return;
29387
+ if (!ready) {
29388
+ begin(st);
29389
+ return;
29390
+ }
29391
+ if (recent.indexOf(JSON.stringify(st.state === void 0 ? null : st.state)) >= 0) return;
29392
+ adopt(st);
29393
+ });
29394
+ let got;
29395
+ try {
29396
+ got = bridge.getState(defaults);
29397
+ } catch (e) {
29398
+ got = void 0;
29399
+ }
29400
+ if (got && typeof got.then === "function") {
29401
+ got.then(begin, () => begin(void 0));
29402
+ } else {
29403
+ begin(got);
29404
+ }
29405
+ }
29406
+ if (!o.ignoreAppColors) {
29407
+ const fromMessage = {};
29408
+ const rgb2 = (v) => {
29409
+ const s = (v || "").trim().toLowerCase();
29410
+ let m = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(s);
29411
+ if (m) {
29412
+ let h2 = m[1];
29413
+ if (h2.length === 3) h2 = h2.split("").map((c22) => c22 + c22).join("");
29414
+ if (h2.length === 8 && h2.slice(6) !== "ff") return null;
29415
+ return [parseInt(h2.slice(0, 2), 16), parseInt(h2.slice(2, 4), 16), parseInt(h2.slice(4, 6), 16)];
29416
+ }
29417
+ m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:\s*[,/]\s*([\d.]+)(%?))?\s*\)$/.exec(s);
29418
+ if (!m) return null;
29419
+ if (m[4] !== void 0 && Number(m[4]) < (m[5] ? 100 : 1)) return null;
29420
+ const c2 = [Number(m[1]), Number(m[2]), Number(m[3])];
29421
+ return c2.every((x) => Number.isFinite(x) && x <= 255) ? c2 : null;
29422
+ };
29423
+ const hex = (c2) => "#" + c2.map((x) => ("0" + Math.max(0, Math.min(255, Math.round(x))).toString(16)).slice(-2)).join("");
29424
+ const color2 = (v) => {
29425
+ const c2 = rgb2(v);
29426
+ return c2 ? hex(c2) : null;
29427
+ };
29428
+ const lum = (v) => {
29429
+ const c2 = rgb2(v) || [0, 0, 0];
29430
+ const lin = (x) => {
29431
+ const s = x / 255;
29432
+ return s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
29433
+ };
29434
+ return 0.2126 * lin(c2[0]) + 0.7152 * lin(c2[1]) + 0.0722 * lin(c2[2]);
29435
+ };
29436
+ const contrast2 = (a, b) => {
29437
+ const x = lum(a), y = lum(b);
29438
+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);
29439
+ };
29440
+ const mix2 = (a, b, t2) => {
29441
+ const x = rgb2(a) || [0, 0, 0], y = rgb2(b) || [0, 0, 0];
29442
+ return hex([x[0] + (y[0] - x[0]) * t2, x[1] + (y[1] - x[1]) * t2, x[2] + (y[2] - x[2]) * t2]);
29443
+ };
29444
+ const readable = (want, backs, min) => {
29445
+ const ok = (c2) => backs.every((b) => contrast2(c2, b) >= min);
29446
+ if (ok(want)) return want;
29447
+ const toward = lum(backs[0]) > 0.18 ? "#0b0f14" : "#ffffff";
29448
+ let lo = 0, hi = 1;
29449
+ for (let i = 0; i < 24; i++) {
29450
+ const t2 = (lo + hi) / 2;
29451
+ if (ok(mix2(want, toward, t2))) hi = t2;
29452
+ else lo = t2;
29453
+ }
29454
+ let out = mix2(want, toward, hi);
29455
+ for (let t2 = hi; !ok(out) && t2 < 1; t2 = Math.min(1, t2 + 0.01)) out = mix2(want, toward, t2);
29456
+ return out;
29457
+ };
29458
+ const read2 = () => {
29459
+ const out = {};
29460
+ const doc2 = host.document;
29461
+ const el = root && typeof root === "object" ? root : doc2 && doc2.documentElement;
29462
+ let style = null;
29463
+ try {
29464
+ style = el && typeof host.getComputedStyle === "function" ? host.getComputedStyle(el) : null;
29465
+ } catch (e) {
29466
+ style = null;
29467
+ }
29468
+ for (const name2 of MUSE.colors) {
29469
+ const v = fromMessage[name2] || (style ? style.getPropertyValue(MUSE.cssPrefix + name2) : "");
29470
+ if (v && v.trim()) out[name2] = v.trim();
29471
+ }
29472
+ return out;
29473
+ };
29474
+ const themeOf = (c2) => {
29475
+ const surface = color2(c2.bg);
29476
+ const text2 = color2(c2.text);
29477
+ if (!surface || !text2) return null;
29478
+ const dark = lum(surface) < 0.18;
29479
+ const base2 = dark ? S.darkTheme : S.lightTheme;
29480
+ const raised = color2(c2.surface) || (dark ? mix2(surface, text2, 0.045) : surface);
29481
+ const backs = [surface, raised];
29482
+ const ink = readable(text2, backs, 4.5);
29483
+ const accent = readable(color2(c2.accent) || base2.colors.accent, backs, 4.5);
29484
+ const onWanted = color2(c2["on-accent"]);
29485
+ const onAccent = onWanted && contrast2(onWanted, accent) >= 4.5 ? onWanted : contrast2(accent, "#ffffff") >= contrast2(accent, "#0b0f14") ? "#ffffff" : "#0b0f14";
29486
+ const colors = {
29487
+ surface,
29488
+ raised,
29489
+ ink,
29490
+ muted: readable(color2(c2.muted) || mix2(ink, surface, 0.35), backs, 4.5),
29491
+ line: color2(c2.border) || mix2(ink, surface, 0.82),
29492
+ control: readable(color2(c2.border) || mix2(ink, surface, 0.55), backs, 3),
29493
+ accent,
29494
+ accent2: accent,
29495
+ onAccent,
29496
+ series1: accent,
29497
+ focus: readable(color2(c2.focus) || accent, backs, 3),
29498
+ good: readable(base2.colors.good, backs, 4.5),
29499
+ warn: readable(base2.colors.warn, backs, 4.5),
29500
+ bad: readable(base2.colors.bad, backs, 4.5)
29501
+ };
29502
+ return S.extendTheme(base2, { name: base2.name + " (app)", colors });
29503
+ };
29504
+ let shown2 = "";
29505
+ const update = () => {
29506
+ try {
29507
+ const c2 = read2();
29508
+ const key = JSON.stringify(c2);
29509
+ if (key === shown2) return;
29510
+ const theme = themeOf(c2);
29511
+ if (!theme) return;
29512
+ shown2 = key;
29513
+ ui.setTheme(theme);
29514
+ } catch (e) {
29515
+ }
29516
+ };
29517
+ listen2("message", (e) => {
29518
+ const data2 = e.data;
29519
+ const vars = isObj(data2) ? data2.cssVariables : void 0;
29520
+ if (!isObj(vars)) return;
29521
+ for (const k2 of Object.keys(vars)) {
29522
+ const v = vars[k2];
29523
+ const name2 = k2.replace(/^--/, "").replace(/^hatch-widget-/, "");
29524
+ if (typeof v === "string" && MUSE.colors.indexOf(name2) >= 0) fromMessage[name2] = v;
29525
+ }
29526
+ update();
29527
+ });
29528
+ const doc = host.document;
29529
+ if (host.MutationObserver && doc) {
29530
+ try {
29531
+ const watch = new host.MutationObserver(update);
29532
+ if (doc.documentElement) watch.observe(doc.documentElement, { attributes: true });
29533
+ if (doc.head) watch.observe(doc.head, { childList: true, subtree: true, characterData: true });
29534
+ cleanups.push(() => watch.disconnect());
29535
+ } catch (e) {
29536
+ }
29537
+ }
29538
+ for (const ms of [0, 250, 1e3, 3e3]) {
29539
+ const t2 = setTimeout(update, ms);
29540
+ cleanups.push(() => clearTimeout(t2));
29541
+ }
29542
+ }
29543
+ return {
29544
+ emit(action) {
29545
+ if (!hasBridge) return;
29546
+ const a = typeof action === "string" ? { name: action } : { name: String(action && action.name), value: action && action.value };
29547
+ if (!ready) waiting.push(a);
29548
+ else record2(a);
29549
+ ui.notify(NOTICE);
29550
+ },
29551
+ destroy() {
29552
+ if (timer !== null) {
29553
+ clearTimeout(timer);
29554
+ timer = null;
29555
+ }
29556
+ for (const f of cleanups.splice(0)) {
29557
+ try {
29558
+ f();
29559
+ } catch (e) {
29560
+ }
29561
+ }
29562
+ }
29563
+ };
29564
+ }
29565
+ const MUSE_SOURCE = museAdapter.toString();
29566
+ const WIDGET_HOSTS = {
29567
+ muse: { title: "Muse", source: MUSE_SOURCE }
29568
+ };
29569
+ function isWidgetHost(name2) {
29570
+ return Object.prototype.hasOwnProperty.call(WIDGET_HOSTS, name2);
29571
+ }
29572
+ function adapterSource(name2, options = {}) {
29573
+ const num2 = (v, fallback) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : fallback;
29574
+ const settings = {
29575
+ ignoreAppColors: options.ignoreAppColors === true,
29576
+ stateLimit: num2(options.stateLimit, STATE_LIMIT),
29577
+ saveEvery: num2(options.saveEvery),
29578
+ maxActions: num2(options.maxActions)
29579
+ };
29580
+ const json = JSON.stringify(settings);
29581
+ return `function (ui, S, root) { return (${WIDGET_HOSTS[name2].source})(ui, S, root, ${json}); }`;
29582
+ }
29583
+ const WIDGET_HOST_NAMES = Object.keys(WIDGET_HOSTS);
29584
+ function widgetHostRefusal(name2, hasDir) {
29585
+ const valid = `Hosts: ${WIDGET_HOST_NAMES.join(", ")}.`;
29586
+ if (name2 === void 0 || name2.startsWith("--")) return `--widget-host needs the name of a chat app. ${valid}`;
29587
+ if (!isWidgetHost(name2)) return `--widget-host doesn't know "${name2}". ${valid}`;
29588
+ if (!hasDir) return "--widget-host only applies with --widget-dir: it hooks an adapter into the widget files that flag writes.";
29589
+ return null;
29590
+ }
29591
+ const isScript = (v) => {
29592
+ const s = v;
29593
+ return !!s && typeof s.base64 === "string" && typeof s.digest === "string" && typeof s.bytes === "number" && typeof s.gzipBytes === "number";
29594
+ };
29595
+ const LOCATIONS = [new URL("./widget-engine.json", import.meta.url), new URL("../dist/widget-engine.json", import.meta.url)];
29596
+ let cache = null;
29597
+ function loadPackedEngine() {
29598
+ return cache ??= (async () => {
29599
+ for (const url of LOCATIONS) {
29600
+ let raw;
29601
+ try {
29602
+ raw = await readFile(fileURLToPath(url), "utf8");
29603
+ } catch {
29604
+ continue;
29605
+ }
29606
+ const parsed2 = JSON.parse(raw);
29607
+ if (isScript(parsed2.engine) && isScript(parsed2.map)) return { engine: parsed2.engine, map: parsed2.map };
29608
+ throw new Error("widget-engine.json isn't what this version of sayshape-mcp writes: run `npm run build` again.");
29609
+ }
29610
+ throw new Error("widget-engine.json is missing, so --widget-dir has no engine to put in its files: run `npm run build` in the sayshape-mcp package.");
29611
+ })().catch((e) => {
29612
+ cache = null;
29613
+ throw e;
29614
+ });
29615
+ }
29616
+ const VERSION = "0.2.2";
28398
29617
  const UI_URI = "ui://sayshape/interface.html";
28399
29618
  const MAX_SPEC_CHARS = 2e4;
28400
29619
  const MAX_REPORTED = 12;
28401
29620
  let components = [...coreComponents, ...mapComponents];
28402
29621
  let registry = new Registry(components);
28403
29622
  let scenesOn = false;
29623
+ let slidesOn = false;
28404
29624
  let behaviorOn = false;
28405
29625
  let imageHosts = [];
28406
29626
  const sectionsCache = /* @__PURE__ */ new Map();
28407
29627
  function setScenes(on) {
28408
- components = [...coreComponents, ...mapComponents, ...on ? sceneComponents : []];
28409
- registry = new Registry(components);
28410
29628
  scenesOn = on;
29629
+ register();
29630
+ }
29631
+ function setSlides(on) {
29632
+ slidesOn = on;
29633
+ register();
29634
+ }
29635
+ function register() {
29636
+ components = [...coreComponents, ...mapComponents, ...scenesOn ? sceneComponents : [], ...slidesOn ? slideComponents : []];
29637
+ registry = new Registry(components);
28411
29638
  sectionsCache.clear();
28412
29639
  }
29640
+ const behaviorFor = (textOnly, fileMode) => behaviorOn && (!textOnly || fileMode);
29641
+ const PAGE_DECK_TEXT = "The deck is written correctly, but this app can't show slide decks yet, so there is no page to open. Tell the person it needs a chat app that draws SayShape views.";
29642
+ const usesDeck = (spec) => /^\s*deck\b/m.test(spec);
28413
29643
  function setBehavior(on) {
28414
29644
  behaviorOn = on;
28415
29645
  sectionsCache.clear();
@@ -28421,10 +29651,11 @@ function setImageHosts(hosts) {
28421
29651
  function imageCsp(hosts) {
28422
29652
  return hosts.length ? { resourceDomains: hosts.map((h2) => `https://${h2}`) } : void 0;
28423
29653
  }
29654
+ const CHAT_EMIT = 'When the person should be able to send something back to you (a choice, a form, an approval), give it a button with on=emit:name, for example on=emit:submit_order. The chat shows a short line like "Submit order", and you also receive the exact action name, its value and every state value; reply to it, or call show_interface again with an updated spec.';
28424
29655
  const CHAT_NOTES = `You are writing an interface that appears inside a chat conversation, in a narrow column about 600 pixels wide.
28425
29656
  Keep it to one focused screen: a card or column with a title, then the content. Prefer row and grid for side-by-side numbers; avoid more than three columns.
28426
29657
  Put the data you know straight into state (lists of records for tables, charts and each). Never claim data is live: if numbers come from your own knowledge, say so in a caption.
28427
- When the person should be able to send something back to you (a choice, a form, an approval), give it a button with on=emit:name, for example on=emit:submit_order. The chat shows a short line like "Submit order", and you also receive the exact action name, its value and every state value; reply to it, or call show_interface again with an updated spec.
29658
+ ${CHAT_EMIT}
28428
29659
  Output only the spec in show_interface's spec argument, with no Markdown fences.`;
28429
29660
  const DATA_NOTES = `DATA FROM THE DATABASE
28430
29661
  - Look at the tables with describe_data, then get exactly the rows you need with query_data (one SELECT). Do the work in SQL: GROUP BY, SUM, COUNT, ORDER BY, LIMIT. A query keeps at most 500 rows.
@@ -28442,20 +29673,21 @@ function sectionsOf(mode) {
28442
29673
  return sections;
28443
29674
  }
28444
29675
  const sectionText = (mode, name2) => sectionsOf(mode).find((sec) => sec.name === name2)?.text ?? "";
28445
- function topics(withData, withMcp = false, textOnly = false) {
29676
+ function topics(withData, withMcp = false, textOnly = false, fileMode = false, pressesSaved = false) {
29677
+ const emitLine = textOnly ? pressesSaved ? PRESSES_SAVED : NO_EMIT : CHAT_EMIT;
28446
29678
  return {
28447
29679
  expressions: sectionText("full", "expressions"),
28448
29680
  actions: sectionText("full", "actions"),
28449
- ...behaviorOn && !textOnly ? { behavior: sectionText("full", "behavior") } : {},
29681
+ ...behaviorFor(textOnly, fileMode) ? { behavior: sectionText("full", "behavior") } : {},
28450
29682
  lists: sectionText("full", "data"),
28451
29683
  rules: sectionText("full", "rules"),
28452
29684
  examples: sectionText("full", "example"),
28453
- chat: CHAT_NOTES.split("\n").slice(1).join("\n"),
29685
+ chat: CHAT_NOTES.split("\n").slice(1).map((line2) => line2 === CHAT_EMIT ? emitLine : line2).join("\n"),
28454
29686
  ...withData ? { database: DATA_NOTES } : {},
28455
29687
  ...withMcp ? { datasets: MCP_NOTES } : {}
28456
29688
  };
28457
29689
  }
28458
- function quickStart(withData = false, withMcp = false, textOnly = false) {
29690
+ function quickStart(withData = false, withMcp = false, textOnly = false, fileMode = false, pressesSaved = false) {
28459
29691
  return [
28460
29692
  "QUICK START",
28461
29693
  // The guide's "not JavaScript" line is left out to keep this short: show_interface returns
@@ -28464,9 +29696,9 @@ function quickStart(withData = false, withMcp = false, textOnly = false) {
28464
29696
  sectionText("compact", "format").replace(/^FORMAT\n/, "").replace(/^- Not JavaScript:.*\n/m, "").replace(/\n- # starts a comment\.$/m, ""),
28465
29697
  '- Text and props show state: text "Total: {money(total)}"; actions run on press: button "Add" on=inc:count',
28466
29698
  `- Any element takes tip="…": a short explanation shown on hover, focus or a tap: for a term or a number some people won't know, instead of more words on screen.`,
28467
- textOnly ? `- ${NO_EMIT}` : "- on=emit:pick:{x.name} sends a choice to you; no handler blocks. Also update the screen: on=set:sel:{x.name};emit:pick:{x.name}",
29699
+ textOnly ? `- ${pressesSaved ? PRESSES_SAVED : NO_EMIT}` : "- on=emit:pick:{x.name} sends a choice to you; no handler blocks. Also update the screen: on=set:sel:{x.name};emit:pick:{x.name}",
28468
29700
  `- Functions (no others exist): ${EXPRESSION_FUNCTIONS.join(", ")}. The best row: first(sort(rows, 'revenue', 'desc')).month; a total: sum(rows, 'revenue'); within a budget: filter(rows, 'price', {to: budget})`,
28469
- ...behaviorOn && !textOnly ? [sectionText("compact", "behavior")] : [],
29701
+ ...behaviorFor(textOnly, fileMode) ? [sectionText("compact", "behavior")] : [],
28470
29702
  `ELEMENTS
28471
29703
  ${elementIndex(components.filter((c2) => !arrivesWithParent(c2)))}`,
28472
29704
  // The same heading as the guides', in fewer words: this text goes out with every call.
@@ -28476,7 +29708,8 @@ ${elementIndex(components.filter((c2) => !arrivesWithParent(c2)))}`,
28476
29708
  `${PICKS_HEADING_SHORT}
28477
29709
  ${pickList(components).replace(/, such as [^:\n]*(?=: )/g, "").replace(/ \((?![^)\n]*=)[^)\n]*\)(?=: )/g, "")}`,
28478
29710
  "IN A CHAT: one card with a title; about 600px wide. Use grid min=140 for side-by-side figures; caption estimated numbers.",
28479
- `BEFORE YOU USE AN ELEMENT the first time, get its props and an example from sayshape_docs (elements: ["chart", "table"]). Topics: ${Object.keys(topics(withData, withMcp, textOnly)).join(", ")}.`,
29711
+ ...slidesOn ? ["A PRESENTATION: a deck at the top level, not inside a card; a slide per idea, its title in the slide's own text."] : [],
29712
+ `BEFORE YOU USE AN ELEMENT the first time, get its props and an example from sayshape_docs (elements: ["chart", "table"]). Topics: ${Object.keys(topics(withData, withMcp, textOnly, fileMode)).join(", ")}.`,
28480
29713
  ...withMcp ? [`Imported results: call list_datasets for available ids and fields. Pass data={"rows":"m1"} to show_interface; don't put dataset rows in spec.`] : []
28481
29714
  ].join("\n");
28482
29715
  }
@@ -28486,11 +29719,11 @@ function arrivesWithParent(c2) {
28486
29719
  return Array.isArray(parent?.children) && parent.children.includes(c2.type);
28487
29720
  });
28488
29721
  }
28489
- function docsText(elements, topicNames, withData = false, withMcp = false, textOnly = false) {
29722
+ function docsText(elements, topicNames, withData = false, withMcp = false, textOnly = false, fileMode = false, pressesSaved = false) {
28490
29723
  const parts = [];
28491
- const t2 = topics(withData, withMcp, textOnly);
29724
+ const t2 = topics(withData, withMcp, textOnly, fileMode, pressesSaved);
28492
29725
  if (elements.length) {
28493
- const { text: text2, unknown } = elementGuide(registry, elements, { behavior: behaviorOn && !textOnly });
29726
+ const { text: text2, unknown } = elementGuide(registry, elements, { behavior: behaviorFor(textOnly, fileMode) });
28494
29727
  if (text2) parts.push(`ELEMENTS
28495
29728
  ${text2}`);
28496
29729
  if (imageHosts.length && elements.includes("image")) parts.push(sectionText("compact", "images"));
@@ -28498,10 +29731,10 @@ ${text2}`);
28498
29731
  ${elementIndex(components)}`);
28499
29732
  }
28500
29733
  for (const name2 of topicNames) {
28501
- const body = t2[name2];
28502
- parts.push(body ? body : `No topic called ${name2}. Topics: ${Object.keys(t2).join(", ")}.`);
29734
+ const body2 = t2[name2];
29735
+ parts.push(body2 ? body2 : `No topic called ${name2}. Topics: ${Object.keys(t2).join(", ")}.`);
28503
29736
  }
28504
- return parts.length ? parts.join("\n\n") : quickStart(withData, withMcp, textOnly);
29737
+ return parts.length ? parts.join("\n\n") : quickStart(withData, withMcp, textOnly, fileMode, pressesSaved);
28505
29738
  }
28506
29739
  function elementsOnLines(spec, diagnostics, max = 3) {
28507
29740
  const lines = spec.split("\n");
@@ -28529,8 +29762,8 @@ function emitProblems(spec, hostNames = []) {
28529
29762
  walk(parse(spec, registry, { knownNames: hostNames }).root);
28530
29763
  return out;
28531
29764
  }
28532
- function checkSpec(spec, hostNames = [], textOnly = false) {
28533
- const behavior = behaviorOn && !textOnly;
29765
+ function checkSpec(spec, hostNames = [], textOnly = false, fileMode = false) {
29766
+ const behavior = behaviorFor(textOnly, fileMode);
28534
29767
  const parsed2 = parse(spec, registry, { knownNames: hostNames, ...behavior ? { behavior } : {} });
28535
29768
  const { diagnostics } = parsed2;
28536
29769
  return {
@@ -28541,7 +29774,7 @@ function checkSpec(spec, hostNames = [], textOnly = false) {
28541
29774
  }
28542
29775
  const HARMLESS = /has no prop "|is a weight, not a style|doesn't take quoted text; it was ignored/;
28543
29776
  const isHarmless = (d) => d.severity !== "error" && HARMLESS.test(d.message);
28544
- function describeCheck(c2, textOnly = false) {
29777
+ function describeCheck(c2, textOnly = false, fileMode = false, widget = "") {
28545
29778
  const all = [...c2.errors, ...c2.warnings];
28546
29779
  const drawing = c2.drawing.map((d) => `line ${d.line}: ${d.message.replace(/^Drawing: /, "")}`);
28547
29780
  if (textOnly) {
@@ -28549,18 +29782,18 @@ function describeCheck(c2, textOnly = false) {
28549
29782
  if (fix2.length) {
28550
29783
  const listed2 = [...fix2, ...all.filter(isHarmless)].slice(0, MAX_REPORTED).map((d) => `line ${d.line} (${isHarmless(d) ? "ignored" : d.severity}): ${d.message}`);
28551
29784
  if (all.length > MAX_REPORTED) listed2.push(`…and ${all.length - MAX_REPORTED} more.`);
28552
- return `${pageFixLead(fix2.length)}
29785
+ return `${fileMode ? widgetFixLead(fix2.length) : pageFixLead(fix2.length)}
28553
29786
  ${listed2.join("\n")}${drawing.length ? `
28554
29787
  Also tidy the drawing:
28555
29788
  ${drawing.join("\n")}` : ""}`;
28556
29789
  }
28557
29790
  const minor2 = all.map((d) => `line ${d.line} (ignored): ${d.message}`);
28558
29791
  return [
28559
- PAGE_TEXT,
29792
+ fileMode ? widget : PAGE_TEXT,
28560
29793
  ...minor2.length ? [`The parser ignored these small things, which change nothing on the page:
28561
29794
  ${minor2.join("\n")}`] : [],
28562
29795
  // A scene's drawing problems don't hold the page back: some, like small text on a phone, may not be worth another call.
28563
- ...drawing.length ? [`Its drawing has problems the person can see. If you fix them, call show_interface again and use the new page instead:
29796
+ ...drawing.length ? [`Its drawing has problems the person can see. If you fix them, call show_interface again and use the new ${fileMode ? "file" : "page"} instead:
28564
29797
  ${drawing.join("\n")}`] : []
28565
29798
  ].join("\n");
28566
29799
  }
@@ -28600,6 +29833,11 @@ function createServer(opts) {
28600
29833
  const hasDatasets = !!data2 || !!mcpResults;
28601
29834
  const findDataset = (id) => id.startsWith("m") ? mcpResults?.get(id) : data2?.get(id);
28602
29835
  const now = opts.now ?? Date.now;
29836
+ const widgetDir = opts.widgetDir;
29837
+ const widgetEngine = opts.widgetEngine ?? loadPackedEngine;
29838
+ const fileModeFor = (textOnly) => textOnly && widgetDir !== void 0;
29839
+ const hostSource = widgetDir !== void 0 && opts.widgetHost ? adapterSource(opts.widgetHost.name, { ignoreAppColors: opts.widgetHost.ignoreAppColors === true }) : void 0;
29840
+ const pressesSavedFor = (textOnly) => fileModeFor(textOnly) && hostSource !== void 0;
28603
29841
  let lastGood = null;
28604
29842
  const server = new McpServer(
28605
29843
  { name: "sayshape", title: "SayShape", version: VERSION },
@@ -28618,9 +29856,12 @@ function createServer(opts) {
28618
29856
  },
28619
29857
  annotations: { readOnlyHint: true, openWorldHint: false }
28620
29858
  },
28621
- async ({ elements, topics: names }) => text(docsText(elements ?? [], names ?? [], !!data2, !!mcpResults, cannotDrawViews(server)))
29859
+ async ({ elements, topics: names }) => {
29860
+ const textOnly = cannotDrawViews(server);
29861
+ return text(docsText(elements ?? [], names ?? [], !!data2, !!mcpResults, textOnly, fileModeFor(textOnly), pressesSavedFor(textOnly)));
29862
+ }
28622
29863
  );
28623
- const showDescription = (textOnly) => (textOnly ? "Draws an interactive interface from a spec you write, with the SayShape engine. This chat app can't show it in the conversation, so when the spec has nothing to fix the result gives you a small web page that draws it, to publish or save for the person. Use it for every visual or interactive answer (charts, tables, dashboards, stat cards, forms, calculators, trackers) rather than writing HTML, React, SVG or chart code. Specs can't run code or choose colors. " : "Shows an interactive interface inside the conversation, drawn by the SayShape engine from a spec you write. Use it for every visual or interactive answer (charts, tables, dashboards, stat cards, forms, calculators, trackers) rather than writing HTML, React, SVG or chart code, or making an artifact. Specs can't run code or choose colors. ") + "The result lists lines the parser skipped, with the docs for those elements, so you can fix them." + (data2 ? ' To show rows from the database, pass data={"name": "d1"} with a dataset id from query_data and use that name in the spec (items=name).' : "") + (mcpResults ? " For imported MCP results, call list_datasets then pass the selected id in data. The model never needs the full rows." : "") + "\n\n" + quickStart(!!data2, !!mcpResults, textOnly);
29864
+ const showDescription = (textOnly) => (textOnly ? "Draws an interactive interface from a spec you write, with the SayShape engine. This chat app can't show it in the conversation, " + (fileModeFor(textOnly) ? "so when the spec has nothing to fix the result gives you the path of a file that draws it, to create a widget from for the person. " : "so when the spec has nothing to fix the result gives you a small web page that draws it, to publish or save for the person. ") + "Use it for every visual or interactive answer (charts, tables, dashboards, stat cards, forms, calculators, trackers) rather than writing HTML, React, SVG or chart code. Specs can't run code or choose colors. " : "Shows an interactive interface inside the conversation, drawn by the SayShape engine from a spec you write. Use it for every visual or interactive answer (charts, tables, dashboards, stat cards, forms, calculators, trackers) rather than writing HTML, React, SVG or chart code, or making an artifact. Specs can't run code or choose colors. ") + "The result lists lines the parser skipped, with the docs for those elements, so you can fix them." + (data2 ? ' To show rows from the database, pass data={"name": "d1"} with a dataset id from query_data and use that name in the spec (items=name).' : "") + (mcpResults ? " For imported MCP results, call list_datasets then pass the selected id in data. The model never needs the full rows." : "") + "\n\n" + quickStart(!!data2, !!mcpResults, textOnly, fileModeFor(textOnly), pressesSavedFor(textOnly));
28624
29865
  const showTool = registerAppTool(
28625
29866
  server,
28626
29867
  "show_interface",
@@ -28650,8 +29891,11 @@ function createServer(opts) {
28650
29891
  }
28651
29892
  const names = Object.keys(datasets);
28652
29893
  const textOnly = cannotDrawViews(server);
28653
- const parsed2 = checkSpec(spec, names, textOnly);
28654
- const check2 = textOnly ? { ...parsed2, errors: [...parsed2.errors, ...emitProblems(spec, names)].sort((a, b) => a.line - b.line) } : parsed2;
29894
+ const fileMode = fileModeFor(textOnly);
29895
+ const parsed2 = checkSpec(spec, names, textOnly, fileMode);
29896
+ const saved = pressesSavedFor(textOnly);
29897
+ const emits = textOnly ? emitProblems(spec, names) : [];
29898
+ const check2 = textOnly && !saved ? { ...parsed2, errors: [...parsed2.errors, ...emits].sort((a, b) => a.line - b.line) } : parsed2;
28655
29899
  const declared = names.filter((n2) => new RegExp(`^state\\b[^\\n]*\\b${n2}=`, "m").test(spec));
28656
29900
  const notes = [
28657
29901
  ...names.length ? [`Loaded into the interface: ${names.map((n2) => `${n2} (${datasets[n2].id}, ${datasets[n2].rows} rows)`).join(", ")}.`] : [],
@@ -28663,7 +29907,7 @@ function createServer(opts) {
28663
29907
  if (toFix === 0) lastGood = { key, at: now() };
28664
29908
  if (textOnly) {
28665
29909
  if (names.length) return text(PAGE_DATASETS_TEXT);
28666
- if (repeat) return text(PAGE_REPEAT_TEXT);
29910
+ if (repeat) return text(fileMode ? WIDGET_REPEAT_TEXT : PAGE_REPEAT_TEXT);
28667
29911
  }
28668
29912
  if (repeat) {
28669
29913
  return {
@@ -28675,9 +29919,33 @@ function createServer(opts) {
28675
29919
  if (failing.length) notes.push(`
28676
29920
  Docs for ${failing.join(", ")}:
28677
29921
  ${elementGuide(registry, failing).text}`);
28678
- const withPage = textOnly && toFix === 0;
29922
+ const deckOnly = textOnly && !fileMode && toFix === 0 && slidesOn && usesDeck(spec);
29923
+ const withPage = textOnly && !fileMode && toFix === 0 && !deckOnly;
29924
+ if (deckOnly) notes.push(PAGE_DECK_TEXT);
28679
29925
  if (withPage) notes.push(fenced(fallbackPage({ spec, title, scenes: scenesOn })));
28680
- const said = [describeCheck(check2, textOnly), ...notes].join("\n");
29926
+ let widget = "";
29927
+ if (fileMode && toFix === 0) {
29928
+ try {
29929
+ const written = await writeWidget(widgetDir, {
29930
+ spec,
29931
+ engine: await widgetEngine(),
29932
+ scenes: scenesOn,
29933
+ behavior: behaviorOn,
29934
+ slides: slidesOn,
29935
+ imageHosts,
29936
+ ...hostSource !== void 0 ? { host: hostSource } : {},
29937
+ ...opts.view?.theme ? { theme: opts.view.theme } : {},
29938
+ ...opts.view?.accent ? { accent: opts.view.accent } : {},
29939
+ ...opts.view?.logo ? { logo: opts.view.logo } : {}
29940
+ });
29941
+ widget = written.ok ? widgetText(written.path, written.bytes) + (saved && emits.length ? ` ${PRESSES_SAVED_RESULT}` : "") : widgetFailedText(written.reason);
29942
+ if (!written.ok) lastGood = null;
29943
+ } catch (e) {
29944
+ widget = widgetFailedText(e instanceof Error ? e.message : String(e));
29945
+ lastGood = null;
29946
+ }
29947
+ }
29948
+ const said = [describeCheck(check2, textOnly, fileMode, widget), ...notes].join("\n");
28681
29949
  if (textOnly) return text(said);
28682
29950
  return {
28683
29951
  content: [{ type: "text", text: said }],
@@ -28913,9 +30181,9 @@ function createHttp(makeServer, options, limits = LIMITS, now = Date.now) {
28913
30181
  const first2 = limiter?.take(who, 1);
28914
30182
  if (first2 && !first2.ok) return refuse(res, first2.retryAfterSeconds);
28915
30183
  try {
28916
- const body = await readJson(req);
28917
- if (limiter && Array.isArray(body) && body.length > 1) {
28918
- const rest = limiter.take(who, body.length - 1);
30184
+ const body2 = await readJson(req);
30185
+ if (limiter && Array.isArray(body2) && body2.length > 1) {
30186
+ const rest = limiter.take(who, body2.length - 1);
28919
30187
  if (!rest.ok) return refuse(res, rest.retryAfterSeconds);
28920
30188
  }
28921
30189
  const server = makeServer();
@@ -28925,7 +30193,7 @@ function createHttp(makeServer, options, limits = LIMITS, now = Date.now) {
28925
30193
  void server.close();
28926
30194
  });
28927
30195
  await server.connect(transport);
28928
- await transport.handleRequest(req, res, body);
30196
+ await transport.handleRequest(req, res, body2);
28929
30197
  } catch {
28930
30198
  jsonError(res, 400, "Bad request");
28931
30199
  }
@@ -28974,9 +30242,14 @@ async function main() {
28974
30242
  "Usage: sayshape-mcp [--data database.db] [--mcp-result result.json ...]",
28975
30243
  " [--http [port] [--host address] [--rate-limit n] [--trust-proxy [hops]] [--allow-public-data]]",
28976
30244
  " [--theme-picker] [--theme teal|purple|blue|neutral|studio] [--accent color]",
28977
- " [--no-save-image] [--no-copy-text] [--scene] [--behavior]",
28978
- " [--image-hosts host1,host2,...]",
30245
+ " [--no-save-image] [--no-copy-text] [--scene] [--behavior] [--slides] [--logo <https url>]",
30246
+ " [--image-hosts host1,host2,...] [--widget-dir folder [--widget-host name]]",
28979
30247
  "",
30248
+ " --widget-dir <folder> for chat apps that can't draw interfaces but can show a widget made from a file:",
30249
+ " write each interface there as one self-contained file, named by a hash of the",
30250
+ " spec and settings (the newest 50 are kept); stdio only, refused with --http",
30251
+ ` --widget-host <name> with --widget-dir: hook a chat app's adapter into each file so emit: presses and the`,
30252
+ " interface's state are saved for the model's next turn; hosts: " + WIDGET_HOST_NAMES.join(", "),
28980
30253
  " --http [port] Streamable HTTP on /mcp instead of stdio; port from the flag, else PORT, else 3001",
28981
30254
  " --host <address> where to listen: 127.0.0.1 by default, else HOST if it's an IP address;",
28982
30255
  " 0.0.0.0 to take requests from other machines (behind an HTTPS proxy)",
@@ -28993,6 +30266,8 @@ async function main() {
28993
30266
  " --no-save-image hide the Save image button (shown where the chat app can download files)",
28994
30267
  " --no-copy-text hide the Copy text button",
28995
30268
  " --scene experimental: scenes, pictures and animations the model paints (off by default)",
30269
+ " --slides experimental: slide decks, a deck of 16:9 slides shown one at a time (off by default)",
30270
+ " --logo <url> with --slides: an https image drawn small in the corner of every slide (its host is allowed like --image-hosts)",
28996
30271
  " --behavior experimental: rules that tick (timers, simulations) and, with --scene, dragging (off by default)",
28997
30272
  " --image-hosts hosts images may load from, comma-separated; *.example.com allows its subdomains",
28998
30273
  " (none by default; https only, and the host must send CORS headers)"
@@ -29003,8 +30278,34 @@ async function main() {
29003
30278
  for (const note of accentNotes(view)) console.error(`SayShape: ${note}`);
29004
30279
  setScenes(view.scene === true);
29005
30280
  setBehavior(view.behavior === true);
30281
+ setSlides(view.slides === true);
29006
30282
  setImageHosts(view.imageHosts ?? []);
29007
30283
  const httpAt = args.indexOf("--http");
30284
+ const widgetAt = args.indexOf("--widget-dir");
30285
+ let widgetDir;
30286
+ const hostAt = args.indexOf("--widget-host");
30287
+ let widgetHost;
30288
+ if (hostAt >= 0) {
30289
+ const refusal2 = widgetHostRefusal(args[hostAt + 1], widgetAt >= 0);
30290
+ if (refusal2) throw new Error(refusal2);
30291
+ const name2 = args[hostAt + 1];
30292
+ if (name2 === void 0 || !isWidgetHost(name2)) throw new Error("unreachable: widgetHostRefusal checked the name");
30293
+ widgetHost = name2;
30294
+ }
30295
+ if (widgetAt >= 0) {
30296
+ if (httpAt >= 0) throw new Error("--widget-dir can't be used with --http: it writes files on this computer for a chat app on this computer to read, and an HTTP server's callers can't read them.");
30297
+ const raw = args[widgetAt + 1];
30298
+ if (!raw || raw.startsWith("--")) throw new Error("--widget-dir needs the folder to write widget files into.");
30299
+ widgetDir = resolve(raw);
30300
+ try {
30301
+ await mkdir(widgetDir, { recursive: true });
30302
+ await access(widgetDir, constants.W_OK);
30303
+ } catch (e) {
30304
+ throw new Error(`--widget-dir ${widgetDir} can't be written to: ${e instanceof Error ? e.message : String(e)}`);
30305
+ }
30306
+ await loadPackedEngine();
30307
+ console.error(`SayShape: chat apps that can't draw interfaces get a widget file in ${widgetDir}${widgetHost ? `, hooked to ${widgetHost}` : ""}`);
30308
+ }
29008
30309
  if (httpAt < 0) {
29009
30310
  for (const flag of ["--host", "--rate-limit", "--trust-proxy", "--allow-public-data"]) {
29010
30311
  if (args.includes(flag)) throw new Error(`${flag} only applies with --http.`);
@@ -29050,7 +30351,7 @@ async function main() {
29050
30351
  console.error(startupLine(http.options, port));
29051
30352
  return;
29052
30353
  }
29053
- await logClient(createServer({ uiHtml, data: data2, mcpResults, view })).connect(new StdioServerTransport());
30354
+ await logClient(createServer({ uiHtml, data: data2, mcpResults, view, ...widgetDir ? { widgetDir } : {}, ...widgetHost ? { widgetHost: { name: widgetHost, ignoreAppColors: args.includes("--theme") || args.includes("--accent") } } : {} })).connect(new StdioServerTransport());
29054
30355
  }
29055
30356
  main().catch((e) => {
29056
30357
  console.error(e instanceof Error ? e.message : e);