@crvouga/mockingbird-service-aha 1.4.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -533,10 +533,10 @@ var OpenAPIReferenceError = class extends Error {
533
533
  };
534
534
  var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
535
535
  var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
536
- var resolveRef = (document2, ref) => {
536
+ var resolveRef = (document3, ref) => {
537
537
  if (!ref.startsWith("#/"))
538
538
  throw new OpenAPIReferenceError(ref);
539
- let cursor = document2;
539
+ let cursor = document3;
540
540
  for (const raw of ref.slice(2).split("/")) {
541
541
  const segment = unescapePointer(raw);
542
542
  if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
@@ -548,14 +548,14 @@ var resolveRef = (document2, ref) => {
548
548
  throw new OpenAPIReferenceError(ref);
549
549
  return cursor;
550
550
  };
551
- var deref = (document2, value) => {
551
+ var deref = (document3, value) => {
552
552
  let current = value;
553
553
  const seen = /* @__PURE__ */ new Set();
554
554
  while (isReference(current)) {
555
555
  if (seen.has(current.$ref))
556
556
  throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
557
557
  seen.add(current.$ref);
558
- current = resolveRef(document2, current.$ref);
558
+ current = resolveRef(document3, current.$ref);
559
559
  }
560
560
  return current;
561
561
  };
@@ -573,36 +573,36 @@ var HTTP_METHODS = [
573
573
  ];
574
574
 
575
575
  // ../../openapi/core/dist/document.js
576
- var mergeParameters = (document2, item, own) => {
576
+ var mergeParameters = (document3, item, own) => {
577
577
  const merged = /* @__PURE__ */ new Map();
578
578
  for (const raw of item.parameters ?? []) {
579
- const parameter = deref(document2, raw);
579
+ const parameter = deref(document3, raw);
580
580
  merged.set(`${parameter.in}:${parameter.name}`, parameter);
581
581
  }
582
582
  for (const raw of own ?? []) {
583
- const parameter = deref(document2, raw);
583
+ const parameter = deref(document3, raw);
584
584
  merged.set(`${parameter.in}:${parameter.name}`, parameter);
585
585
  }
586
586
  return [...merged.values()];
587
587
  };
588
- var listOperations = (document2) => {
588
+ var listOperations = (document3) => {
589
589
  const operations = [];
590
- for (const [path, item] of Object.entries(document2.paths)) {
590
+ for (const [path, item] of Object.entries(document3.paths)) {
591
591
  for (const method of HTTP_METHODS) {
592
592
  const operation = item[method];
593
593
  if (operation?.operationId === void 0)
594
594
  continue;
595
595
  const responses = {};
596
596
  for (const [status, response] of Object.entries(operation.responses)) {
597
- responses[status] = deref(document2, response);
597
+ responses[status] = deref(document3, response);
598
598
  }
599
599
  operations.push({
600
600
  operationId: operation.operationId,
601
601
  method,
602
602
  path,
603
603
  operation,
604
- parameters: mergeParameters(document2, item, operation.parameters),
605
- requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
604
+ parameters: mergeParameters(document3, item, operation.parameters),
605
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document3, operation.requestBody),
606
606
  responses
607
607
  });
608
608
  }
@@ -611,7 +611,7 @@ var listOperations = (document2) => {
611
611
  };
612
612
 
613
613
  // ../../openapi/core/dist/schema.js
614
- var resolveSchema = (document2, schema) => {
614
+ var resolveSchema = (document3, schema) => {
615
615
  let current = schema;
616
616
  const seen = /* @__PURE__ */ new Set();
617
617
  while (typeof current.$ref === "string") {
@@ -620,7 +620,7 @@ var resolveSchema = (document2, schema) => {
620
620
  break;
621
621
  seen.add(ref);
622
622
  const { $ref: _ignored, ...siblings } = current;
623
- const target = resolveRef(document2, ref);
623
+ const target = resolveRef(document3, ref);
624
624
  current = { ...target, ...siblings };
625
625
  }
626
626
  if (current.nullable === true) {
@@ -691,9 +691,9 @@ var FORMAT_PATTERNS = {
691
691
  ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
692
692
  };
693
693
  var graphemeLength = (value) => [...value].length;
694
- var validateValue = (document2, schema, value, path = []) => {
694
+ var validateValue = (document3, schema, value, path = []) => {
695
695
  const errors = [];
696
- const s = resolveSchema(document2, schema);
696
+ const s = resolveSchema(document3, schema);
697
697
  const fail2 = (message) => errors.push({ path, message });
698
698
  const actual = jsonTypeOf(value);
699
699
  if (actual === "undefined") {
@@ -755,7 +755,7 @@ var validateValue = (document2, schema, value, path = []) => {
755
755
  value.forEach((item, i) => {
756
756
  const itemSchema = s.prefixItems?.[i] ?? s.items;
757
757
  if (itemSchema)
758
- errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
758
+ errors.push(...validateValue(document3, itemSchema, item, [...path, i]));
759
759
  });
760
760
  }
761
761
  if (actual === "object") {
@@ -771,16 +771,16 @@ var validateValue = (document2, schema, value, path = []) => {
771
771
  for (const key2 of keys) {
772
772
  const property = s.properties?.[key2];
773
773
  if (property) {
774
- errors.push(...validateValue(document2, property, record2[key2], [...path, key2]));
774
+ errors.push(...validateValue(document3, property, record2[key2], [...path, key2]));
775
775
  continue;
776
776
  }
777
777
  if (s.additionalProperties === false)
778
778
  fail2(`unexpected property ${key2}`);
779
779
  else if (typeof s.additionalProperties === "object") {
780
- errors.push(...validateValue(document2, s.additionalProperties, record2[key2], [...path, key2]));
780
+ errors.push(...validateValue(document3, s.additionalProperties, record2[key2], [...path, key2]));
781
781
  }
782
782
  if (s.propertyNames) {
783
- const nameErrors = validateValue(document2, s.propertyNames, key2, [...path, key2]);
783
+ const nameErrors = validateValue(document3, s.propertyNames, key2, [...path, key2]);
784
784
  if (nameErrors.length > 0)
785
785
  fail2(`property name ${key2} is invalid: ${nameErrors[0]?.message}`);
786
786
  }
@@ -788,15 +788,15 @@ var validateValue = (document2, schema, value, path = []) => {
788
788
  }
789
789
  if (s.allOf)
790
790
  for (const branch of s.allOf)
791
- errors.push(...validateValue(document2, branch, value, path));
792
- if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
791
+ errors.push(...validateValue(document3, branch, value, path));
792
+ if (s.anyOf && !s.anyOf.some((branch) => validateValue(document3, branch, value).length === 0))
793
793
  fail2("matches no anyOf branch");
794
794
  if (s.oneOf) {
795
- const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
795
+ const matches2 = s.oneOf.filter((branch) => validateValue(document3, branch, value).length === 0).length;
796
796
  if (matches2 !== 1)
797
797
  fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
798
798
  }
799
- if (s.not && validateValue(document2, s.not, value).length === 0)
799
+ if (s.not && validateValue(document3, s.not, value).length === 0)
800
800
  fail2("matches forbidden `not` schema");
801
801
  return errors;
802
802
  };
@@ -1389,6 +1389,1232 @@ var clearNamespace = (sqlite, namespace) => {
1389
1389
  });
1390
1390
  };
1391
1391
 
1392
+ // ../../ui/dist/reset.js
1393
+ var CSS_RESET = `*,
1394
+ *::before,
1395
+ *::after {
1396
+ box-sizing: border-box;
1397
+ margin: 0;
1398
+ padding: 0;
1399
+ }
1400
+
1401
+ * {
1402
+ scrollbar-width: thin;
1403
+ scrollbar-color: color-mix(in srgb, CanvasText 35%, Canvas) Canvas;
1404
+ }
1405
+
1406
+ *::-webkit-scrollbar {
1407
+ width: 12px;
1408
+ height: 12px;
1409
+ }
1410
+
1411
+ *::-webkit-scrollbar-track,
1412
+ *::-webkit-scrollbar-corner {
1413
+ background: Canvas;
1414
+ }
1415
+
1416
+ *::-webkit-scrollbar-thumb {
1417
+ background: color-mix(in srgb, CanvasText 35%, Canvas);
1418
+ border: 3px solid Canvas;
1419
+ border-radius: 999px;
1420
+ }
1421
+
1422
+ html {
1423
+ hanging-punctuation: first allow-end last;
1424
+ -webkit-text-size-adjust: none;
1425
+ text-size-adjust: none;
1426
+ tab-size: 4;
1427
+ font-family:
1428
+ ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI",
1429
+ "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
1430
+ font-size: 16px;
1431
+ line-height: 1.5;
1432
+ -webkit-font-smoothing: antialiased;
1433
+ -moz-osx-font-smoothing: grayscale;
1434
+ text-rendering: optimizeLegibility;
1435
+ -webkit-tap-highlight-color: transparent;
1436
+ scroll-behavior: smooth;
1437
+ background: Canvas;
1438
+ color: CanvasText;
1439
+ }
1440
+
1441
+ body {
1442
+ min-height: 100svh;
1443
+ line-height: 1.5;
1444
+ background: Canvas;
1445
+ color: CanvasText;
1446
+ }
1447
+
1448
+ h1 {
1449
+ font-size: 2em;
1450
+ }
1451
+
1452
+ h2 {
1453
+ font-size: 1.5em;
1454
+ }
1455
+
1456
+ h3 {
1457
+ font-size: 1.17em;
1458
+ }
1459
+
1460
+ h4 {
1461
+ font-size: 1em;
1462
+ }
1463
+
1464
+ h5 {
1465
+ font-size: 0.83em;
1466
+ }
1467
+
1468
+ h6 {
1469
+ font-size: 0.67em;
1470
+ }
1471
+
1472
+ h1,
1473
+ h2,
1474
+ h3,
1475
+ h4,
1476
+ h5,
1477
+ h6 {
1478
+ font-weight: 700;
1479
+ line-height: 1.2;
1480
+ text-wrap: balance;
1481
+ overflow-wrap: break-word;
1482
+ }
1483
+
1484
+ p,
1485
+ li,
1486
+ figcaption,
1487
+ dd,
1488
+ dt,
1489
+ blockquote {
1490
+ overflow-wrap: break-word;
1491
+ }
1492
+
1493
+ p,
1494
+ li,
1495
+ figcaption,
1496
+ blockquote {
1497
+ text-wrap: pretty;
1498
+ }
1499
+
1500
+ ul,
1501
+ ol,
1502
+ menu {
1503
+ list-style: none;
1504
+ }
1505
+
1506
+ a {
1507
+ color: inherit;
1508
+ text-decoration: underline;
1509
+ text-decoration-thickness: 1px;
1510
+ text-underline-offset: 0.15em;
1511
+ text-decoration-skip-ink: auto;
1512
+ }
1513
+
1514
+ b,
1515
+ strong {
1516
+ font-weight: 700;
1517
+ }
1518
+
1519
+ small {
1520
+ font-size: 0.875em;
1521
+ }
1522
+
1523
+ code,
1524
+ kbd,
1525
+ samp,
1526
+ pre {
1527
+ font-family: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1528
+ font-size: 1em;
1529
+ }
1530
+
1531
+ sub,
1532
+ sup {
1533
+ font-size: 75%;
1534
+ line-height: 0;
1535
+ position: relative;
1536
+ vertical-align: baseline;
1537
+ }
1538
+
1539
+ sub {
1540
+ bottom: -0.25em;
1541
+ }
1542
+
1543
+ sup {
1544
+ top: -0.5em;
1545
+ }
1546
+
1547
+ abbr[title] {
1548
+ text-decoration: underline dotted;
1549
+ text-underline-offset: 0.15em;
1550
+ }
1551
+
1552
+ mark {
1553
+ background: Mark;
1554
+ color: MarkText;
1555
+ }
1556
+
1557
+ hr {
1558
+ height: 0;
1559
+ border: 0;
1560
+ border-top: 1px solid color-mix(in srgb, CanvasText 20%, transparent);
1561
+ color: inherit;
1562
+ }
1563
+
1564
+ img,
1565
+ picture,
1566
+ video,
1567
+ canvas {
1568
+ display: block;
1569
+ max-width: 100%;
1570
+ }
1571
+
1572
+ img,
1573
+ video {
1574
+ height: auto;
1575
+ }
1576
+
1577
+ svg {
1578
+ overflow: hidden;
1579
+ }
1580
+
1581
+ iframe {
1582
+ border: 0;
1583
+ max-width: 100%;
1584
+ }
1585
+
1586
+ table {
1587
+ border-collapse: collapse;
1588
+ border-spacing: 0;
1589
+ }
1590
+
1591
+ fieldset {
1592
+ border: 0;
1593
+ min-inline-size: 0;
1594
+ }
1595
+
1596
+ legend {
1597
+ padding: 0;
1598
+ }
1599
+
1600
+ button,
1601
+ input,
1602
+ select,
1603
+ textarea,
1604
+ optgroup {
1605
+ font: inherit;
1606
+ letter-spacing: inherit;
1607
+ color: inherit;
1608
+ margin: 0;
1609
+ vertical-align: middle;
1610
+ }
1611
+
1612
+ button,
1613
+ input[type="button"],
1614
+ input[type="submit"],
1615
+ input[type="reset"] {
1616
+ appearance: none;
1617
+ background: none;
1618
+ border: 0;
1619
+ padding: 0;
1620
+ cursor: pointer;
1621
+ text-align: center;
1622
+ }
1623
+
1624
+ input,
1625
+ textarea,
1626
+ select {
1627
+ background-color: Canvas;
1628
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1629
+ border-radius: 0;
1630
+ padding: 0.5em 0.65em;
1631
+ }
1632
+
1633
+ input[type="checkbox"],
1634
+ input[type="radio"],
1635
+ input[type="range"],
1636
+ input[type="file"],
1637
+ input[type="color"],
1638
+ input[type="button"],
1639
+ input[type="submit"],
1640
+ input[type="reset"],
1641
+ input[type="image"],
1642
+ input[type="hidden"] {
1643
+ background: none;
1644
+ border: 0;
1645
+ padding: 0;
1646
+ border-radius: 0;
1647
+ }
1648
+
1649
+ input[type="checkbox"],
1650
+ input[type="radio"] {
1651
+ accent-color: CanvasText;
1652
+ }
1653
+
1654
+ input[type="search"] {
1655
+ appearance: none;
1656
+ background-color: Canvas;
1657
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1658
+ }
1659
+
1660
+ input[type="search"]::-webkit-search-decoration,
1661
+ input[type="search"]::-webkit-search-cancel-button,
1662
+ input[type="search"]::-webkit-search-results-button,
1663
+ input[type="search"]::-webkit-search-results-decoration {
1664
+ -webkit-appearance: none;
1665
+ display: none;
1666
+ }
1667
+
1668
+ input[type="number"] {
1669
+ appearance: textfield;
1670
+ background-color: Canvas;
1671
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1672
+ }
1673
+
1674
+ input[type="number"]::-webkit-inner-spin-button,
1675
+ input[type="number"]::-webkit-outer-spin-button {
1676
+ -webkit-appearance: none;
1677
+ margin: 0;
1678
+ }
1679
+
1680
+ textarea {
1681
+ resize: vertical;
1682
+ }
1683
+
1684
+ ::placeholder {
1685
+ opacity: 1;
1686
+ color: color-mix(in srgb, CanvasText 45%, transparent);
1687
+ }
1688
+
1689
+ :focus-visible {
1690
+ outline: 2px solid CanvasText;
1691
+ outline-offset: 2px;
1692
+ }
1693
+
1694
+ :focus:not(:focus-visible) {
1695
+ outline: none;
1696
+ }
1697
+
1698
+ :disabled,
1699
+ [disabled] {
1700
+ cursor: default;
1701
+ opacity: 0.6;
1702
+ }
1703
+
1704
+ label,
1705
+ summary,
1706
+ select,
1707
+ [role="button"] {
1708
+ cursor: pointer;
1709
+ }
1710
+
1711
+ summary {
1712
+ display: list-item;
1713
+ }
1714
+
1715
+ details {
1716
+ display: block;
1717
+ }
1718
+
1719
+ dialog {
1720
+ margin: auto;
1721
+ padding: 1rem;
1722
+ border: 1px solid color-mix(in srgb, CanvasText 20%, transparent);
1723
+ background: Canvas;
1724
+ color: CanvasText;
1725
+ max-width: calc(100vw - 2rem);
1726
+ max-height: calc(100svh - 2rem);
1727
+ }
1728
+
1729
+ dialog:not([open]) {
1730
+ display: none;
1731
+ }
1732
+
1733
+ ::backdrop {
1734
+ background: color-mix(in srgb, CanvasText 40%, transparent);
1735
+ }
1736
+
1737
+ [hidden] {
1738
+ display: none !important;
1739
+ }
1740
+
1741
+ ::selection {
1742
+ background: Highlight;
1743
+ color: HighlightText;
1744
+ }
1745
+
1746
+ @media (prefers-reduced-motion: reduce) {
1747
+ *,
1748
+ *::before,
1749
+ *::after {
1750
+ animation-duration: 0.01ms !important;
1751
+ animation-iteration-count: 1 !important;
1752
+ transition-duration: 0.01ms !important;
1753
+ scroll-behavior: auto !important;
1754
+ }
1755
+ }
1756
+
1757
+ @media (pointer: coarse) {
1758
+ input,
1759
+ select,
1760
+ textarea {
1761
+ font-size: max(16px, 1em);
1762
+ }
1763
+ }`;
1764
+
1765
+ // ../core/dist/admin-client.js
1766
+ function isRecord2(value) {
1767
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1768
+ }
1769
+ function mountAdminBrand(doc, host, service, catalog) {
1770
+ const clip = (value, max) => {
1771
+ if (typeof value !== "string")
1772
+ return null;
1773
+ const trimmed = value.trim();
1774
+ if (trimmed === "")
1775
+ return null;
1776
+ return trimmed.length > max ? trimmed.slice(0, max) : trimmed;
1777
+ };
1778
+ const httpUrl = (value) => {
1779
+ if (typeof value !== "string" || value.length > 2e3)
1780
+ return null;
1781
+ try {
1782
+ const url = new URL(value);
1783
+ if (url.protocol !== "https:" && url.protocol !== "http:")
1784
+ return null;
1785
+ return url.href;
1786
+ } catch {
1787
+ return null;
1788
+ }
1789
+ };
1790
+ const hexColor = (value) => {
1791
+ if (typeof value !== "string")
1792
+ return null;
1793
+ const raw = value.trim();
1794
+ return /^#[0-9a-fA-F]{3,8}$/.test(raw) ? raw : null;
1795
+ };
1796
+ const hostname = (value) => {
1797
+ try {
1798
+ return new URL(value).hostname.replace(/^www\./, "");
1799
+ } catch {
1800
+ return value;
1801
+ }
1802
+ };
1803
+ host.replaceChildren();
1804
+ host.hidden = true;
1805
+ if (!isRecord2(catalog) || !Object.hasOwn(catalog, service))
1806
+ return;
1807
+ const row = catalog[service];
1808
+ if (!isRecord2(row))
1809
+ return;
1810
+ const vendor = clip(row.vendor, 80);
1811
+ const website = httpUrl(row.website);
1812
+ const guide = httpUrl(row.guide);
1813
+ const docs = httpUrl(row.docs);
1814
+ const logo = httpUrl(row.logo);
1815
+ const color = hexColor(row.color);
1816
+ const description = clip(row.description, 280);
1817
+ if (vendor === null || website === null && guide === null && docs === null)
1818
+ return;
1819
+ const add = (node) => {
1820
+ host.append(node);
1821
+ return node;
1822
+ };
1823
+ if (logo !== null) {
1824
+ const img = doc.createElement("img");
1825
+ img.alt = "";
1826
+ img.src = logo;
1827
+ img.width = 16;
1828
+ img.height = 16;
1829
+ img.decoding = "async";
1830
+ img.referrerPolicy = "no-referrer";
1831
+ if (color !== null)
1832
+ img.style.borderColor = color;
1833
+ add(img);
1834
+ }
1835
+ const name = doc.createElement("span");
1836
+ name.className = "vendor-name";
1837
+ name.textContent = vendor;
1838
+ if (description !== null)
1839
+ name.title = description;
1840
+ add(name);
1841
+ const sep = () => {
1842
+ const node = doc.createElement("span");
1843
+ node.className = "vendor-sep";
1844
+ node.setAttribute("aria-hidden", "true");
1845
+ node.textContent = "\xB7";
1846
+ return node;
1847
+ };
1848
+ const link = (href, label, title) => {
1849
+ const node = doc.createElement("a");
1850
+ node.className = "vendor-link";
1851
+ node.href = href;
1852
+ node.target = "_blank";
1853
+ node.rel = "noopener noreferrer";
1854
+ node.referrerPolicy = "no-referrer";
1855
+ node.textContent = label;
1856
+ node.title = title;
1857
+ return node;
1858
+ };
1859
+ if (website !== null) {
1860
+ add(sep());
1861
+ add(link(website, hostname(website), `${vendor} website`));
1862
+ }
1863
+ if (guide !== null) {
1864
+ add(sep());
1865
+ add(link(guide, "Docs", `Docs for ${vendor}`));
1866
+ }
1867
+ if (docs !== null) {
1868
+ add(sep());
1869
+ add(link(docs, "API", `${vendor} API reference`));
1870
+ }
1871
+ host.removeAttribute("hidden");
1872
+ host.hidden = false;
1873
+ }
1874
+ function startAdminBrand(env) {
1875
+ const requested = env.params.get("brands");
1876
+ let brandsUrl = env.brandsUrl;
1877
+ if (requested) {
1878
+ try {
1879
+ const url = new URL(requested, env.location.href);
1880
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "::1" || url.hostname === "[::1]" || url.origin === env.location.origin;
1881
+ if ((url.protocol === "https:" || url.protocol === "http:") && local)
1882
+ brandsUrl = url.href;
1883
+ } catch {
1884
+ brandsUrl = env.brandsUrl;
1885
+ }
1886
+ }
1887
+ const vendorHost = env.$("vendor");
1888
+ const brandRoot = env.document.querySelector("[data-mockingbird-admin]");
1889
+ const brandService = brandRoot?.getAttribute("data-service") || "";
1890
+ if (vendorHost === null)
1891
+ return;
1892
+ env.fetch(brandsUrl, {
1893
+ headers: { accept: "application/json" },
1894
+ signal: AbortSignal.timeout(5e3)
1895
+ }).then(async (response) => {
1896
+ if (!response.ok)
1897
+ return null;
1898
+ const catalog = await response.json();
1899
+ return catalog;
1900
+ }).then((catalog) => {
1901
+ mountAdminBrand(env.document, vendorHost, brandService, catalog);
1902
+ }).catch(() => {
1903
+ });
1904
+ }
1905
+ function faultPresetList(value) {
1906
+ if (!isRecord2(value))
1907
+ throw new Error("Fault presets response was not an object");
1908
+ if (!Object.hasOwn(value, "presets") || value.presets === void 0 || value.presets === null) {
1909
+ return { presets: [] };
1910
+ }
1911
+ if (!Array.isArray(value.presets))
1912
+ throw new Error("Fault presets response was not a list");
1913
+ return {
1914
+ presets: value.presets.flatMap((item) => {
1915
+ if (!isRecord2(item) || typeof item.name !== "string")
1916
+ return [];
1917
+ return [{ name: item.name }];
1918
+ })
1919
+ };
1920
+ }
1921
+ function bootAdmin(config) {
1922
+ const fieldKinds = ["string", "number", "boolean", "null", "object", "array", "unknown"];
1923
+ const sources = ["declared", "inferred", "mixed"];
1924
+ const isFieldKind = (value) => typeof value === "string" && fieldKinds.some((kind) => kind === value);
1925
+ const isSource = (value) => typeof value === "string" && sources.some((source) => source === value);
1926
+ const readJson2 = (text) => {
1927
+ const value = JSON.parse(text);
1928
+ return value;
1929
+ };
1930
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => {
1931
+ switch (char) {
1932
+ case "&":
1933
+ return "&amp;";
1934
+ case "<":
1935
+ return "&lt;";
1936
+ case ">":
1937
+ return "&gt;";
1938
+ case '"':
1939
+ return "&quot;";
1940
+ default:
1941
+ return "&#39;";
1942
+ }
1943
+ });
1944
+ const el = (id, kind) => {
1945
+ const node = document.getElementById(id);
1946
+ if (!(node instanceof kind))
1947
+ throw new Error(`admin shell is missing #${id}`);
1948
+ return node;
1949
+ };
1950
+ const errorMessage = (data, fallback) => {
1951
+ if (!isRecord2(data))
1952
+ return fallback;
1953
+ const error2 = data.error;
1954
+ if (!isRecord2(error2) || typeof error2.message !== "string" || error2.message === "") {
1955
+ return fallback;
1956
+ }
1957
+ return error2.message;
1958
+ };
1959
+ const requireList = (value, label) => {
1960
+ if (value === void 0 || value === null)
1961
+ return [];
1962
+ if (!Array.isArray(value))
1963
+ throw new Error(`${label} was not a list`);
1964
+ return value;
1965
+ };
1966
+ const state = {
1967
+ namespace: "default",
1968
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1969
+ view: "overview",
1970
+ collection: "",
1971
+ shape: null,
1972
+ route: null,
1973
+ editing: null
1974
+ };
1975
+ const standard = new Set(config.standardRoutes);
1976
+ const banner = el("banner", HTMLElement);
1977
+ const keyInput = el("admin-key", HTMLInputElement);
1978
+ keyInput.value = state.key;
1979
+ const params = new URLSearchParams(location.search);
1980
+ const queryKey = params.get("key");
1981
+ if (queryKey) {
1982
+ state.key = queryKey;
1983
+ keyInput.value = state.key;
1984
+ sessionStorage.setItem("mockingbird-admin-key", state.key);
1985
+ params.delete("key");
1986
+ const next = params.toString();
1987
+ history.replaceState(null, "", location.pathname + (next ? `?${next}` : ""));
1988
+ }
1989
+ const queryNamespace = params.get("namespace");
1990
+ if (queryNamespace)
1991
+ state.namespace = queryNamespace;
1992
+ const showError = (error2) => {
1993
+ banner.textContent = error2 instanceof Error ? error2.message : String(error2);
1994
+ banner.classList.add("show");
1995
+ };
1996
+ const clearError = () => {
1997
+ banner.classList.remove("show");
1998
+ };
1999
+ const api = async (method, path, body) => {
2000
+ const headers = { accept: "application/json" };
2001
+ if (state.key !== "")
2002
+ headers[config.adminKeyHeader] = state.key;
2003
+ if (state.namespace !== "")
2004
+ headers["x-mockingbird-namespace"] = state.namespace;
2005
+ if (body !== void 0)
2006
+ headers["content-type"] = "application/json";
2007
+ const init = { method, headers };
2008
+ if (body !== void 0)
2009
+ init.body = JSON.stringify(body);
2010
+ const response = await fetch(config.adminPrefix + path, init);
2011
+ const text = await response.text();
2012
+ let data = null;
2013
+ if (text !== "") {
2014
+ try {
2015
+ data = readJson2(text);
2016
+ } catch {
2017
+ data = { raw: text };
2018
+ }
2019
+ }
2020
+ if (response.status === 401) {
2021
+ keyInput.focus();
2022
+ throw new Error(errorMessage(data, "Admin key required"));
2023
+ }
2024
+ if (!response.ok) {
2025
+ throw new Error(errorMessage(data, `${response.status} ${method} ${path}`));
2026
+ }
2027
+ return data;
2028
+ };
2029
+ const originGet = async (path) => {
2030
+ const response = await fetch(path, { headers: { accept: "application/json" } });
2031
+ if (!response.ok)
2032
+ throw new Error(`${response.status} ${path}`);
2033
+ const value = await response.json();
2034
+ return value;
2035
+ };
2036
+ const panelApi = {
2037
+ get: (path) => api("GET", path),
2038
+ send: (method, path, body) => api(method, path, body),
2039
+ namespace: () => state.namespace
2040
+ };
2041
+ const isPanelScript = (value) => typeof value === "function";
2042
+ const setTheme = (theme) => {
2043
+ if (theme)
2044
+ document.documentElement.dataset.theme = theme;
2045
+ else
2046
+ delete document.documentElement.dataset.theme;
2047
+ };
2048
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme");
2049
+ if (storedTheme)
2050
+ setTheme(storedTheme);
2051
+ el("theme", HTMLButtonElement).addEventListener("click", () => {
2052
+ const current = document.documentElement.dataset.theme;
2053
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches;
2054
+ const next = dark ? "light" : "dark";
2055
+ localStorage.setItem("mockingbird-admin-theme", next);
2056
+ setTheme(next);
2057
+ });
2058
+ const show = (view) => {
2059
+ state.view = view;
2060
+ for (const button of document.querySelectorAll("#nav button")) {
2061
+ if (!(button instanceof HTMLButtonElement))
2062
+ continue;
2063
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false");
2064
+ }
2065
+ for (const section of document.querySelectorAll("main .view")) {
2066
+ if (!(section instanceof HTMLElement))
2067
+ continue;
2068
+ section.hidden = section.id !== `view-${view}`;
2069
+ }
2070
+ };
2071
+ el("nav", HTMLElement).addEventListener("click", (event) => {
2072
+ const target = event.target;
2073
+ if (!(target instanceof Element))
2074
+ return;
2075
+ const button = target.closest("button[data-view]");
2076
+ if (!(button instanceof HTMLButtonElement))
2077
+ return;
2078
+ const view = button.dataset.view;
2079
+ if (view === void 0)
2080
+ return;
2081
+ show(view);
2082
+ refresh().catch(showError);
2083
+ });
2084
+ const cards = (items) => `<div class="grid">${items.map((item) => `<article class="card"><div class="k">${item.k}</div><div class="v">${item.v}</div></article>`).join("")}</div>`;
2085
+ const table = (columns, rows) => {
2086
+ if (rows.length === 0)
2087
+ return '<p class="empty">Nothing here yet.</p>';
2088
+ const head = `<tr>${columns.map((column) => `<th>${column.label}</th>`).join("")}</tr>`;
2089
+ const body = rows.map((row) => {
2090
+ const cells = columns.map((column) => `<td data-label="${column.label}">${column.cell(row)}</td>`).join("");
2091
+ const attrs = "attrs" in row && typeof row.attrs === "string" ? row.attrs : "";
2092
+ return `<tr${attrs}>${cells}</tr>`;
2093
+ }).join("");
2094
+ return `<table><thead>${head}</thead><tbody>${body}</tbody></table>`;
2095
+ };
2096
+ const preview = (value) => {
2097
+ const text = JSON.stringify(value) ?? "null";
2098
+ return esc(text.length > 180 ? `${text.slice(0, 180)}\u2026` : text);
2099
+ };
2100
+ const when = (epoch) => {
2101
+ const date = new Date(epoch);
2102
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString();
2103
+ };
2104
+ const clockCard = (epoch) => {
2105
+ const date = new Date(epoch);
2106
+ if (Number.isNaN(date.getTime()))
2107
+ return esc(String(epoch));
2108
+ const iso = date.toISOString();
2109
+ return `${esc(iso.slice(0, 10))}<span class="clock-time">${esc(iso.slice(11, 19))} UTC</span>`;
2110
+ };
2111
+ const decodeClock = (value) => {
2112
+ if (!isRecord2(value) || typeof value.now !== "number" || typeof value.offsetMs !== "number" || typeof value.frozen !== "boolean") {
2113
+ throw new Error("Clock response was not a clock");
2114
+ }
2115
+ return { now: value.now, offsetMs: value.offsetMs, frozen: value.frozen };
2116
+ };
2117
+ const decodeField = (value) => {
2118
+ if (!isRecord2(value) || typeof value.name !== "string" || !isFieldKind(value.kind)) {
2119
+ return void 0;
2120
+ }
2121
+ const field = {
2122
+ name: value.name,
2123
+ kind: value.kind,
2124
+ optional: value.optional === true
2125
+ };
2126
+ if (typeof value.description === "string")
2127
+ field.description = value.description;
2128
+ if (Array.isArray(value.fields)) {
2129
+ field.fields = value.fields.flatMap((item) => {
2130
+ const child = decodeField(item);
2131
+ return child === void 0 ? [] : [child];
2132
+ });
2133
+ }
2134
+ return field;
2135
+ };
2136
+ const decodeCollection = (value) => {
2137
+ if (!isRecord2(value) || typeof value.name !== "string")
2138
+ return void 0;
2139
+ const fields = Array.isArray(value.fields) ? value.fields.flatMap((item) => {
2140
+ const field = decodeField(item);
2141
+ return field === void 0 ? [] : [field];
2142
+ }) : [];
2143
+ const collection = {
2144
+ name: value.name,
2145
+ label: typeof value.label === "string" ? value.label : value.name,
2146
+ count: typeof value.count === "number" ? value.count : 0,
2147
+ source: isSource(value.source) ? value.source : "inferred",
2148
+ fields
2149
+ };
2150
+ if (typeof value.description === "string")
2151
+ collection.description = value.description;
2152
+ return collection;
2153
+ };
2154
+ const decodeState = (value) => {
2155
+ if (!isRecord2(value) || !Array.isArray(value.collections)) {
2156
+ throw new Error("State response has no collection list");
2157
+ }
2158
+ return {
2159
+ namespace: typeof value.namespace === "string" ? value.namespace : state.namespace,
2160
+ storageNamespace: typeof value.storageNamespace === "string" ? value.storageNamespace : "",
2161
+ collections: value.collections.flatMap((item) => {
2162
+ const collection = decodeCollection(item);
2163
+ return collection === void 0 ? [] : [collection];
2164
+ })
2165
+ };
2166
+ };
2167
+ const decodeRecords = (value) => requireList(isRecord2(value) ? value.records : void 0, "Records").flatMap((item) => {
2168
+ if (!isRecord2(item) || typeof item.id !== "string")
2169
+ return [];
2170
+ return [
2171
+ {
2172
+ id: item.id,
2173
+ seq: typeof item.seq === "number" ? item.seq : 0,
2174
+ value: item.value,
2175
+ attrs: ` class="clickable" data-id="${esc(item.id)}"`
2176
+ }
2177
+ ];
2178
+ });
2179
+ const textOf = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : "";
2180
+ const decodeJournal = (value) => requireList(isRecord2(value) ? value.requests : void 0, "Journal").flatMap((item) => {
2181
+ if (!isRecord2(item))
2182
+ return [];
2183
+ return [
2184
+ {
2185
+ at: textOf(item.at),
2186
+ method: textOf(item.method),
2187
+ path: textOf(item.path),
2188
+ status: textOf(item.status),
2189
+ durationMs: textOf(item.durationMs),
2190
+ operationId: textOf(item.operationId)
2191
+ }
2192
+ ];
2193
+ });
2194
+ const decodeFaults = (value) => requireList(isRecord2(value) ? value.faults : void 0, "Faults").flatMap((item) => {
2195
+ if (!isRecord2(item))
2196
+ return [];
2197
+ return [
2198
+ {
2199
+ id: textOf(item.id),
2200
+ method: typeof item.method === "string" ? item.method : void 0,
2201
+ pathPrefix: typeof item.pathPrefix === "string" ? item.pathPrefix : void 0,
2202
+ operationId: typeof item.operationId === "string" ? item.operationId : void 0,
2203
+ status: typeof item.status === "number" ? item.status : void 0,
2204
+ effect: typeof item.effect === "string" ? item.effect : void 0,
2205
+ drop: typeof item.drop === "boolean" ? item.drop : void 0,
2206
+ latencyMs: typeof item.latencyMs === "number" ? item.latencyMs : void 0
2207
+ }
2208
+ ];
2209
+ });
2210
+ const loadNamespaces = async () => {
2211
+ const data = await api("GET", "/namespaces");
2212
+ const select = el("namespace", HTMLSelectElement);
2213
+ const listed = requireList(isRecord2(data) ? data.namespaces : void 0, "Namespaces");
2214
+ const fallback = isRecord2(data) && typeof data.default === "string" && data.default !== "" ? data.default : "default";
2215
+ const names = (listed.length > 0 ? listed.map((name) => String(name)) : [fallback]).slice();
2216
+ if (!names.includes(state.namespace))
2217
+ names.unshift(state.namespace);
2218
+ select.innerHTML = names.map((name) => `<option value="${esc(name)}">${esc(name)}</option>`).join("");
2219
+ select.value = state.namespace;
2220
+ };
2221
+ const renderOverview = async () => {
2222
+ const [health, shape, clock, journal] = await Promise.all([
2223
+ originGet("/health"),
2224
+ api("GET", "/state"),
2225
+ api("GET", "/clock"),
2226
+ api("GET", "/requests?limit=8")
2227
+ ]);
2228
+ if (!isRecord2(health))
2229
+ throw new Error("Health response was not an object");
2230
+ const decoded = decodeState(shape);
2231
+ state.shape = decoded;
2232
+ const time = decodeClock(clock);
2233
+ el("overview-cards", HTMLElement).innerHTML = cards([
2234
+ {
2235
+ k: "Service",
2236
+ v: esc(typeof health.service === "string" && health.service !== "" ? health.service : config.service)
2237
+ },
2238
+ {
2239
+ k: "Status",
2240
+ v: esc(typeof health.status === "string" && health.status !== "" ? health.status : "ok")
2241
+ },
2242
+ { k: "Namespace", v: esc(state.namespace) },
2243
+ { k: "Collections", v: String(decoded.collections.length) },
2244
+ {
2245
+ k: "Records",
2246
+ v: String(decoded.collections.reduce((sum, item) => sum + item.count, 0))
2247
+ },
2248
+ { k: "Clock", v: clockCard(time.now) }
2249
+ ]);
2250
+ el("overview-requests", HTMLElement).innerHTML = table([
2251
+ { label: "Method", cell: (row) => esc(row.method) },
2252
+ { label: "Path", cell: (row) => esc(row.path) },
2253
+ {
2254
+ label: "Status",
2255
+ cell: (row) => `<span class="status-${row.status.charAt(0)}">${esc(row.status)}</span>`
2256
+ },
2257
+ { label: "Operation", cell: (row) => esc(row.operationId) }
2258
+ ], decodeJournal(journal));
2259
+ };
2260
+ const schemaChips = (collection) => {
2261
+ if (collection.fields.length === 0) {
2262
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>';
2263
+ }
2264
+ return `<div class="chips">${collection.fields.map((field) => `<span class="chip">${esc(field.name)} <i>${esc(field.kind)}${field.optional ? "?" : ""}</i></span>`).join("")}</div>`;
2265
+ };
2266
+ const renderState = async () => {
2267
+ const shape = decodeState(await api("GET", "/state"));
2268
+ state.shape = shape;
2269
+ const host = el("collections", HTMLElement);
2270
+ if (shape.collections.length === 0) {
2271
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>';
2272
+ el("schema", HTMLElement).innerHTML = "";
2273
+ el("records", HTMLElement).innerHTML = "";
2274
+ return;
2275
+ }
2276
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2277
+ const first = shape.collections[0];
2278
+ if (first === void 0)
2279
+ return;
2280
+ state.collection = first.name;
2281
+ }
2282
+ host.innerHTML = shape.collections.map((item) => `<button type="button" class="collection" data-collection="${esc(item.name)}" aria-current="${item.name === state.collection ? "true" : "false"}"><strong>${esc(item.label)}</strong><small>${esc(item.count)} \xB7 ${esc(item.source)}</small></button>`).join("");
2283
+ const selected = shape.collections.find((item) => item.name === state.collection);
2284
+ if (selected === void 0)
2285
+ return;
2286
+ const description = selected.description ? `<p class="lede">${esc(selected.description)}</p>` : "";
2287
+ el("schema", HTMLElement).innerHTML = `<h3>${esc(selected.label)}</h3>${description}${schemaChips(selected)}`;
2288
+ const page = await api("GET", `/state/${encodeURIComponent(state.collection)}?limit=50`);
2289
+ el("records", HTMLElement).innerHTML = table([
2290
+ { label: "Id", cell: (row) => `<code>${esc(row.id)}</code>` },
2291
+ { label: "Seq", cell: (row) => esc(row.seq) },
2292
+ { label: "Value", cell: (row) => preview(row.value) }
2293
+ ], decodeRecords(page));
2294
+ };
2295
+ const renderClock = async () => {
2296
+ const clock = decodeClock(await api("GET", "/clock"));
2297
+ el("clock-readout", HTMLElement).innerHTML = `<div class="k">Now</div><div class="v">${esc(when(clock.now))}</div><p>${esc(clock.now)} ms \xB7 offset ${esc(clock.offsetMs)} ms ${clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>"}</p>`;
2298
+ const freeze = el("freeze", HTMLButtonElement);
2299
+ freeze.textContent = clock.frozen ? "Unfreeze" : "Freeze";
2300
+ freeze.dataset.frozen = clock.frozen ? "1" : "0";
2301
+ };
2302
+ const renderFaults = async () => {
2303
+ const [faults, presets] = await Promise.all([
2304
+ api("GET", "/faults"),
2305
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2306
+ ]);
2307
+ const select = el("fault-preset", HTMLSelectElement);
2308
+ const current = select.value;
2309
+ const list = faultPresetList(presets).presets;
2310
+ select.innerHTML = `<option value="">Custom rule</option>${list.map((preset) => `<option value="${esc(preset.name)}">${esc(preset.name)}</option>`).join("")}`;
2311
+ select.value = current;
2312
+ el("fault-list", HTMLElement).innerHTML = table([
2313
+ { label: "Id", cell: (row) => esc(row.id) },
2314
+ {
2315
+ label: "Match",
2316
+ cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter((part) => Boolean(part)).join(" ") || "all")
2317
+ },
2318
+ {
2319
+ label: "Effect",
2320
+ cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || ""))
2321
+ }
2322
+ ], decodeFaults(faults));
2323
+ };
2324
+ const renderJournal = async () => {
2325
+ const journal = await api("GET", "/requests?limit=100");
2326
+ el("journal", HTMLElement).innerHTML = table([
2327
+ { label: "When", cell: (row) => esc(row.at) },
2328
+ { label: "Method", cell: (row) => esc(row.method) },
2329
+ { label: "Path", cell: (row) => esc(row.path) },
2330
+ { label: "Status", cell: (row) => esc(row.status) },
2331
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2332
+ ], decodeJournal(journal));
2333
+ };
2334
+ const renderRoutes = async () => {
2335
+ const data = await api("GET", "/");
2336
+ if (!isRecord2(data))
2337
+ throw new Error("Route list was not an object");
2338
+ const routes = requireList(data.routes, "Routes").map((route) => String(route));
2339
+ el("route-list", HTMLElement).innerHTML = routes.map((route) => {
2340
+ const extra = standard.has(route) ? "" : " <span class='badge'>extension</span>";
2341
+ const parts = route.split(" ");
2342
+ const method = parts[0] ?? "";
2343
+ const path = parts.slice(1).join(" ");
2344
+ return `<div class="route"><span class="method">${esc(method)}</span><span>${esc(path)}${extra}</span><button class="btn" type="button" data-route="${esc(route)}">Use</button></div>`;
2345
+ }).join("");
2346
+ };
2347
+ const renderers = {
2348
+ overview: renderOverview,
2349
+ state: renderState,
2350
+ clock: renderClock,
2351
+ faults: renderFaults,
2352
+ journal: renderJournal,
2353
+ routes: renderRoutes
2354
+ };
2355
+ async function refresh() {
2356
+ clearError();
2357
+ const render = renderers[state.view];
2358
+ if (render)
2359
+ await render();
2360
+ }
2361
+ el("namespace", HTMLSelectElement).addEventListener("change", () => {
2362
+ state.namespace = el("namespace", HTMLSelectElement).value;
2363
+ refresh().catch(showError);
2364
+ });
2365
+ keyInput.addEventListener("change", () => {
2366
+ state.key = keyInput.value.trim();
2367
+ sessionStorage.setItem("mockingbird-admin-key", state.key);
2368
+ refresh().catch(showError);
2369
+ });
2370
+ el("refresh", HTMLButtonElement).addEventListener("click", () => {
2371
+ refresh().catch(showError);
2372
+ });
2373
+ el("collections", HTMLElement).addEventListener("click", (event) => {
2374
+ const target = event.target;
2375
+ if (!(target instanceof Element))
2376
+ return;
2377
+ const button = target.closest("[data-collection]");
2378
+ if (!(button instanceof HTMLElement))
2379
+ return;
2380
+ const collection = button.dataset.collection;
2381
+ if (collection === void 0)
2382
+ return;
2383
+ state.collection = collection;
2384
+ renderState().catch(showError);
2385
+ });
2386
+ el("records", HTMLElement).addEventListener("click", (event) => {
2387
+ const target = event.target;
2388
+ if (!(target instanceof Element))
2389
+ return;
2390
+ const row = target.closest("[data-id]");
2391
+ if (!(row instanceof HTMLElement))
2392
+ return;
2393
+ const id = row.dataset.id;
2394
+ if (id === void 0)
2395
+ return;
2396
+ openEditor(id).catch(showError);
2397
+ });
2398
+ const editor = el("editor", HTMLDialogElement);
2399
+ const editorId = el("editor-id", HTMLInputElement);
2400
+ const editorValue = el("editor-value", HTMLTextAreaElement);
2401
+ const editorDelete = el("editor-delete", HTMLButtonElement);
2402
+ async function openEditor(id) {
2403
+ state.editing = id;
2404
+ el("editor-title", HTMLElement).textContent = id ? "Edit record" : "New record";
2405
+ editorId.value = id ?? "";
2406
+ editorId.readOnly = id !== null;
2407
+ editorDelete.hidden = id === null;
2408
+ if (id) {
2409
+ const record2 = await api("GET", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`);
2410
+ if (!isRecord2(record2))
2411
+ throw new Error("Record response was not an object");
2412
+ editorValue.value = JSON.stringify(record2.value, null, 2) ?? "";
2413
+ } else {
2414
+ editorValue.value = "{\n \n}";
2415
+ }
2416
+ editor.showModal();
2417
+ }
2418
+ el("new-record", HTMLButtonElement).addEventListener("click", () => {
2419
+ openEditor(null).catch(showError);
2420
+ });
2421
+ el("editor-form", HTMLFormElement).addEventListener("submit", (event) => {
2422
+ const submitter = event.submitter;
2423
+ if (!(submitter instanceof HTMLButtonElement) || submitter.value !== "save")
2424
+ return;
2425
+ event.preventDefault();
2426
+ let value;
2427
+ try {
2428
+ value = readJson2(editorValue.value);
2429
+ } catch {
2430
+ showError(new Error("Value is not JSON"));
2431
+ return;
2432
+ }
2433
+ const id = editorId.value.trim();
2434
+ const path = `/state/${encodeURIComponent(state.collection)}`;
2435
+ const request = state.editing ? api("PUT", `${path}/${encodeURIComponent(id)}`, { value }) : api("POST", path, { id: id || void 0, value });
2436
+ request.then(() => {
2437
+ editor.close();
2438
+ return renderState();
2439
+ }).catch(showError);
2440
+ });
2441
+ editorDelete.addEventListener("click", () => {
2442
+ const id = state.editing;
2443
+ if (!id)
2444
+ return;
2445
+ api("DELETE", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`).then(() => {
2446
+ editor.close();
2447
+ return renderState();
2448
+ }).catch(showError);
2449
+ });
2450
+ for (const button of document.querySelectorAll("[data-advance]")) {
2451
+ if (!(button instanceof HTMLButtonElement))
2452
+ continue;
2453
+ button.addEventListener("click", () => {
2454
+ const raw = button.dataset.advance;
2455
+ if (raw === void 0)
2456
+ return;
2457
+ api("POST", "/clock", { advance: Number(raw) }).then(() => renderClock()).catch(showError);
2458
+ });
2459
+ }
2460
+ el("freeze", HTMLButtonElement).addEventListener("click", () => {
2461
+ const frozen = el("freeze", HTMLButtonElement).dataset.frozen === "1";
2462
+ api("POST", "/clock", { freeze: !frozen }).then(() => renderClock()).catch(showError);
2463
+ });
2464
+ el("clock-reset", HTMLButtonElement).addEventListener("click", () => {
2465
+ api("POST", "/clock", { reset: true }).then(() => renderClock()).catch(showError);
2466
+ });
2467
+ el("clock-set", HTMLFormElement).addEventListener("submit", (event) => {
2468
+ event.preventDefault();
2469
+ const raw = el("clock-instant", HTMLInputElement).value.trim();
2470
+ const set = /^-?\d+$/.test(raw) ? Number(raw) : raw;
2471
+ api("POST", "/clock", { set }).then(() => renderClock()).catch(showError);
2472
+ });
2473
+ el("fault-form", HTMLFormElement).addEventListener("submit", (event) => {
2474
+ event.preventDefault();
2475
+ const preset = el("fault-preset", HTMLSelectElement).value;
2476
+ if (preset !== "") {
2477
+ api("POST", "/faults", { preset }).then(() => renderFaults()).catch(showError);
2478
+ return;
2479
+ }
2480
+ const status = Number(el("fault-status", HTMLInputElement).value);
2481
+ if (!Number.isFinite(status)) {
2482
+ showError(new Error("Status must be a number, or choose a preset"));
2483
+ return;
2484
+ }
2485
+ const path = el("fault-path", HTMLInputElement).value;
2486
+ const method = el("fault-method", HTMLInputElement).value;
2487
+ api("POST", "/faults", {
2488
+ status,
2489
+ ...path !== "" ? { pathPrefix: path } : {},
2490
+ ...method !== "" ? { method } : {}
2491
+ }).then(() => renderFaults()).catch(showError);
2492
+ });
2493
+ el("fault-clear", HTMLButtonElement).addEventListener("click", () => {
2494
+ api("DELETE", "/faults").then(() => renderFaults()).catch(showError);
2495
+ });
2496
+ el("journal-clear", HTMLButtonElement).addEventListener("click", () => {
2497
+ api("DELETE", "/requests").then(() => renderJournal()).catch(showError);
2498
+ });
2499
+ el("route-list", HTMLElement).addEventListener("click", (event) => {
2500
+ const target = event.target;
2501
+ if (!(target instanceof Element))
2502
+ return;
2503
+ const button = target.closest("[data-route]");
2504
+ if (!(button instanceof HTMLElement))
2505
+ return;
2506
+ const route = button.dataset.route;
2507
+ if (route === void 0)
2508
+ return;
2509
+ state.route = route;
2510
+ el("route-title", HTMLElement).textContent = route;
2511
+ const method = route.split(" ")[0] ?? "";
2512
+ el("route-body", HTMLTextAreaElement).disabled = method === "GET" || method === "DELETE";
2513
+ });
2514
+ el("route-form", HTMLFormElement).addEventListener("submit", (event) => {
2515
+ event.preventDefault();
2516
+ const send = async () => {
2517
+ if (state.route === null)
2518
+ throw new Error("Choose a route first");
2519
+ const parts = state.route.split(" ");
2520
+ const method = parts[0];
2521
+ const path = parts.slice(1).join(" ");
2522
+ if (method === void 0)
2523
+ throw new Error("Choose a route first");
2524
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_match, key2) => prompt(`Value for ${key2}`) || "");
2525
+ let body;
2526
+ const routeBody = el("route-body", HTMLTextAreaElement);
2527
+ if (method !== "GET" && method !== "DELETE" && routeBody.value.trim() !== "") {
2528
+ try {
2529
+ body = readJson2(routeBody.value);
2530
+ } catch {
2531
+ throw new Error("Body is not JSON");
2532
+ }
2533
+ }
2534
+ const data = await api(method, concrete, body);
2535
+ el("route-result", HTMLElement).textContent = JSON.stringify(data, null, 2);
2536
+ };
2537
+ send().catch(showError);
2538
+ });
2539
+ const decodePanel = (value) => {
2540
+ if (!isRecord2(value) || typeof value.id !== "string" || typeof value.title !== "string") {
2541
+ return void 0;
2542
+ }
2543
+ const panel = {
2544
+ id: value.id,
2545
+ title: value.title,
2546
+ description: typeof value.description === "string" ? value.description : "",
2547
+ html: typeof value.html === "string" ? value.html : ""
2548
+ };
2549
+ if (typeof value.script === "string")
2550
+ panel.script = value.script;
2551
+ return panel;
2552
+ };
2553
+ const mountPanels = (panels) => {
2554
+ const nav = el("nav", HTMLElement);
2555
+ const views = el("views", HTMLElement);
2556
+ for (const panel of panels) {
2557
+ const button = document.createElement("button");
2558
+ button.type = "button";
2559
+ button.dataset.view = panel.id;
2560
+ button.textContent = panel.title;
2561
+ nav.append(button);
2562
+ const section = document.createElement("section");
2563
+ section.className = "view";
2564
+ section.id = `view-${panel.id}`;
2565
+ section.hidden = true;
2566
+ const title = document.createElement("h2");
2567
+ title.textContent = panel.title;
2568
+ const lede = document.createElement("p");
2569
+ lede.className = "lede";
2570
+ lede.textContent = panel.description;
2571
+ const body = document.createElement("div");
2572
+ body.className = "panel-body";
2573
+ body.id = `panel-${panel.id}`;
2574
+ body.innerHTML = panel.html;
2575
+ section.append(title, lede, body);
2576
+ views.append(section);
2577
+ if (panel.script === void 0)
2578
+ continue;
2579
+ try {
2580
+ const compiled = new Function("root", "api", panel.script);
2581
+ if (!isPanelScript(compiled))
2582
+ throw new Error("panel script did not compile");
2583
+ compiled(body, panelApi);
2584
+ } catch (error2) {
2585
+ const note = document.createElement("p");
2586
+ note.className = "banner show";
2587
+ note.textContent = error2 instanceof Error ? error2.message : String(error2);
2588
+ body.append(note);
2589
+ }
2590
+ }
2591
+ };
2592
+ startAdminBrand({
2593
+ document,
2594
+ $: (id) => document.getElementById(id),
2595
+ params,
2596
+ location: { href: location.href, origin: location.origin },
2597
+ fetch,
2598
+ brandsUrl: config.brandsUrl
2599
+ });
2600
+ loadNamespaces().then(() => api("GET", "/ui/manifest")).then((manifest) => {
2601
+ const panels = requireList(isRecord2(manifest) ? manifest.panels : void 0, "Panels").flatMap((panel) => {
2602
+ const decoded = decodePanel(panel);
2603
+ return decoded === void 0 ? [] : [decoded];
2604
+ });
2605
+ mountPanels(panels);
2606
+ return refresh();
2607
+ }).catch(showError);
2608
+ }
2609
+ var clientPrelude = [isRecord2, mountAdminBrand, startAdminBrand, faultPresetList, bootAdmin].map((fn) => fn.toString()).join("\n");
2610
+ var adminClientSource = (config) => {
2611
+ const payload = JSON.stringify(config).replace(/</g, "\\u003c");
2612
+ return `<script>
2613
+ ${clientPrelude}
2614
+ bootAdmin(${payload});
2615
+ </script>`;
2616
+ };
2617
+
1392
2618
  // ../core/dist/surface.js
1393
2619
  var defineMock = (runtime) => runtime;
1394
2620
  var STANDARD_ADMIN_ROUTES = [
@@ -1457,94 +2683,106 @@ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1457
2683
  return "&#39;";
1458
2684
  }
1459
2685
  });
2686
+ var ADMIN_BRANDS_URL = "https://mockingbird.chrisvouga.dev/brands.json";
1460
2687
  var renderAdminDocument = (service) => {
1461
2688
  const name = escapeHtml(service);
1462
- const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
2689
+ const script = adminClientSource({
2690
+ standardRoutes: STANDARD_ADMIN_ROUTES,
2691
+ adminPrefix: ADMIN_PREFIX,
2692
+ adminKeyHeader: ADMIN_KEY_HEADER,
2693
+ brandsUrl: ADMIN_BRANDS_URL,
2694
+ service
2695
+ });
1463
2696
  return `<!DOCTYPE html>
1464
2697
  <html lang="en">
1465
2698
  <head>
1466
2699
  <meta charset="utf-8">
1467
2700
  <meta name="viewport" content="width=device-width, initial-scale=1">
1468
2701
  <meta name="color-scheme" content="light dark">
1469
- <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='3' fill='%233d4f3a'/%3E%3C/svg%3E">
2702
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='2' fill='%2327272a'/%3E%3C/svg%3E">
1470
2703
  <title>${name} admin</title>
1471
2704
  <style>
2705
+ ${CSS_RESET}
1472
2706
  :root {
1473
2707
  color-scheme: light;
1474
- --bg: #f6f5f2;
2708
+ --bg: #fafafa;
1475
2709
  --bg-elev: #ffffff;
1476
- --bg-muted: #eeece6;
1477
- --bg-inset: #f3f1eb;
1478
- --line: #e2dfd6;
1479
- --line-strong: #d0ccc1;
1480
- --ink: #1c1915;
1481
- --muted: #5e584f;
1482
- --faint: #8a8378;
1483
- --accent: #3d4f3a;
1484
- --accent-ink: #f7f6f2;
1485
- --accent-soft: #e5ece2;
1486
- --ok: #1f7a45;
1487
- --ok-soft: #e5f4eb;
1488
- --warn: #9a6700;
1489
- --warn-soft: #fbf3df;
1490
- --err: #a33b32;
1491
- --err-soft: #fdecea;
1492
- --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1493
- --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
2710
+ --bg-muted: #f4f4f5;
2711
+ --bg-inset: #f4f4f5;
2712
+ --line: #dedee3;
2713
+ --line-strong: #c4c4cc;
2714
+ --ink: #18181b;
2715
+ --muted: #62626b;
2716
+ --faint: #71717a;
2717
+ --accent: #27272a;
2718
+ --accent-ink: #ffffff;
2719
+ --accent-soft: #f4f4f5;
2720
+ --ok: #166534;
2721
+ --ok-soft: #f0fdf4;
2722
+ --warn: #a16207;
2723
+ --warn-soft: #fefce8;
2724
+ --err: #a82d32;
2725
+ --err-soft: #fef2f2;
2726
+ --shadow: none;
2727
+ --sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1494
2728
  --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1495
- --radius: 14px;
1496
- --header: 60px;
1497
- --nav: 220px;
2729
+ --radius: 10px;
2730
+ --header: 56px;
2731
+ --nav: 200px;
1498
2732
  }
1499
2733
  :root[data-theme="dark"] {
1500
2734
  color-scheme: dark;
1501
- --bg: #141311;
1502
- --bg-elev: #1e1c19;
1503
- --bg-muted: #26231f;
1504
- --bg-inset: #181715;
1505
- --line: #34302b;
1506
- --line-strong: #4a453d;
1507
- --ink: #f4f1ea;
1508
- --muted: #c4bdb1;
1509
- --faint: #8f877c;
1510
- --accent: #c5d5b8;
1511
- --accent-ink: #1a2118;
1512
- --accent-soft: #2a3328;
1513
- --ok: #8fd6a8;
1514
- --ok-soft: #1a2e22;
1515
- --warn: #f0cc78;
1516
- --warn-soft: #332911;
1517
- --err: #f0a8a2;
1518
- --err-soft: #3a201e;
1519
- --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
2735
+ --bg: #111113;
2736
+ --bg-elev: #19191c;
2737
+ --bg-muted: #242428;
2738
+ --bg-inset: #111113;
2739
+ --line: #36363c;
2740
+ --line-strong: #52525b;
2741
+ --ink: #f4f4f5;
2742
+ --muted: #a9a9b2;
2743
+ --faint: #71717a;
2744
+ --accent: #e4e4e7;
2745
+ --accent-ink: #18181b;
2746
+ --accent-soft: #242428;
2747
+ --ok: #86efac;
2748
+ --ok-soft: #14241b;
2749
+ --warn: #fde68a;
2750
+ --warn-soft: #2a2410;
2751
+ --err: #ffaaaa;
2752
+ --err-soft: #2c1516;
2753
+ --shadow: none;
1520
2754
  }
1521
2755
  @media (prefers-color-scheme: dark) {
1522
2756
  :root:not([data-theme="light"]) {
1523
2757
  color-scheme: dark;
1524
- --bg: #141311;
1525
- --bg-elev: #1e1c19;
1526
- --bg-muted: #26231f;
1527
- --bg-inset: #181715;
1528
- --line: #34302b;
1529
- --line-strong: #4a453d;
1530
- --ink: #f4f1ea;
1531
- --muted: #c4bdb1;
1532
- --faint: #8f877c;
1533
- --accent: #c5d5b8;
1534
- --accent-ink: #1a2118;
1535
- --accent-soft: #2a3328;
1536
- --ok: #8fd6a8;
1537
- --ok-soft: #1a2e22;
1538
- --warn: #f0cc78;
1539
- --warn-soft: #332911;
1540
- --err: #f0a8a2;
1541
- --err-soft: #3a201e;
1542
- --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
2758
+ --bg: #111113;
2759
+ --bg-elev: #19191c;
2760
+ --bg-muted: #242428;
2761
+ --bg-inset: #111113;
2762
+ --line: #36363c;
2763
+ --line-strong: #52525b;
2764
+ --ink: #f4f4f5;
2765
+ --muted: #a9a9b2;
2766
+ --faint: #71717a;
2767
+ --accent: #e4e4e7;
2768
+ --accent-ink: #18181b;
2769
+ --accent-soft: #242428;
2770
+ --ok: #86efac;
2771
+ --ok-soft: #14241b;
2772
+ --warn: #fde68a;
2773
+ --warn-soft: #2a2410;
2774
+ --err: #ffaaaa;
2775
+ --err-soft: #2c1516;
2776
+ --shadow: none;
1543
2777
  }
1544
2778
  }
1545
- * { box-sizing: border-box; }
1546
- html, body { margin: 0; height: 100%; }
2779
+ /* Fill the viewport, then grow with the content so the background covers the scroll. */
2780
+ html { height: 100%; }
1547
2781
  body {
2782
+ margin: 0;
2783
+ min-height: 100%;
2784
+ display: flex;
2785
+ flex-direction: column;
1548
2786
  font-family: var(--sans);
1549
2787
  background: var(--bg);
1550
2788
  color: var(--ink);
@@ -1553,24 +2791,37 @@ var renderAdminDocument = (service) => {
1553
2791
  padding-right: env(safe-area-inset-right);
1554
2792
  -webkit-text-size-adjust: 100%;
1555
2793
  }
1556
- button, input, select, textarea { font: inherit; color: inherit; }
1557
- button { cursor: pointer; }
1558
2794
  :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1559
- @media (prefers-reduced-motion: reduce) {
1560
- * { scroll-behavior: auto !important; transition: none !important; }
1561
- }
1562
- .app { min-height: 100%; display: flex; flex-direction: column; }
2795
+ .app { flex: 1 0 auto; display: flex; flex-direction: column; min-width: 0; width: 100%; }
1563
2796
  header.top {
1564
2797
  position: sticky; top: 0; z-index: 5;
1565
2798
  display: flex; align-items: center; gap: 12px;
1566
2799
  min-height: var(--header); padding: 10px 16px;
1567
- background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
2800
+ background: var(--bg-elev);
1568
2801
  border-bottom: 1px solid var(--line);
1569
- backdrop-filter: blur(10px);
1570
- }
1571
- .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1572
- .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1573
- .brand span { color: var(--faint); font-size: 12px; }
2802
+ min-width: 0; max-width: 100%;
2803
+ }
2804
+ .brand {
2805
+ display: flex; flex-flow: row wrap; align-items: center; gap: 14px;
2806
+ min-width: 0; max-width: 100%; margin-right: auto;
2807
+ }
2808
+ .brand-id { display: flex; flex-direction: column; min-width: 0; flex: none; }
2809
+ .brand-id strong { font-size: 15px; letter-spacing: -0.01em; }
2810
+ .brand-id span { color: var(--faint); font-size: 12px; }
2811
+ .vendor {
2812
+ display: flex; flex-wrap: wrap; align-items: center; gap: 6px;
2813
+ min-width: 0; max-width: 100%; font-size: 12px; color: var(--muted);
2814
+ }
2815
+ .vendor[hidden] { display: none; }
2816
+ /* Logos are drawn for a light tile, same as the docs site, so the plate stays white. */
2817
+ .vendor img {
2818
+ width: 16px; height: 16px; padding: 2px; box-sizing: content-box;
2819
+ border-radius: 4px; border: 1px solid var(--line); background: #fff; object-fit: contain;
2820
+ }
2821
+ .vendor-name { color: var(--ink); font-weight: 600; }
2822
+ .vendor-sep { color: var(--faint); }
2823
+ .vendor-link { color: inherit; text-decoration: none; }
2824
+ .vendor-link:hover { color: var(--ink); text-decoration: underline; }
1574
2825
  .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1575
2826
  label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1576
2827
  label.field input, label.field select, .controls input[type="password"] {
@@ -1588,7 +2839,7 @@ var renderAdminDocument = (service) => {
1588
2839
  record or the full nav row would widen the page past the viewport. */
1589
2840
  .layout {
1590
2841
  display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1591
- flex: 1; min-height: 0; min-width: 0;
2842
+ flex: 1 0 auto; min-width: 0;
1592
2843
  }
1593
2844
  nav.side {
1594
2845
  border-right: 1px solid var(--line); padding: 12px;
@@ -1603,7 +2854,7 @@ var renderAdminDocument = (service) => {
1603
2854
  main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1604
2855
  .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1605
2856
  .lede { margin: 0 0 16px; color: var(--muted); }
1606
- .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
2857
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 180px), 1fr)); gap: 12px; }
1607
2858
  .card {
1608
2859
  background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1609
2860
  padding: 14px 16px; box-shadow: var(--shadow);
@@ -1642,8 +2893,8 @@ var renderAdminDocument = (service) => {
1642
2893
  .banner.show { display: block; }
1643
2894
  .empty { color: var(--muted); padding: 24px 8px; }
1644
2895
  dialog {
1645
- border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1646
- color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
2896
+ border: 1px solid var(--line); border-radius: var(--radius); padding: 0; background: var(--bg-elev);
2897
+ color: var(--ink); width: min(640px, calc(100% - 24px)); max-width: calc(100vw - 24px); box-shadow: none;
1647
2898
  }
1648
2899
  dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1649
2900
  dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
@@ -1670,7 +2921,7 @@ var renderAdminDocument = (service) => {
1670
2921
  padding-top: max(10px, env(safe-area-inset-top));
1671
2922
  }
1672
2923
  input, select, textarea { font-size: 16px; }
1673
- .controls { width: 100%; }
2924
+ .brand, .vendor, .controls { width: 100%; }
1674
2925
  label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1675
2926
  .layout { grid-template-columns: minmax(0, 1fr); }
1676
2927
  nav.side {
@@ -1701,8 +2952,11 @@ var renderAdminDocument = (service) => {
1701
2952
  <div class="app" data-service="${name}" data-mockingbird-admin>
1702
2953
  <header class="top">
1703
2954
  <div class="brand">
1704
- <strong>${name}</strong>
1705
- <span>Mockingbird admin</span>
2955
+ <div class="brand-id">
2956
+ <strong>${name}</strong>
2957
+ <span>Admin</span>
2958
+ </div>
2959
+ <div class="vendor" id="vendor" hidden></div>
1706
2960
  </div>
1707
2961
  <div class="controls">
1708
2962
  <label class="field">Namespace
@@ -1832,460 +3086,7 @@ var renderAdminDocument = (service) => {
1832
3086
  </div>
1833
3087
  </form>
1834
3088
  </dialog>
1835
- <script>
1836
- (() => {
1837
- const STANDARD = new Set(${standard})
1838
- const state = {
1839
- namespace: "default",
1840
- key: sessionStorage.getItem("mockingbird-admin-key") || "",
1841
- view: "overview",
1842
- collection: "",
1843
- shape: null,
1844
- route: null,
1845
- editing: null
1846
- }
1847
- const $ = (id) => document.getElementById(id)
1848
- const banner = $("banner")
1849
- const keyInput = $("admin-key")
1850
- keyInput.value = state.key
1851
- const params = new URLSearchParams(location.search)
1852
- if (params.get("key")) {
1853
- state.key = params.get("key")
1854
- keyInput.value = state.key
1855
- sessionStorage.setItem("mockingbird-admin-key", state.key)
1856
- params.delete("key")
1857
- const next = params.toString()
1858
- history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1859
- }
1860
- if (params.get("namespace")) state.namespace = params.get("namespace")
1861
-
1862
- const showError = (error) => {
1863
- banner.textContent = error instanceof Error ? error.message : String(error)
1864
- banner.classList.add("show")
1865
- }
1866
- const clearError = () => banner.classList.remove("show")
1867
-
1868
- async function originGet(path) {
1869
- const response = await fetch(path, { headers: { accept: "application/json" } })
1870
- if (!response.ok) throw new Error(response.status + " " + path)
1871
- return response.json()
1872
- }
1873
- async function api(method, path, body) {
1874
- const headers = { accept: "application/json" }
1875
- if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1876
- if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1877
- if (body !== undefined) headers["content-type"] = "application/json"
1878
- const response = await fetch("${ADMIN_PREFIX}" + path, {
1879
- method,
1880
- headers,
1881
- body: body === undefined ? undefined : JSON.stringify(body)
1882
- })
1883
- const text = await response.text()
1884
- let data = null
1885
- if (text) {
1886
- try { data = JSON.parse(text) } catch { data = { raw: text } }
1887
- }
1888
- if (response.status === 401) {
1889
- keyInput.focus()
1890
- throw new Error((data && data.error && data.error.message) || "Admin key required")
1891
- }
1892
- if (!response.ok) {
1893
- throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1894
- }
1895
- return data
1896
- }
1897
- const panelApi = {
1898
- get: (path) => api("GET", path),
1899
- send: (method, path, body) => api(method, path, body),
1900
- namespace: () => state.namespace
1901
- }
1902
-
1903
- function setTheme(theme) {
1904
- if (theme) document.documentElement.dataset.theme = theme
1905
- else delete document.documentElement.dataset.theme
1906
- }
1907
- const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1908
- if (storedTheme) setTheme(storedTheme)
1909
- $("theme").addEventListener("click", () => {
1910
- const current = document.documentElement.dataset.theme
1911
- const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1912
- const next = dark ? "light" : "dark"
1913
- localStorage.setItem("mockingbird-admin-theme", next)
1914
- setTheme(next)
1915
- })
1916
-
1917
- function show(view) {
1918
- state.view = view
1919
- for (const button of document.querySelectorAll("#nav button")) {
1920
- button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1921
- }
1922
- for (const section of document.querySelectorAll("main .view")) {
1923
- section.hidden = section.id !== "view-" + view
1924
- }
1925
- }
1926
- document.getElementById("nav").addEventListener("click", (event) => {
1927
- const button = event.target.closest("button[data-view]")
1928
- if (!button) return
1929
- show(button.dataset.view)
1930
- refresh().catch(showError)
1931
- })
1932
-
1933
- function cards(items) {
1934
- return '<div class="grid">' + items.map((item) =>
1935
- '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1936
- ).join("") + "</div>"
1937
- }
1938
- function table(columns, rows) {
1939
- if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1940
- const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1941
- const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1942
- '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1943
- ).join("") + "</tr>").join("")
1944
- return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1945
- }
1946
- const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1947
- "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1948
- }[char]))
1949
- const preview = (value) => {
1950
- const text = JSON.stringify(value)
1951
- return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1952
- }
1953
- const when = (epoch) => {
1954
- const date = new Date(epoch)
1955
- return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1956
- }
1957
- const clockCard = (epoch) => {
1958
- const date = new Date(epoch)
1959
- if (Number.isNaN(date.getTime())) return esc(String(epoch))
1960
- const iso = date.toISOString()
1961
- return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1962
- }
1963
-
1964
- async function loadNamespaces() {
1965
- const data = await api("GET", "/namespaces")
1966
- const select = $("namespace")
1967
- const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1968
- if (!names.includes(state.namespace)) names.unshift(state.namespace)
1969
- select.innerHTML = names.map((name) =>
1970
- '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1971
- ).join("")
1972
- select.value = state.namespace
1973
- }
1974
-
1975
- async function renderOverview() {
1976
- const [health, shape, clock, journal] = await Promise.all([
1977
- originGet("/health"),
1978
- api("GET", "/state"),
1979
- api("GET", "/clock"),
1980
- api("GET", "/requests?limit=8")
1981
- ])
1982
- state.shape = shape
1983
- $("overview-cards").innerHTML = cards([
1984
- { k: "Service", v: esc(health.service || "${name}") },
1985
- { k: "Status", v: esc(health.status || "ok") },
1986
- { k: "Namespace", v: esc(state.namespace) },
1987
- { k: "Collections", v: String(shape.collections.length) },
1988
- { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1989
- { k: "Clock", v: clockCard(clock.now) }
1990
- ])
1991
- const requests = (journal && journal.requests) || []
1992
- $("overview-requests").innerHTML = table(
1993
- [
1994
- { label: "Method", cell: (row) => esc(row.method) },
1995
- { label: "Path", cell: (row) => esc(row.path) },
1996
- { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1997
- { label: "Operation", cell: (row) => esc(row.operationId || "") }
1998
- ],
1999
- requests
2000
- )
2001
- }
2002
-
2003
- function schemaChips(collection) {
2004
- if (!collection || collection.fields.length === 0) {
2005
- return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
2006
- }
2007
- return '<div class="chips">' + collection.fields.map((field) =>
2008
- '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
2009
- ).join("") + "</div>"
2010
- }
2011
-
2012
- async function renderState() {
2013
- const shape = await api("GET", "/state")
2014
- state.shape = shape
2015
- const host = $("collections")
2016
- if (shape.collections.length === 0) {
2017
- host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
2018
- $("schema").innerHTML = ""
2019
- $("records").innerHTML = ""
2020
- return
2021
- }
2022
- if (!shape.collections.some((item) => item.name === state.collection)) {
2023
- state.collection = shape.collections[0].name
2024
- }
2025
- host.innerHTML = shape.collections.map((item) =>
2026
- '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
2027
- (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
2028
- '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
2029
- ).join("")
2030
- const selected = shape.collections.find((item) => item.name === state.collection)
2031
- $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
2032
- (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
2033
- schemaChips(selected)
2034
- const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
2035
- const rows = page.records.map((record) => ({
2036
- ...record,
2037
- attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
2038
- }))
2039
- $("records").innerHTML = table(
2040
- [
2041
- { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
2042
- { label: "Seq", cell: (row) => esc(row.seq) },
2043
- { label: "Value", cell: (row) => preview(row.value) }
2044
- ],
2045
- rows
2046
- )
2047
- }
2048
-
2049
- async function renderClock() {
2050
- const clock = await api("GET", "/clock")
2051
- $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
2052
- "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
2053
- (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
2054
- $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
2055
- $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
2056
- }
2057
-
2058
- async function renderFaults() {
2059
- const [faults, presets] = await Promise.all([
2060
- api("GET", "/faults"),
2061
- api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2062
- ])
2063
- const select = $("fault-preset")
2064
- const current = select.value
2065
- const list = presets.presets || []
2066
- select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
2067
- '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
2068
- ).join("")
2069
- select.value = current
2070
- const rules = faults.faults || []
2071
- $("fault-list").innerHTML = table(
2072
- [
2073
- { label: "Id", cell: (row) => esc(row.id) },
2074
- { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
2075
- { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
2076
- ],
2077
- rules
2078
- )
2079
- }
2080
-
2081
- async function renderJournal() {
2082
- const journal = await api("GET", "/requests?limit=100")
2083
- $("journal").innerHTML = table(
2084
- [
2085
- { label: "When", cell: (row) => esc(row.at || "") },
2086
- { label: "Method", cell: (row) => esc(row.method) },
2087
- { label: "Path", cell: (row) => esc(row.path) },
2088
- { label: "Status", cell: (row) => esc(row.status) },
2089
- { label: "ms", cell: (row) => esc(row.durationMs) }
2090
- ],
2091
- journal.requests || []
2092
- )
2093
- }
2094
-
2095
- async function renderRoutes() {
2096
- const data = await api("GET", "/")
2097
- const routes = data.routes || []
2098
- $("route-list").innerHTML = routes.map((route) => {
2099
- const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
2100
- return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
2101
- '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
2102
- '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
2103
- }).join("")
2104
- }
2105
-
2106
- const renderers = {
2107
- overview: renderOverview,
2108
- state: renderState,
2109
- clock: renderClock,
2110
- faults: renderFaults,
2111
- journal: renderJournal,
2112
- routes: renderRoutes
2113
- }
2114
-
2115
- async function refresh() {
2116
- clearError()
2117
- if (state.view in renderers) await renderers[state.view]()
2118
- }
2119
-
2120
- $("namespace").addEventListener("change", () => {
2121
- state.namespace = $("namespace").value
2122
- refresh().catch(showError)
2123
- })
2124
- keyInput.addEventListener("change", () => {
2125
- state.key = keyInput.value.trim()
2126
- sessionStorage.setItem("mockingbird-admin-key", state.key)
2127
- refresh().catch(showError)
2128
- })
2129
- $("refresh").addEventListener("click", () => refresh().catch(showError))
2130
-
2131
- $("collections").addEventListener("click", (event) => {
2132
- const button = event.target.closest("[data-collection]")
2133
- if (!button) return
2134
- state.collection = button.dataset.collection
2135
- renderState().catch(showError)
2136
- })
2137
- $("records").addEventListener("click", (event) => {
2138
- const row = event.target.closest("[data-id]")
2139
- if (!row) return
2140
- openEditor(row.dataset.id).catch(showError)
2141
- })
2142
-
2143
- const editor = $("editor")
2144
- async function openEditor(id) {
2145
- state.editing = id || null
2146
- $("editor-title").textContent = id ? "Edit record" : "New record"
2147
- $("editor-id").value = id || ""
2148
- $("editor-id").readOnly = Boolean(id)
2149
- $("editor-delete").hidden = !id
2150
- if (id) {
2151
- const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2152
- $("editor-value").value = JSON.stringify(record.value, null, 2)
2153
- } else {
2154
- $("editor-value").value = "{\\n \\n}"
2155
- }
2156
- editor.showModal()
2157
- }
2158
- $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
2159
- $("editor-form").addEventListener("submit", (event) => {
2160
- const submitter = event.submitter
2161
- if (!submitter || submitter.value !== "save") return
2162
- event.preventDefault()
2163
- let value
2164
- try { value = JSON.parse($("editor-value").value) }
2165
- catch { showError(new Error("Value is not JSON")); return }
2166
- const id = $("editor-id").value.trim()
2167
- const path = "/state/" + encodeURIComponent(state.collection)
2168
- const request = state.editing
2169
- ? api("PUT", path + "/" + encodeURIComponent(id), { value })
2170
- : api("POST", path, { id: id || undefined, value })
2171
- request.then(() => { editor.close(); return renderState() }).catch(showError)
2172
- })
2173
- $("editor-delete").addEventListener("click", () => {
2174
- const id = state.editing
2175
- if (!id) return
2176
- api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2177
- .then(() => { editor.close(); return renderState() })
2178
- .catch(showError)
2179
- })
2180
-
2181
- document.querySelectorAll("[data-advance]").forEach((button) => {
2182
- button.addEventListener("click", () => {
2183
- api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
2184
- })
2185
- })
2186
- $("freeze").addEventListener("click", () => {
2187
- const frozen = $("freeze").dataset.frozen === "1"
2188
- api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
2189
- })
2190
- $("clock-reset").addEventListener("click", () => {
2191
- api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
2192
- })
2193
- $("clock-set").addEventListener("submit", (event) => {
2194
- event.preventDefault()
2195
- const raw = $("clock-instant").value.trim()
2196
- const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2197
- api("POST", "/clock", { set }).then(renderClock).catch(showError)
2198
- })
2199
-
2200
- $("fault-form").addEventListener("submit", (event) => {
2201
- event.preventDefault()
2202
- const preset = $("fault-preset").value
2203
- const body = preset
2204
- ? { preset }
2205
- : {
2206
- status: Number($("fault-status").value),
2207
- ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2208
- ...($("fault-method").value ? { method: $("fault-method").value } : {})
2209
- }
2210
- if (!preset && !Number.isFinite(body.status)) {
2211
- showError(new Error("Status must be a number, or choose a preset"))
2212
- return
2213
- }
2214
- api("POST", "/faults", body).then(renderFaults).catch(showError)
2215
- })
2216
- $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2217
- $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2218
-
2219
- $("route-list").addEventListener("click", (event) => {
2220
- const button = event.target.closest("[data-route]")
2221
- if (!button) return
2222
- state.route = button.dataset.route
2223
- $("route-title").textContent = state.route
2224
- const method = state.route.split(" ")[0]
2225
- $("route-body").disabled = method === "GET" || method === "DELETE"
2226
- })
2227
- $("route-form").addEventListener("submit", async (event) => {
2228
- event.preventDefault()
2229
- if (!state.route) return showError(new Error("Choose a route first"))
2230
- const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2231
- const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2232
- let body
2233
- if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2234
- try { body = JSON.parse($("route-body").value) }
2235
- catch { return showError(new Error("Body is not JSON")) }
2236
- }
2237
- try {
2238
- const data = await api(method, concrete, body)
2239
- $("route-result").textContent = JSON.stringify(data, null, 2)
2240
- } catch (error) {
2241
- showError(error)
2242
- }
2243
- })
2244
-
2245
- function mountPanels(panels) {
2246
- const nav = $("nav")
2247
- const views = $("views")
2248
- for (const panel of panels) {
2249
- const button = document.createElement("button")
2250
- button.type = "button"
2251
- button.dataset.view = panel.id
2252
- button.textContent = panel.title
2253
- nav.append(button)
2254
- const section = document.createElement("section")
2255
- section.className = "view"
2256
- section.id = "view-" + panel.id
2257
- section.hidden = true
2258
- const title = document.createElement("h2")
2259
- title.textContent = panel.title
2260
- const lede = document.createElement("p")
2261
- lede.className = "lede"
2262
- lede.textContent = panel.description || ""
2263
- const body = document.createElement("div")
2264
- body.className = "panel-body"
2265
- body.id = "panel-" + panel.id
2266
- body.innerHTML = panel.html || ""
2267
- section.append(title, lede, body)
2268
- views.append(section)
2269
- if (panel.script) {
2270
- try {
2271
- const run = new Function("root", "api", panel.script)
2272
- run(body, panelApi)
2273
- } catch (error) {
2274
- const note = document.createElement("p")
2275
- note.className = "banner show"
2276
- note.textContent = error instanceof Error ? error.message : String(error)
2277
- body.append(note)
2278
- }
2279
- }
2280
- }
2281
- }
2282
-
2283
- loadNamespaces()
2284
- .then(() => api("GET", "/ui/manifest"))
2285
- .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2286
- .catch(showError)
2287
- })()
2288
- </script>
3089
+ ${script}
2289
3090
  </body>
2290
3091
  </html>`;
2291
3092
  };
@@ -2302,10 +3103,10 @@ var json2 = (body) => new Response(JSON.stringify(body), {
2302
3103
  });
2303
3104
  var adminUiRoutes = (service, ui) => {
2304
3105
  const shell = () => renderAdminDocument(service);
2305
- const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
3106
+ const document3 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2306
3107
  return {
2307
- "GET /ui": () => htmlResponse(document2()),
2308
- "GET /ui/": () => htmlResponse(document2()),
3108
+ "GET /ui": () => htmlResponse(document3()),
3109
+ "GET /ui/": () => htmlResponse(document3()),
2309
3110
  "GET /ui/manifest": () => json2({
2310
3111
  service,
2311
3112
  panels: (ui?.panels ?? []).map((panel) => ({
@@ -2331,11 +3132,11 @@ var EXTENSION_KEYS = {
2331
3132
  };
2332
3133
 
2333
3134
  // ../../openapi/metadata/dist/read.js
2334
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3135
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2335
3136
  var extensionOf = (holder, key2) => holder[key2];
2336
3137
  var operationMetadata = (operation) => {
2337
3138
  const raw = extensionOf(operation, EXTENSION_KEYS.operation);
2338
- const ext = isRecord2(raw) ? raw : {};
3139
+ const ext = isRecord3(raw) ? raw : {};
2339
3140
  const supported = ext.supported ?? true;
2340
3141
  const parity = ext.parity ?? {};
2341
3142
  return {
@@ -2455,9 +3256,9 @@ ${problems.map((p) => ` - ${p}`).join("\n")}`);
2455
3256
  this.name = "OperationRegistryError";
2456
3257
  }
2457
3258
  };
2458
- var verifyOperations = (document2, handlers) => {
3259
+ var verifyOperations = (document3, handlers) => {
2459
3260
  const problems = [];
2460
- const operations = listOperations(document2);
3261
+ const operations = listOperations(document3);
2461
3262
  const seen = /* @__PURE__ */ new Set();
2462
3263
  for (const operation of operations) {
2463
3264
  if (seen.has(operation.operationId))
@@ -2573,7 +3374,7 @@ var SAMPLE = 25;
2573
3374
  var WALK_LIMIT = 1e4;
2574
3375
  var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2575
3376
  var fail = (status, message) => ({ ok: false, status, message });
2576
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3377
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2577
3378
  var kindOf = (value) => {
2578
3379
  if (value === null)
2579
3380
  return "null";
@@ -2672,7 +3473,7 @@ var absorb = (accum, value) => {
2672
3473
  const kind = kindOf(value);
2673
3474
  accum.kinds.add(kind);
2674
3475
  accum.present++;
2675
- if (!isRecord3(value))
3476
+ if (!isRecord4(value))
2676
3477
  return;
2677
3478
  for (const [key2, child] of Object.entries(value)) {
2678
3479
  const nested = accum.nested.get(key2) ?? blankAccum(key2);
@@ -2697,7 +3498,7 @@ var inferFields = (records) => {
2697
3498
  if (records.length === 0)
2698
3499
  return [];
2699
3500
  const sample = records.slice(0, SAMPLE);
2700
- const objects = sample.filter((record2) => isRecord3(record2.value));
3501
+ const objects = sample.filter((record2) => isRecord4(record2.value));
2701
3502
  if (objects.length === 0) {
2702
3503
  const kinds = new Set(sample.map((record2) => kindOf(record2.value)));
2703
3504
  const list = [...kinds];
@@ -2884,7 +3685,7 @@ var patchStateRecord = (scope, name, id, value) => {
2884
3685
  const parsed = jsonValue(value);
2885
3686
  if (!parsed.ok)
2886
3687
  return parsed;
2887
- const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
3688
+ const next = isRecord4(current.value.value) && isRecord4(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2888
3689
  return replaceStateRecord(scope, name, id, next);
2889
3690
  };
2890
3691
  var deleteStateRecord = (scope, name, id) => {
@@ -2952,7 +3753,7 @@ var stateAdminRoutes = (routes) => {
2952
3753
  const scope = open(namespace);
2953
3754
  if (!scope.ok)
2954
3755
  return fromResult(scope, 201);
2955
- if (!isRecord3(body) || !("value" in body)) {
3756
+ if (!isRecord4(body) || !("value" in body)) {
2956
3757
  return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2957
3758
  }
2958
3759
  const id = body.id;
@@ -2970,7 +3771,7 @@ var stateAdminRoutes = (routes) => {
2970
3771
  const scope = open(namespace);
2971
3772
  if (!scope.ok)
2972
3773
  return fromResult(scope, 200);
2973
- if (!isRecord3(body) || !("value" in body))
3774
+ if (!isRecord4(body) || !("value" in body))
2974
3775
  return adminError2(400, 'expected {"value": <json>}');
2975
3776
  const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2976
3777
  if (replaced.ok)
@@ -2981,7 +3782,7 @@ var stateAdminRoutes = (routes) => {
2981
3782
  const scope = open(namespace);
2982
3783
  if (!scope.ok)
2983
3784
  return fromResult(scope, 200);
2984
- if (!isRecord3(body) || !("value" in body))
3785
+ if (!isRecord4(body) || !("value" in body))
2985
3786
  return adminError2(400, 'expected {"value": <json>}');
2986
3787
  const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2987
3788
  if (patched.ok)
@@ -3001,7 +3802,7 @@ var stateAdminRoutes = (routes) => {
3001
3802
  };
3002
3803
 
3003
3804
  // ../core/dist/version.js
3004
- var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
3805
+ var PACKAGE_VERSION = true ? "1.5.1" : UNRELEASED_VERSION;
3005
3806
 
3006
3807
  // ../core/dist/signing.js
3007
3808
  var encoder = new TextEncoder();
@@ -3346,9 +4147,9 @@ var createWebhookHub = (options) => {
3346
4147
  };
3347
4148
  var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3348
4149
  var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
3349
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4150
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3350
4151
  var parseEndpoint = (value) => {
3351
- if (!isRecord4(value) || typeof value.url !== "string")
4152
+ if (!isRecord5(value) || typeof value.url !== "string")
3352
4153
  return "each endpoint needs a url";
3353
4154
  try {
3354
4155
  new URL(value.url);
@@ -3365,12 +4166,12 @@ var parseEndpoint = (value) => {
3365
4166
  const events = value.events ?? value.enabledEvents;
3366
4167
  if (Array.isArray(events))
3367
4168
  endpoint.events = events.map(String);
3368
- if (isRecord4(value.tags)) {
4169
+ if (isRecord5(value.tags)) {
3369
4170
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
3370
4171
  }
3371
4172
  if (typeof value.account === "string")
3372
4173
  endpoint.tags = { ...endpoint.tags, account: value.account };
3373
- if (isRecord4(value.headers)) {
4174
+ if (isRecord5(value.headers)) {
3374
4175
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
3375
4176
  }
3376
4177
  return endpoint;
@@ -3397,7 +4198,7 @@ var webhookAdminRoutes = (hub) => ({
3397
4198
  return json4(200, { status: "ok" });
3398
4199
  },
3399
4200
  "POST /webhooks/faults": ({ body, namespace }) => {
3400
- if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
4201
+ if (!isRecord5(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3401
4202
  return adminError3(400, "mode must be duplicate, reorder or drop");
3402
4203
  }
3403
4204
  const fault = { mode: body.mode };
@@ -3413,7 +4214,7 @@ var webhookAdminRoutes = (hub) => ({
3413
4214
  }))
3414
4215
  }),
3415
4216
  "PUT /webhook-endpoints": ({ body, namespace }) => {
3416
- const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
4217
+ const list = Array.isArray(body) ? body : isRecord5(body) ? body.endpoints : void 0;
3417
4218
  if (!Array.isArray(list))
3418
4219
  return adminError3(400, "expected [{url, secret?, events?}]");
3419
4220
  const parsed = [];
@@ -3483,8 +4284,8 @@ var DroppedConnectionError = class extends TypeError {
3483
4284
  this.name = "TypeError";
3484
4285
  }
3485
4286
  };
3486
- var operationMatcher = (document2) => {
3487
- const matchers = listOperations(document2).map((operation) => ({
4287
+ var operationMatcher = (document3) => {
4288
+ const matchers = listOperations(document3).map((operation) => ({
3488
4289
  operationId: operation.operationId,
3489
4290
  method: operation.method.toUpperCase(),
3490
4291
  pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
@@ -3579,10 +4380,10 @@ var createRuntime = (options) => {
3579
4380
  const ensureBranch = (namespace, branch2, at) => {
3580
4381
  if (!BRANCH_PATTERN2.test(branch2))
3581
4382
  throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
3582
- const history = timeline(namespace);
4383
+ const history2 = timeline(namespace);
3583
4384
  if (branch2 === "main") {
3584
4385
  if (at !== void 0) {
3585
- const point = history.checkout("main", at);
4386
+ const point = history2.checkout("main", at);
3586
4387
  restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
3587
4388
  captured.set(namespace, point.value.snapshot);
3588
4389
  rng.setState(point.value.rngState);
@@ -3595,10 +4396,10 @@ var createRuntime = (options) => {
3595
4396
  return namespace;
3596
4397
  }
3597
4398
  const storage = physicalBranch(namespace, branch2);
3598
- if (!history.hasBranch(branch2)) {
4399
+ if (!history2.hasBranch(branch2)) {
3599
4400
  if (at === void 0)
3600
- history.commit(capture(namespace));
3601
- const point = history.fork(branch2, at === void 0 ? {} : { from: at });
4401
+ history2.commit(capture(namespace));
4402
+ const point = history2.fork(branch2, at === void 0 ? {} : { from: at });
3602
4403
  const branchRng = createRng(options.seed ?? 0);
3603
4404
  if (point)
3604
4405
  branchRng.setState(point.value.rngState);
@@ -3607,8 +4408,8 @@ var createRuntime = (options) => {
3607
4408
  restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
3608
4409
  if (point)
3609
4410
  captured.set(storage, point.value.snapshot);
3610
- } else if (at !== void 0 && history.head(branch2)?.id !== at) {
3611
- const point = history.checkout(branch2, at);
4411
+ } else if (at !== void 0 && history2.head(branch2)?.id !== at) {
4412
+ const point = history2.checkout(branch2, at);
3612
4413
  if (!instances.has(storage)) {
3613
4414
  const branchRng = createRng(options.seed ?? 0);
3614
4415
  branchRng.setState(point.value.rngState);
@@ -3619,7 +4420,7 @@ var createRuntime = (options) => {
3619
4420
  captured.set(storage, point.value.snapshot);
3620
4421
  } else {
3621
4422
  if (!instances.has(storage)) {
3622
- const point = history.head(branch2);
4423
+ const point = history2.head(branch2);
3623
4424
  const branchRng = createRng(options.seed ?? 0);
3624
4425
  if (point)
3625
4426
  branchRng.setState(point.value.rngState);
@@ -3643,8 +4444,8 @@ var createRuntime = (options) => {
3643
4444
  const checkout = (checkpointId, checkoutOptions = {}) => {
3644
4445
  const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
3645
4446
  const branchName = checkoutOptions.branch ?? "main";
3646
- const history = timeline(namespace);
3647
- const point = history.checkout(branchName, checkpointId);
4447
+ const history2 = timeline(namespace);
4448
+ const point = history2.checkout(branchName, checkpointId);
3648
4449
  const storage = ensureBranch(namespace, branchName);
3649
4450
  restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
3650
4451
  captured.set(storage, point.value.snapshot);
@@ -3694,9 +4495,9 @@ var createRuntime = (options) => {
3694
4495
  instance(name);
3695
4496
  restoreNamespace(sqlite, storageNamespace(name), from);
3696
4497
  captured.set(name, from);
3697
- const history = timelines.get(name);
3698
- if (history)
3699
- history.commit(capture(name), { branch: "main" });
4498
+ const history2 = timelines.get(name);
4499
+ if (history2)
4500
+ history2.commit(capture(name), { branch: "main" });
3700
4501
  else
3701
4502
  timeline(name);
3702
4503
  };
@@ -3925,10 +4726,10 @@ var createRuntime = (options) => {
3925
4726
  },
3926
4727
  release: (name, checkpointId) => timeline(name).release(checkpointId),
3927
4728
  inspect: (name) => {
3928
- const history = timeline(name);
4729
+ const history2 = timeline(name);
3929
4730
  return {
3930
- branches: history.branches(),
3931
- checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
4731
+ branches: history2.branches(),
4732
+ checkpoints: history2.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
3932
4733
  id,
3933
4734
  branch: branchName,
3934
4735
  parent,
@@ -3943,11 +4744,11 @@ var createRuntime = (options) => {
3943
4744
  } : {},
3944
4745
  routes: {
3945
4746
  ...credentialRoutes(credentials),
3946
- ...options.presets ? presetRoutes(options.presets, runtime) : {},
3947
4747
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
3948
4748
  ...options.admin?.(runtime) ?? {},
3949
- // Standard state and UI routes win a colliding key. A service adds its own keys
3950
- // beside these; it does not replace `/state` or `/ui`.
4749
+ // Shell routes win a colliding key. Fault presets are one of them: the admin page
4750
+ // maps `presets`, and a service route must not replace that list with a record.
4751
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
3951
4752
  ...stateAdminRoutes({
3952
4753
  open: stateScope,
3953
4754
  afterWrite: (namespace) => {
@@ -4022,9 +4823,12 @@ var credentialRoutes = (registry) => ({
4022
4823
  }
4023
4824
  });
4024
4825
  var presetRoutes = (presets, runtime) => ({
4025
- "GET /faults/presets": () => adminJson(200, {
4026
- presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
4027
- }),
4826
+ "GET /faults/presets": () => {
4827
+ const body = {
4828
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
4829
+ };
4830
+ return adminJson(200, body);
4831
+ },
4028
4832
  "POST /faults/presets/:name": ({ params, body, namespace }) => {
4029
4833
  const name = params.name;
4030
4834
  if (!presets[name])
@@ -4035,7 +4839,7 @@ var presetRoutes = (presets, runtime) => ({
4035
4839
  });
4036
4840
 
4037
4841
  // src/generated/openapi.ts
4038
- var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"AHA (Advanced Health Academy) partner API (Mockingbird subset)","description":"Stateful mock of the AHA at-home phlebotomy partner API: create-or-update order and cancel.\\nThe vendor has no pull API; order state reaches the partner only as inbound webhooks, which\\nthe mock emits from admin transitions (see the README). Hand-authored from the consumer's\\nwire shapes (the vendor publishes no spec).\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from aha.service.ts, aha.types.ts (zod request/response schemas) and aha.lab-provider.ts. Success responses come in one of two envelopes (raw, or {success, data}) because our two clients disagree (G-A1); the mock serves either."}},"servers":[{"url":"https://stage-api.mobileaha.com"}],"security":[{"hmacKey":[],"hmacTimestamp":[],"hmacSignature":[]},{"legacyKey":[]}],"paths":{"/v1/{partner}/create-order":{"post":{"operationId":"CreateOrder","description":"Create an order, or update it when partner_order_id already exists (the same order_number is returned). Honors X-Idempotency-Key.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/Partner"},{"$ref":"#/components/parameters/IdempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderBody"}}}},"responses":{"200":{"description":"Order created or updated (raw or wrapped envelope, per namespace setting)","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/CreateOrderResponse"},{"$ref":"#/components/schemas/WrappedCreateOrderResponse"}]}}}},"400":{"description":"Invalid request body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"Missing or invalid authentication","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"409":{"description":"Idempotency key reused with a different request, or still in flight","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/v1/{partner}/cancel":{"post":{"operationId":"CancelOrder","description":"Cancel an order by partner_order_id. The mock also accepts the AHA order_number here, because our lab-provider client sends it in that field (G-A1).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/Partner"},{"$ref":"#/components/parameters/IdempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelOrderBody"}}}},"responses":{"200":{"description":"Cancel outcome (raw or wrapped envelope; status ERROR when not cancellable)","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/CancelOrderResponse"},{"$ref":"#/components/schemas/WrappedCancelOrderResponse"}]}}}},"400":{"description":"Invalid request body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"Missing or invalid authentication","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"Unknown partner order","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"409":{"description":"Idempotency key reused with a different request, or still in flight","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}}},"components":{"securitySchemes":{"hmacKey":{"type":"apiKey","in":"header","name":"X-API-KEY"},"hmacTimestamp":{"type":"apiKey","in":"header","name":"X-TIMESTAMP","description":"Unix epoch milliseconds."},"hmacSignature":{"type":"apiKey","in":"header","name":"X-SIGNATURE","description":"base64(HMAC-SHA256(apiSecret, \\"<apiKey>:<path>:<timestamp>\\"))."},"legacyKey":{"type":"apiKey","in":"header","name":"X-Acme-Auth-Key","description":"Legacy mode (AHA_USE_LEGACY_AUTH=true), sent with X-API-Version 1.0. The real header embeds the partner's name (\`X-<Partner>-Auth-Key\`); the mock accepts any partner name."}},"parameters":{"Partner":{"name":"partner","in":"path","required":true,"description":"The partner segment AHA assigns your account (its slug), e.g. \`acme\`.","schema":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$","examples":["acme"]}},"IdempotencyKey":{"name":"X-Idempotency-Key","in":"header","required":false,"description":"Sent by the lab-provider client; the same key and body replays the stored response.","schema":{"type":"string","pattern":"^[A-Za-z0-9:_.-]{1,128}$"}}},"schemas":{"TestCode":{"type":"object","required":["test_code","test_description"],"properties":{"test_code":{"type":"string","minLength":1,"maxLength":64},"test_description":{"type":"string","maxLength":200}}},"CreateOrderBody":{"type":"object","required":["partner_order_id","patient_first_name","patient_id","patient_last_name","biological_sex","patient_dob","patient_phone_number","patient_address_line1","patient_city","patient_state","patient_zipcode","service_type","npi","ordering_physician","test_codes"],"properties":{"partner_order_id":{"type":"string","minLength":1,"maxLength":64},"patient_first_name":{"type":"string","minLength":1,"maxLength":60},"patient_id":{"type":"string","minLength":1,"maxLength":64},"patient_middle_initial":{"type":"string","maxLength":5},"patient_last_name":{"type":"string","minLength":1,"maxLength":60},"biological_sex":{"type":"string","enum":["Male","Female","Non-binary"]},"patient_dob":{"type":"string","description":"YYYY-MM-DD","maxLength":10},"patient_phone_number":{"type":"string","description":"10 digits from AhaService; the lab-provider client may send +1XXXXXXXXXX.","maxLength":20},"patient_email_address":{"type":"string","maxLength":120},"patient_address_line1":{"type":"string","minLength":1,"maxLength":120},"patient_address_line2":{"type":"string","maxLength":120},"patient_city":{"type":"string","minLength":1,"maxLength":60},"patient_state":{"type":"string","minLength":1,"maxLength":20},"patient_zipcode":{"type":"string","minLength":1,"maxLength":10},"service_type":{"type":"string","enum":["Full Service","Draw Only","Pickup Only"]},"preferred_schedule_date":{"type":"string","description":"YYYY-MM-DD","maxLength":10},"preferred_schedule_time":{"type":"string","description":"HH:MM","maxLength":8},"patient_timezone":{"type":"string","description":"IANA zone, e.g. America/New_York","maxLength":64},"npi":{"type":"string","minLength":1,"maxLength":20},"ordering_physician":{"type":"string","minLength":1,"maxLength":120},"test_codes":{"type":"array","maxItems":20,"items":{"$ref":"#/components/schemas/TestCode"}}}},"CancelOrderBody":{"type":"object","required":["partner_order_id","notes"],"properties":{"partner_order_id":{"type":"string","minLength":1,"maxLength":64,"x-mockingbird-resource-ref":{"type":"order","missing":"AC-999999999"}},"notes":{"type":"array","maxItems":5,"items":{"type":"object","required":["note_type","notes"],"properties":{"note_type":{"type":"string","enum":["CANCELLATION"]},"notes":{"type":"string","maxLength":500}}}}}},"CreateOrderResponse":{"type":"object","required":["content","message","status"],"properties":{"content":{"type":"object","required":["partner_order_id","order_number"],"properties":{"partner_order_id":{"type":"string","x-mockingbird-resource":{"type":"order","identity":true}},"order_number":{"type":"string","x-mockingbird-volatile":{"kind":"id"}}}},"message":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","ERROR"]}}},"WrappedCreateOrderResponse":{"type":"object","required":["success","data"],"properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CreateOrderResponse"}}},"CancelOrderResponse":{"type":"object","required":["message","status"],"properties":{"message":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","ERROR"]}}},"WrappedCancelOrderResponse":{"type":"object","required":["success","data"],"properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CancelOrderResponse"}}},"ErrorBody":{"type":"object","required":["status","message"],"properties":{"status":{"type":"string","enum":["ERROR"]},"message":{"type":"string"},"errors":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}}}}}}}`);
4842
+ var document2 = JSON.parse(`{"openapi":"3.1.0","info":{"title":"AHA (Advanced Health Academy) partner API (Mockingbird subset)","description":"Stateful mock of the AHA at-home phlebotomy partner API: create-or-update order and cancel.\\nThe vendor has no pull API; order state reaches the partner only as inbound webhooks, which\\nthe mock emits from admin transitions (see the README). Hand-authored from the consumer's\\nwire shapes (the vendor publishes no spec).\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from aha.service.ts, aha.types.ts (zod request/response schemas) and aha.lab-provider.ts. Success responses come in one of two envelopes (raw, or {success, data}) because our two clients disagree (G-A1); the mock serves either."}},"servers":[{"url":"https://stage-api.mobileaha.com"}],"security":[{"hmacKey":[],"hmacTimestamp":[],"hmacSignature":[]},{"legacyKey":[]}],"paths":{"/v1/{partner}/create-order":{"post":{"operationId":"CreateOrder","description":"Create an order, or update it when partner_order_id already exists (the same order_number is returned). Honors X-Idempotency-Key.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/Partner"},{"$ref":"#/components/parameters/IdempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderBody"}}}},"responses":{"200":{"description":"Order created or updated (raw or wrapped envelope, per namespace setting)","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/CreateOrderResponse"},{"$ref":"#/components/schemas/WrappedCreateOrderResponse"}]}}}},"400":{"description":"Invalid request body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"Missing or invalid authentication","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"409":{"description":"Idempotency key reused with a different request, or still in flight","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}},"/v1/{partner}/cancel":{"post":{"operationId":"CancelOrder","description":"Cancel an order by partner_order_id. The mock also accepts the AHA order_number here, because our lab-provider client sends it in that field (G-A1).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"$ref":"#/components/parameters/Partner"},{"$ref":"#/components/parameters/IdempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelOrderBody"}}}},"responses":{"200":{"description":"Cancel outcome (raw or wrapped envelope; status ERROR when not cancellable)","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/CancelOrderResponse"},{"$ref":"#/components/schemas/WrappedCancelOrderResponse"}]}}}},"400":{"description":"Invalid request body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"401":{"description":"Missing or invalid authentication","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"404":{"description":"Unknown partner order","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"409":{"description":"Idempotency key reused with a different request, or still in flight","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"429":{"description":"Rate limited","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}}}}}},"components":{"securitySchemes":{"hmacKey":{"type":"apiKey","in":"header","name":"X-API-KEY"},"hmacTimestamp":{"type":"apiKey","in":"header","name":"X-TIMESTAMP","description":"Unix epoch milliseconds."},"hmacSignature":{"type":"apiKey","in":"header","name":"X-SIGNATURE","description":"base64(HMAC-SHA256(apiSecret, \\"<apiKey>:<path>:<timestamp>\\"))."},"legacyKey":{"type":"apiKey","in":"header","name":"X-Acme-Auth-Key","description":"Legacy mode (AHA_USE_LEGACY_AUTH=true), sent with X-API-Version 1.0. The real header embeds the partner's name (\`X-<Partner>-Auth-Key\`); the mock accepts any partner name."}},"parameters":{"Partner":{"name":"partner","in":"path","required":true,"description":"The partner segment AHA assigns your account (its slug), e.g. \`acme\`.","schema":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,64}$","examples":["acme"]}},"IdempotencyKey":{"name":"X-Idempotency-Key","in":"header","required":false,"description":"Sent by the lab-provider client; the same key and body replays the stored response.","schema":{"type":"string","pattern":"^[A-Za-z0-9:_.-]{1,128}$"}}},"schemas":{"TestCode":{"type":"object","required":["test_code","test_description"],"properties":{"test_code":{"type":"string","minLength":1,"maxLength":64},"test_description":{"type":"string","maxLength":200}}},"CreateOrderBody":{"type":"object","required":["partner_order_id","patient_first_name","patient_id","patient_last_name","biological_sex","patient_dob","patient_phone_number","patient_address_line1","patient_city","patient_state","patient_zipcode","service_type","npi","ordering_physician","test_codes"],"properties":{"partner_order_id":{"type":"string","minLength":1,"maxLength":64},"patient_first_name":{"type":"string","minLength":1,"maxLength":60},"patient_id":{"type":"string","minLength":1,"maxLength":64},"patient_middle_initial":{"type":"string","maxLength":5},"patient_last_name":{"type":"string","minLength":1,"maxLength":60},"biological_sex":{"type":"string","enum":["Male","Female","Non-binary"]},"patient_dob":{"type":"string","description":"YYYY-MM-DD","maxLength":10},"patient_phone_number":{"type":"string","description":"10 digits from AhaService; the lab-provider client may send +1XXXXXXXXXX.","maxLength":20},"patient_email_address":{"type":"string","maxLength":120},"patient_address_line1":{"type":"string","minLength":1,"maxLength":120},"patient_address_line2":{"type":"string","maxLength":120},"patient_city":{"type":"string","minLength":1,"maxLength":60},"patient_state":{"type":"string","minLength":1,"maxLength":20},"patient_zipcode":{"type":"string","minLength":1,"maxLength":10},"service_type":{"type":"string","enum":["Full Service","Draw Only","Pickup Only"]},"preferred_schedule_date":{"type":"string","description":"YYYY-MM-DD","maxLength":10},"preferred_schedule_time":{"type":"string","description":"HH:MM","maxLength":8},"patient_timezone":{"type":"string","description":"IANA zone, e.g. America/New_York","maxLength":64},"npi":{"type":"string","minLength":1,"maxLength":20},"ordering_physician":{"type":"string","minLength":1,"maxLength":120},"test_codes":{"type":"array","maxItems":20,"items":{"$ref":"#/components/schemas/TestCode"}}}},"CancelOrderBody":{"type":"object","required":["partner_order_id","notes"],"properties":{"partner_order_id":{"type":"string","minLength":1,"maxLength":64,"x-mockingbird-resource-ref":{"type":"order","missing":"AC-999999999"}},"notes":{"type":"array","maxItems":5,"items":{"type":"object","required":["note_type","notes"],"properties":{"note_type":{"type":"string","enum":["CANCELLATION"]},"notes":{"type":"string","maxLength":500}}}}}},"CreateOrderResponse":{"type":"object","required":["content","message","status"],"properties":{"content":{"type":"object","required":["partner_order_id","order_number"],"properties":{"partner_order_id":{"type":"string","x-mockingbird-resource":{"type":"order","identity":true}},"order_number":{"type":"string","x-mockingbird-volatile":{"kind":"id"}}}},"message":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","ERROR"]}}},"WrappedCreateOrderResponse":{"type":"object","required":["success","data"],"properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CreateOrderResponse"}}},"CancelOrderResponse":{"type":"object","required":["message","status"],"properties":{"message":{"type":"string"},"status":{"type":"string","enum":["SUCCESS","ERROR"]}}},"WrappedCancelOrderResponse":{"type":"object","required":["success","data"],"properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CancelOrderResponse"}}},"ErrorBody":{"type":"object","required":["status","message"],"properties":{"status":{"type":"string","enum":["ERROR"]},"message":{"type":"string"},"errors":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}}}}}}}`);
4039
4843
  var operationIds = ["CreateOrder", "CancelOrder"];
4040
4844
  var supportedOperationIds = ["CreateOrder", "CancelOrder"];
4041
4845
 
@@ -4222,11 +5026,11 @@ var AHA_PRESETS = {
4222
5026
  };
4223
5027
  var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4224
5028
  var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
4225
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5029
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4226
5030
  var parseAutoSchedule = (value) => {
4227
5031
  if (value === null) return null;
4228
5032
  if (typeof value === "number" && value >= 0) return { afterMs: value };
4229
- if (!isRecord5(value) || typeof value.afterMs !== "number" || value.afterMs < 0) {
5033
+ if (!isRecord6(value) || typeof value.afterMs !== "number" || value.afterMs < 0) {
4230
5034
  return "autoSchedule must be {afterMs, leadMs?}, a number of ms, or null";
4231
5035
  }
4232
5036
  if (value.leadMs !== void 0 && typeof value.leadMs !== "number") return "leadMs: number";
@@ -4239,7 +5043,7 @@ var parseCredentials = (value) => {
4239
5043
  if (!Array.isArray(value)) return "credentials: [{apiKey, apiSecret?}]";
4240
5044
  const out = [];
4241
5045
  for (const each of value) {
4242
- if (!isRecord5(each) || typeof each.apiKey !== "string") return "each credential needs apiKey";
5046
+ if (!isRecord6(each) || typeof each.apiKey !== "string") return "each credential needs apiKey";
4243
5047
  out.push({
4244
5048
  apiKey: each.apiKey,
4245
5049
  ...typeof each.apiSecret === "string" ? { apiSecret: each.apiSecret } : {}
@@ -4257,7 +5061,7 @@ var visible = (settings) => ({
4257
5061
  var adminRoutes = (runtime) => ({
4258
5062
  "GET /orders": ({ namespace }) => json5(200, { orders: runtime.instance(namespace).orders() }),
4259
5063
  "POST /orders/:partnerOrderId/transition": ({ params, body, namespace }) => {
4260
- if (!isRecord5(body) || typeof body.status !== "string") {
5064
+ if (!isRecord6(body) || typeof body.status !== "string") {
4261
5065
  return adminError4(
4262
5066
  400,
4263
5067
  'expected {"status": "<AHA status>", "drawStatus"?, "scheduledAt"?, "timeZone"?}'
@@ -4279,7 +5083,7 @@ var adminRoutes = (runtime) => ({
4279
5083
  },
4280
5084
  "GET /settings": ({ namespace }) => json5(200, visible(runtime.instance(namespace).state.current())),
4281
5085
  "PUT /settings": ({ body, namespace }) => {
4282
- if (!isRecord5(body)) return adminError4(400, "expected a JSON object");
5086
+ if (!isRecord6(body)) return adminError4(400, "expected a JSON object");
4283
5087
  const patch = {};
4284
5088
  if (body.envelope !== void 0) {
4285
5089
  if (body.envelope !== "raw" && body.envelope !== "wrapped")
@@ -4326,7 +5130,7 @@ var createRuntime2 = (options = {}) => {
4326
5130
  });
4327
5131
  const runtime = createRuntime({
4328
5132
  name: AHA_NAMESPACE,
4329
- document,
5133
+ document: document2,
4330
5134
  ...options.sqlite ? { sqlite: options.sqlite } : {},
4331
5135
  ...options.clock ? { clock: options.clock } : {},
4332
5136
  ...options.seed !== void 0 ? { seed: options.seed } : {},
@@ -4443,7 +5247,7 @@ var AhaAPI = class {
4443
5247
  CancelOrder: (context) => this.idempotent(context, () => this.cancelOrder(context))
4444
5248
  });
4445
5249
  this.service = createService({
4446
- document,
5250
+ document: document2,
4447
5251
  handlers,
4448
5252
  sqlite,
4449
5253
  namespace,
@@ -4702,7 +5506,7 @@ var AhaAPI = class {
4702
5506
  };
4703
5507
 
4704
5508
  export {
4705
- document,
5509
+ document2 as document,
4706
5510
  operationIds,
4707
5511
  supportedOperationIds,
4708
5512
  ORDER_STATUSES,
@@ -4718,4 +5522,4 @@ export {
4718
5522
  apiKeyCredential,
4719
5523
  AhaAPI
4720
5524
  };
4721
- //# sourceMappingURL=chunk-WC5YEEUF.js.map
5525
+ //# sourceMappingURL=chunk-NAZV2NIY.js.map