@crvouga/mockingbird-service-customerio 1.3.0 → 1.5.0

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.
@@ -38,30 +38,30 @@ var createClock = (source = Date.now) => {
38
38
  var Collection = class {
39
39
  sqlite;
40
40
  namespace;
41
- name;
42
- constructor(sqlite, namespace, name) {
41
+ collectionName;
42
+ constructor(sqlite, namespace, collectionName) {
43
43
  this.sqlite = sqlite;
44
44
  this.namespace = namespace;
45
- this.name = name;
45
+ this.collectionName = collectionName;
46
46
  }
47
47
  bumpCollectionSeq() {
48
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
48
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.collectionName);
49
49
  const next = (row?.value ?? 0) + 1;
50
50
  this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
51
- ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
51
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.collectionName, next);
52
52
  return next;
53
53
  }
54
54
  nextSequence() {
55
55
  return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
56
  }
57
57
  get(id) {
58
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
58
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
59
59
  if (!row)
60
60
  return void 0;
61
61
  return JSON.parse(row.value).value;
62
62
  }
63
63
  has(id) {
64
- const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
64
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
65
65
  return row !== void 0;
66
66
  }
67
67
  /** Insert a new record, assigning it the next sequence number. */
@@ -71,32 +71,32 @@ var Collection = class {
71
71
  const stored = { seq, value };
72
72
  this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
73
73
  VALUES (?, ?, ?, ?, ?)
74
- ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
74
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.collectionName, id, seq, JSON.stringify(stored));
75
75
  return stored;
76
76
  });
77
77
  }
78
78
  /** Replace an existing record's value, keeping its position. */
79
79
  update(id, value) {
80
80
  return this.sqlite.transaction(() => {
81
- const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
81
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
82
82
  if (!row)
83
83
  return void 0;
84
84
  const stored = { seq: row.seq, value };
85
- this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
85
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.collectionName, id);
86
86
  return stored;
87
87
  });
88
88
  }
89
89
  delete(id) {
90
- const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
90
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.collectionName, id);
91
91
  return result.changes > 0;
92
92
  }
93
93
  /** How many records the collection holds, without reading them. */
94
94
  count() {
95
- const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.collectionName);
96
96
  return Number(row?.n ?? 0);
97
97
  }
98
98
  list(options = {}) {
99
- const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
99
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.collectionName);
100
100
  const out = [];
101
101
  for (const row of rows) {
102
102
  const stored = JSON.parse(row.value);
@@ -353,16 +353,18 @@ var createControlPlane = (context) => {
353
353
  uptimeMs: context.wallNow() - context.startedAt,
354
354
  clock: context.clock.state(),
355
355
  namespaces: context.namespaces().length,
356
+ adminUi: `${ADMIN_PREFIX}/ui`,
356
357
  ...context.describe()
357
358
  });
358
359
  }
359
360
  if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
361
  return void 0;
361
362
  }
362
- if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
364
+ const shell = request.method === "GET" && (path === "/ui" || path === "/ui/");
365
+ if (!shell && context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
366
  return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
367
  }
365
- const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
368
  for (const route of routes) {
367
369
  if (route.method !== request.method)
368
370
  continue;
@@ -556,10 +558,10 @@ var OpenAPIReferenceError = class extends Error {
556
558
  };
557
559
  var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
558
560
  var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
559
- var resolveRef = (document2, ref) => {
561
+ var resolveRef = (document3, ref) => {
560
562
  if (!ref.startsWith("#/"))
561
563
  throw new OpenAPIReferenceError(ref);
562
- let cursor = document2;
564
+ let cursor = document3;
563
565
  for (const raw of ref.slice(2).split("/")) {
564
566
  const segment = unescapePointer(raw);
565
567
  if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
@@ -571,14 +573,14 @@ var resolveRef = (document2, ref) => {
571
573
  throw new OpenAPIReferenceError(ref);
572
574
  return cursor;
573
575
  };
574
- var deref = (document2, value) => {
576
+ var deref = (document3, value) => {
575
577
  let current = value;
576
578
  const seen = /* @__PURE__ */ new Set();
577
579
  while (isReference(current)) {
578
580
  if (seen.has(current.$ref))
579
581
  throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
580
582
  seen.add(current.$ref);
581
- current = resolveRef(document2, current.$ref);
583
+ current = resolveRef(document3, current.$ref);
582
584
  }
583
585
  return current;
584
586
  };
@@ -596,36 +598,36 @@ var HTTP_METHODS = [
596
598
  ];
597
599
 
598
600
  // ../../openapi/core/dist/document.js
599
- var mergeParameters = (document2, item, own) => {
601
+ var mergeParameters = (document3, item, own) => {
600
602
  const merged = /* @__PURE__ */ new Map();
601
603
  for (const raw of item.parameters ?? []) {
602
- const parameter = deref(document2, raw);
604
+ const parameter = deref(document3, raw);
603
605
  merged.set(`${parameter.in}:${parameter.name}`, parameter);
604
606
  }
605
607
  for (const raw of own ?? []) {
606
- const parameter = deref(document2, raw);
608
+ const parameter = deref(document3, raw);
607
609
  merged.set(`${parameter.in}:${parameter.name}`, parameter);
608
610
  }
609
611
  return [...merged.values()];
610
612
  };
611
- var listOperations = (document2) => {
613
+ var listOperations = (document3) => {
612
614
  const operations = [];
613
- for (const [path, item] of Object.entries(document2.paths)) {
615
+ for (const [path, item] of Object.entries(document3.paths)) {
614
616
  for (const method of HTTP_METHODS) {
615
617
  const operation = item[method];
616
618
  if (operation?.operationId === void 0)
617
619
  continue;
618
620
  const responses = {};
619
621
  for (const [status, response] of Object.entries(operation.responses)) {
620
- responses[status] = deref(document2, response);
622
+ responses[status] = deref(document3, response);
621
623
  }
622
624
  operations.push({
623
625
  operationId: operation.operationId,
624
626
  method,
625
627
  path,
626
628
  operation,
627
- parameters: mergeParameters(document2, item, operation.parameters),
628
- requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
629
+ parameters: mergeParameters(document3, item, operation.parameters),
630
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document3, operation.requestBody),
629
631
  responses
630
632
  });
631
633
  }
@@ -634,7 +636,7 @@ var listOperations = (document2) => {
634
636
  };
635
637
 
636
638
  // ../../openapi/core/dist/schema.js
637
- var resolveSchema = (document2, schema) => {
639
+ var resolveSchema = (document3, schema) => {
638
640
  let current = schema;
639
641
  const seen = /* @__PURE__ */ new Set();
640
642
  while (typeof current.$ref === "string") {
@@ -643,7 +645,7 @@ var resolveSchema = (document2, schema) => {
643
645
  break;
644
646
  seen.add(ref);
645
647
  const { $ref: _ignored, ...siblings } = current;
646
- const target = resolveRef(document2, ref);
648
+ const target = resolveRef(document3, ref);
647
649
  current = { ...target, ...siblings };
648
650
  }
649
651
  if (current.nullable === true) {
@@ -714,71 +716,71 @@ var FORMAT_PATTERNS = {
714
716
  ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
715
717
  };
716
718
  var graphemeLength = (value) => [...value].length;
717
- var validateValue = (document2, schema, value, path = []) => {
719
+ var validateValue = (document3, schema, value, path = []) => {
718
720
  const errors = [];
719
- const s = resolveSchema(document2, schema);
720
- const fail = (message) => errors.push({ path, message });
721
+ const s = resolveSchema(document3, schema);
722
+ const fail2 = (message) => errors.push({ path, message });
721
723
  const actual = jsonTypeOf(value);
722
724
  if (actual === "undefined") {
723
- fail("value is undefined");
725
+ fail2("value is undefined");
724
726
  return errors;
725
727
  }
726
728
  const types = schemaTypes(s);
727
729
  if (types.length > 0) {
728
730
  const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
729
731
  if (!ok) {
730
- fail(`expected type ${types.join("|")}, got ${actual}`);
732
+ fail2(`expected type ${types.join("|")}, got ${actual}`);
731
733
  return errors;
732
734
  }
733
735
  }
734
736
  if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
735
- fail("value not in enum");
737
+ fail2("value not in enum");
736
738
  }
737
739
  if (s.const !== void 0 && !deepEqual(s.const, value))
738
- fail("value does not equal const");
740
+ fail2("value does not equal const");
739
741
  if (typeof value === "string") {
740
742
  const length = graphemeLength(value);
741
743
  if (s.minLength !== void 0 && length < s.minLength)
742
- fail(`length ${length} < minLength ${s.minLength}`);
744
+ fail2(`length ${length} < minLength ${s.minLength}`);
743
745
  if (s.maxLength !== void 0 && length > s.maxLength)
744
- fail(`length ${length} > maxLength ${s.maxLength}`);
746
+ fail2(`length ${length} > maxLength ${s.maxLength}`);
745
747
  if (s.pattern !== void 0) {
746
748
  try {
747
749
  if (!new RegExp(s.pattern, "u").test(value))
748
- fail(`does not match pattern ${s.pattern}`);
750
+ fail2(`does not match pattern ${s.pattern}`);
749
751
  } catch {
750
752
  }
751
753
  }
752
754
  if (s.format !== void 0) {
753
755
  const pattern = FORMAT_PATTERNS[s.format];
754
756
  if (pattern && !pattern.test(value))
755
- fail(`does not match format ${s.format}`);
757
+ fail2(`does not match format ${s.format}`);
756
758
  }
757
759
  }
758
760
  if (typeof value === "number") {
759
761
  if (s.minimum !== void 0 && value < s.minimum)
760
- fail(`${value} < minimum ${s.minimum}`);
762
+ fail2(`${value} < minimum ${s.minimum}`);
761
763
  if (s.maximum !== void 0 && value > s.maximum)
762
- fail(`${value} > maximum ${s.maximum}`);
764
+ fail2(`${value} > maximum ${s.maximum}`);
763
765
  if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
764
- fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
766
+ fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
765
767
  if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
766
- fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
768
+ fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
767
769
  if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
768
- fail(`${value} is not a multiple of ${s.multipleOf}`);
770
+ fail2(`${value} is not a multiple of ${s.multipleOf}`);
769
771
  }
770
772
  }
771
773
  if (Array.isArray(value)) {
772
774
  if (s.minItems !== void 0 && value.length < s.minItems)
773
- fail(`${value.length} items < minItems ${s.minItems}`);
775
+ fail2(`${value.length} items < minItems ${s.minItems}`);
774
776
  if (s.maxItems !== void 0 && value.length > s.maxItems)
775
- fail(`${value.length} items > maxItems ${s.maxItems}`);
777
+ fail2(`${value.length} items > maxItems ${s.maxItems}`);
776
778
  if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
777
- fail("items are not unique");
779
+ fail2("items are not unique");
778
780
  value.forEach((item, i) => {
779
781
  const itemSchema = s.prefixItems?.[i] ?? s.items;
780
782
  if (itemSchema)
781
- errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
783
+ errors.push(...validateValue(document3, itemSchema, item, [...path, i]));
782
784
  });
783
785
  }
784
786
  if (actual === "object") {
@@ -786,41 +788,41 @@ var validateValue = (document2, schema, value, path = []) => {
786
788
  const keys = Object.keys(record);
787
789
  for (const name of s.required ?? [])
788
790
  if (!(name in record))
789
- fail(`missing required property ${name}`);
791
+ fail2(`missing required property ${name}`);
790
792
  if (s.minProperties !== void 0 && keys.length < s.minProperties)
791
- fail(`${keys.length} properties < minProperties ${s.minProperties}`);
793
+ fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
792
794
  if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
793
- fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
795
+ fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
794
796
  for (const key of keys) {
795
797
  const property = s.properties?.[key];
796
798
  if (property) {
797
- errors.push(...validateValue(document2, property, record[key], [...path, key]));
799
+ errors.push(...validateValue(document3, property, record[key], [...path, key]));
798
800
  continue;
799
801
  }
800
802
  if (s.additionalProperties === false)
801
- fail(`unexpected property ${key}`);
803
+ fail2(`unexpected property ${key}`);
802
804
  else if (typeof s.additionalProperties === "object") {
803
- errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
805
+ errors.push(...validateValue(document3, s.additionalProperties, record[key], [...path, key]));
804
806
  }
805
807
  if (s.propertyNames) {
806
- const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
808
+ const nameErrors = validateValue(document3, s.propertyNames, key, [...path, key]);
807
809
  if (nameErrors.length > 0)
808
- fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
810
+ fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
809
811
  }
810
812
  }
811
813
  }
812
814
  if (s.allOf)
813
815
  for (const branch of s.allOf)
814
- errors.push(...validateValue(document2, branch, value, path));
815
- if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
816
- fail("matches no anyOf branch");
816
+ errors.push(...validateValue(document3, branch, value, path));
817
+ if (s.anyOf && !s.anyOf.some((branch) => validateValue(document3, branch, value).length === 0))
818
+ fail2("matches no anyOf branch");
817
819
  if (s.oneOf) {
818
- const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
820
+ const matches2 = s.oneOf.filter((branch) => validateValue(document3, branch, value).length === 0).length;
819
821
  if (matches2 !== 1)
820
- fail(`matches ${matches2} oneOf branches, expected exactly 1`);
822
+ fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
821
823
  }
822
- if (s.not && validateValue(document2, s.not, value).length === 0)
823
- fail("matches forbidden `not` schema");
824
+ if (s.not && validateValue(document3, s.not, value).length === 0)
825
+ fail2("matches forbidden `not` schema");
824
826
  return errors;
825
827
  };
826
828
 
@@ -1429,6 +1431,1737 @@ var clearNamespace = (sqlite, namespace) => {
1429
1431
  });
1430
1432
  };
1431
1433
 
1434
+ // ../../ui/dist/reset.js
1435
+ var CSS_RESET = `*,
1436
+ *::before,
1437
+ *::after {
1438
+ box-sizing: border-box;
1439
+ margin: 0;
1440
+ padding: 0;
1441
+ }
1442
+
1443
+ * {
1444
+ scrollbar-width: thin;
1445
+ scrollbar-color: color-mix(in srgb, CanvasText 35%, Canvas) Canvas;
1446
+ }
1447
+
1448
+ *::-webkit-scrollbar {
1449
+ width: 12px;
1450
+ height: 12px;
1451
+ }
1452
+
1453
+ *::-webkit-scrollbar-track,
1454
+ *::-webkit-scrollbar-corner {
1455
+ background: Canvas;
1456
+ }
1457
+
1458
+ *::-webkit-scrollbar-thumb {
1459
+ background: color-mix(in srgb, CanvasText 35%, Canvas);
1460
+ border: 3px solid Canvas;
1461
+ border-radius: 999px;
1462
+ }
1463
+
1464
+ html {
1465
+ hanging-punctuation: first allow-end last;
1466
+ -webkit-text-size-adjust: none;
1467
+ text-size-adjust: none;
1468
+ tab-size: 4;
1469
+ font-family:
1470
+ ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI",
1471
+ "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
1472
+ font-size: 16px;
1473
+ line-height: 1.5;
1474
+ -webkit-font-smoothing: antialiased;
1475
+ -moz-osx-font-smoothing: grayscale;
1476
+ text-rendering: optimizeLegibility;
1477
+ -webkit-tap-highlight-color: transparent;
1478
+ scroll-behavior: smooth;
1479
+ background: Canvas;
1480
+ color: CanvasText;
1481
+ }
1482
+
1483
+ body {
1484
+ min-height: 100svh;
1485
+ line-height: 1.5;
1486
+ background: Canvas;
1487
+ color: CanvasText;
1488
+ }
1489
+
1490
+ h1 {
1491
+ font-size: 2em;
1492
+ }
1493
+
1494
+ h2 {
1495
+ font-size: 1.5em;
1496
+ }
1497
+
1498
+ h3 {
1499
+ font-size: 1.17em;
1500
+ }
1501
+
1502
+ h4 {
1503
+ font-size: 1em;
1504
+ }
1505
+
1506
+ h5 {
1507
+ font-size: 0.83em;
1508
+ }
1509
+
1510
+ h6 {
1511
+ font-size: 0.67em;
1512
+ }
1513
+
1514
+ h1,
1515
+ h2,
1516
+ h3,
1517
+ h4,
1518
+ h5,
1519
+ h6 {
1520
+ font-weight: 700;
1521
+ line-height: 1.2;
1522
+ text-wrap: balance;
1523
+ overflow-wrap: break-word;
1524
+ }
1525
+
1526
+ p,
1527
+ li,
1528
+ figcaption,
1529
+ dd,
1530
+ dt,
1531
+ blockquote {
1532
+ overflow-wrap: break-word;
1533
+ }
1534
+
1535
+ p,
1536
+ li,
1537
+ figcaption,
1538
+ blockquote {
1539
+ text-wrap: pretty;
1540
+ }
1541
+
1542
+ ul,
1543
+ ol,
1544
+ menu {
1545
+ list-style: none;
1546
+ }
1547
+
1548
+ a {
1549
+ color: inherit;
1550
+ text-decoration: underline;
1551
+ text-decoration-thickness: 1px;
1552
+ text-underline-offset: 0.15em;
1553
+ text-decoration-skip-ink: auto;
1554
+ }
1555
+
1556
+ b,
1557
+ strong {
1558
+ font-weight: 700;
1559
+ }
1560
+
1561
+ small {
1562
+ font-size: 0.875em;
1563
+ }
1564
+
1565
+ code,
1566
+ kbd,
1567
+ samp,
1568
+ pre {
1569
+ font-family: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1570
+ font-size: 1em;
1571
+ }
1572
+
1573
+ sub,
1574
+ sup {
1575
+ font-size: 75%;
1576
+ line-height: 0;
1577
+ position: relative;
1578
+ vertical-align: baseline;
1579
+ }
1580
+
1581
+ sub {
1582
+ bottom: -0.25em;
1583
+ }
1584
+
1585
+ sup {
1586
+ top: -0.5em;
1587
+ }
1588
+
1589
+ abbr[title] {
1590
+ text-decoration: underline dotted;
1591
+ text-underline-offset: 0.15em;
1592
+ }
1593
+
1594
+ mark {
1595
+ background: Mark;
1596
+ color: MarkText;
1597
+ }
1598
+
1599
+ hr {
1600
+ height: 0;
1601
+ border: 0;
1602
+ border-top: 1px solid color-mix(in srgb, CanvasText 20%, transparent);
1603
+ color: inherit;
1604
+ }
1605
+
1606
+ img,
1607
+ picture,
1608
+ video,
1609
+ canvas {
1610
+ display: block;
1611
+ max-width: 100%;
1612
+ }
1613
+
1614
+ img,
1615
+ video {
1616
+ height: auto;
1617
+ }
1618
+
1619
+ svg {
1620
+ overflow: hidden;
1621
+ }
1622
+
1623
+ iframe {
1624
+ border: 0;
1625
+ max-width: 100%;
1626
+ }
1627
+
1628
+ table {
1629
+ border-collapse: collapse;
1630
+ border-spacing: 0;
1631
+ }
1632
+
1633
+ fieldset {
1634
+ border: 0;
1635
+ min-inline-size: 0;
1636
+ }
1637
+
1638
+ legend {
1639
+ padding: 0;
1640
+ }
1641
+
1642
+ button,
1643
+ input,
1644
+ select,
1645
+ textarea,
1646
+ optgroup {
1647
+ font: inherit;
1648
+ letter-spacing: inherit;
1649
+ color: inherit;
1650
+ margin: 0;
1651
+ vertical-align: middle;
1652
+ }
1653
+
1654
+ button,
1655
+ input[type="button"],
1656
+ input[type="submit"],
1657
+ input[type="reset"] {
1658
+ appearance: none;
1659
+ background: none;
1660
+ border: 0;
1661
+ padding: 0;
1662
+ cursor: pointer;
1663
+ text-align: center;
1664
+ }
1665
+
1666
+ input,
1667
+ textarea,
1668
+ select {
1669
+ background-color: Canvas;
1670
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1671
+ border-radius: 0;
1672
+ padding: 0.5em 0.65em;
1673
+ }
1674
+
1675
+ input[type="checkbox"],
1676
+ input[type="radio"],
1677
+ input[type="range"],
1678
+ input[type="file"],
1679
+ input[type="color"],
1680
+ input[type="button"],
1681
+ input[type="submit"],
1682
+ input[type="reset"],
1683
+ input[type="image"],
1684
+ input[type="hidden"] {
1685
+ background: none;
1686
+ border: 0;
1687
+ padding: 0;
1688
+ border-radius: 0;
1689
+ }
1690
+
1691
+ input[type="checkbox"],
1692
+ input[type="radio"] {
1693
+ accent-color: CanvasText;
1694
+ }
1695
+
1696
+ input[type="search"] {
1697
+ appearance: none;
1698
+ background-color: Canvas;
1699
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1700
+ }
1701
+
1702
+ input[type="search"]::-webkit-search-decoration,
1703
+ input[type="search"]::-webkit-search-cancel-button,
1704
+ input[type="search"]::-webkit-search-results-button,
1705
+ input[type="search"]::-webkit-search-results-decoration {
1706
+ -webkit-appearance: none;
1707
+ display: none;
1708
+ }
1709
+
1710
+ input[type="number"] {
1711
+ appearance: textfield;
1712
+ background-color: Canvas;
1713
+ border: 1px solid color-mix(in srgb, CanvasText 28%, transparent);
1714
+ }
1715
+
1716
+ input[type="number"]::-webkit-inner-spin-button,
1717
+ input[type="number"]::-webkit-outer-spin-button {
1718
+ -webkit-appearance: none;
1719
+ margin: 0;
1720
+ }
1721
+
1722
+ textarea {
1723
+ resize: vertical;
1724
+ }
1725
+
1726
+ ::placeholder {
1727
+ opacity: 1;
1728
+ color: color-mix(in srgb, CanvasText 45%, transparent);
1729
+ }
1730
+
1731
+ :focus-visible {
1732
+ outline: 2px solid CanvasText;
1733
+ outline-offset: 2px;
1734
+ }
1735
+
1736
+ :focus:not(:focus-visible) {
1737
+ outline: none;
1738
+ }
1739
+
1740
+ :disabled,
1741
+ [disabled] {
1742
+ cursor: default;
1743
+ opacity: 0.6;
1744
+ }
1745
+
1746
+ label,
1747
+ summary,
1748
+ select,
1749
+ [role="button"] {
1750
+ cursor: pointer;
1751
+ }
1752
+
1753
+ summary {
1754
+ display: list-item;
1755
+ }
1756
+
1757
+ details {
1758
+ display: block;
1759
+ }
1760
+
1761
+ dialog {
1762
+ margin: auto;
1763
+ padding: 1rem;
1764
+ border: 1px solid color-mix(in srgb, CanvasText 20%, transparent);
1765
+ background: Canvas;
1766
+ color: CanvasText;
1767
+ max-width: calc(100vw - 2rem);
1768
+ max-height: calc(100svh - 2rem);
1769
+ }
1770
+
1771
+ dialog:not([open]) {
1772
+ display: none;
1773
+ }
1774
+
1775
+ ::backdrop {
1776
+ background: color-mix(in srgb, CanvasText 40%, transparent);
1777
+ }
1778
+
1779
+ [hidden] {
1780
+ display: none !important;
1781
+ }
1782
+
1783
+ ::selection {
1784
+ background: Highlight;
1785
+ color: HighlightText;
1786
+ }
1787
+
1788
+ @media (prefers-reduced-motion: reduce) {
1789
+ *,
1790
+ *::before,
1791
+ *::after {
1792
+ animation-duration: 0.01ms !important;
1793
+ animation-iteration-count: 1 !important;
1794
+ transition-duration: 0.01ms !important;
1795
+ scroll-behavior: auto !important;
1796
+ }
1797
+ }
1798
+
1799
+ @media (pointer: coarse) {
1800
+ input,
1801
+ select,
1802
+ textarea {
1803
+ font-size: max(16px, 1em);
1804
+ }
1805
+ }`;
1806
+
1807
+ // ../core/dist/admin-client.js
1808
+ function isRecord2(value) {
1809
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1810
+ }
1811
+ function mountAdminBrand(doc, host, service, catalog) {
1812
+ const clip = (value, max) => {
1813
+ if (typeof value !== "string")
1814
+ return null;
1815
+ const trimmed = value.trim();
1816
+ if (trimmed === "")
1817
+ return null;
1818
+ return trimmed.length > max ? trimmed.slice(0, max) : trimmed;
1819
+ };
1820
+ const httpUrl = (value) => {
1821
+ if (typeof value !== "string" || value.length > 2e3)
1822
+ return null;
1823
+ try {
1824
+ const url = new URL(value);
1825
+ if (url.protocol !== "https:" && url.protocol !== "http:")
1826
+ return null;
1827
+ return url.href;
1828
+ } catch {
1829
+ return null;
1830
+ }
1831
+ };
1832
+ const hexColor = (value) => {
1833
+ if (typeof value !== "string")
1834
+ return null;
1835
+ const raw = value.trim();
1836
+ return /^#[0-9a-fA-F]{3,8}$/.test(raw) ? raw : null;
1837
+ };
1838
+ const hostname = (value) => {
1839
+ try {
1840
+ return new URL(value).hostname.replace(/^www\./, "");
1841
+ } catch {
1842
+ return value;
1843
+ }
1844
+ };
1845
+ host.replaceChildren();
1846
+ host.hidden = true;
1847
+ if (!isRecord2(catalog) || !Object.hasOwn(catalog, service))
1848
+ return;
1849
+ const row = catalog[service];
1850
+ if (!isRecord2(row))
1851
+ return;
1852
+ const vendor = clip(row.vendor, 80);
1853
+ const website = httpUrl(row.website);
1854
+ const guide = httpUrl(row.guide);
1855
+ const docs = httpUrl(row.docs);
1856
+ const logo = httpUrl(row.logo);
1857
+ const color = hexColor(row.color);
1858
+ const description = clip(row.description, 280);
1859
+ if (vendor === null || website === null && guide === null && docs === null)
1860
+ return;
1861
+ const add = (node) => {
1862
+ host.append(node);
1863
+ return node;
1864
+ };
1865
+ if (logo !== null) {
1866
+ const img = doc.createElement("img");
1867
+ img.alt = "";
1868
+ img.src = logo;
1869
+ img.width = 16;
1870
+ img.height = 16;
1871
+ img.decoding = "async";
1872
+ img.referrerPolicy = "no-referrer";
1873
+ if (color !== null)
1874
+ img.style.borderColor = color;
1875
+ add(img);
1876
+ }
1877
+ const name = doc.createElement("span");
1878
+ name.className = "vendor-name";
1879
+ name.textContent = vendor;
1880
+ if (description !== null)
1881
+ name.title = description;
1882
+ add(name);
1883
+ const sep = () => {
1884
+ const node = doc.createElement("span");
1885
+ node.className = "vendor-sep";
1886
+ node.setAttribute("aria-hidden", "true");
1887
+ node.textContent = "\xB7";
1888
+ return node;
1889
+ };
1890
+ const link = (href, label, title) => {
1891
+ const node = doc.createElement("a");
1892
+ node.className = "vendor-link";
1893
+ node.href = href;
1894
+ node.target = "_blank";
1895
+ node.rel = "noopener noreferrer";
1896
+ node.referrerPolicy = "no-referrer";
1897
+ node.textContent = label;
1898
+ node.title = title;
1899
+ return node;
1900
+ };
1901
+ if (website !== null) {
1902
+ add(sep());
1903
+ add(link(website, hostname(website), `${vendor} website`));
1904
+ }
1905
+ if (guide !== null) {
1906
+ add(sep());
1907
+ add(link(guide, "Docs", `Docs for ${vendor}`));
1908
+ }
1909
+ if (docs !== null) {
1910
+ add(sep());
1911
+ add(link(docs, "API", `${vendor} API reference`));
1912
+ }
1913
+ host.removeAttribute("hidden");
1914
+ host.hidden = false;
1915
+ }
1916
+ function startAdminBrand(env) {
1917
+ const requested = env.params.get("brands");
1918
+ let brandsUrl = env.brandsUrl;
1919
+ if (requested) {
1920
+ try {
1921
+ const url = new URL(requested, env.location.href);
1922
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "::1" || url.hostname === "[::1]" || url.origin === env.location.origin;
1923
+ if ((url.protocol === "https:" || url.protocol === "http:") && local)
1924
+ brandsUrl = url.href;
1925
+ } catch {
1926
+ brandsUrl = env.brandsUrl;
1927
+ }
1928
+ }
1929
+ const vendorHost = env.$("vendor");
1930
+ const brandRoot = env.document.querySelector("[data-mockingbird-admin]");
1931
+ const brandService = brandRoot?.getAttribute("data-service") || "";
1932
+ if (vendorHost === null)
1933
+ return;
1934
+ env.fetch(brandsUrl, {
1935
+ headers: { accept: "application/json" },
1936
+ signal: AbortSignal.timeout(5e3)
1937
+ }).then(async (response) => {
1938
+ if (!response.ok)
1939
+ return null;
1940
+ const catalog = await response.json();
1941
+ return catalog;
1942
+ }).then((catalog) => {
1943
+ mountAdminBrand(env.document, vendorHost, brandService, catalog);
1944
+ }).catch(() => {
1945
+ });
1946
+ }
1947
+ function faultPresetList(value) {
1948
+ if (!isRecord2(value))
1949
+ throw new Error("Fault presets response was not an object");
1950
+ if (!Object.hasOwn(value, "presets") || value.presets === void 0 || value.presets === null) {
1951
+ return { presets: [] };
1952
+ }
1953
+ if (!Array.isArray(value.presets))
1954
+ throw new Error("Fault presets response was not a list");
1955
+ return {
1956
+ presets: value.presets.flatMap((item) => {
1957
+ if (!isRecord2(item) || typeof item.name !== "string")
1958
+ return [];
1959
+ return [{ name: item.name }];
1960
+ })
1961
+ };
1962
+ }
1963
+ function bootAdmin(config) {
1964
+ const fieldKinds = ["string", "number", "boolean", "null", "object", "array", "unknown"];
1965
+ const sources = ["declared", "inferred", "mixed"];
1966
+ const isFieldKind = (value) => typeof value === "string" && fieldKinds.some((kind) => kind === value);
1967
+ const isSource = (value) => typeof value === "string" && sources.some((source) => source === value);
1968
+ const readJson2 = (text) => {
1969
+ const value = JSON.parse(text);
1970
+ return value;
1971
+ };
1972
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => {
1973
+ switch (char) {
1974
+ case "&":
1975
+ return "&amp;";
1976
+ case "<":
1977
+ return "&lt;";
1978
+ case ">":
1979
+ return "&gt;";
1980
+ case '"':
1981
+ return "&quot;";
1982
+ default:
1983
+ return "&#39;";
1984
+ }
1985
+ });
1986
+ const el = (id, kind) => {
1987
+ const node = document.getElementById(id);
1988
+ if (!(node instanceof kind))
1989
+ throw new Error(`admin shell is missing #${id}`);
1990
+ return node;
1991
+ };
1992
+ const errorMessage = (data, fallback) => {
1993
+ if (!isRecord2(data))
1994
+ return fallback;
1995
+ const error = data.error;
1996
+ if (!isRecord2(error) || typeof error.message !== "string" || error.message === "") {
1997
+ return fallback;
1998
+ }
1999
+ return error.message;
2000
+ };
2001
+ const requireList = (value, label) => {
2002
+ if (value === void 0 || value === null)
2003
+ return [];
2004
+ if (!Array.isArray(value))
2005
+ throw new Error(`${label} was not a list`);
2006
+ return value;
2007
+ };
2008
+ const state = {
2009
+ namespace: "default",
2010
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
2011
+ view: "overview",
2012
+ collection: "",
2013
+ shape: null,
2014
+ route: null,
2015
+ editing: null
2016
+ };
2017
+ const standard = new Set(config.standardRoutes);
2018
+ const banner = el("banner", HTMLElement);
2019
+ const keyInput = el("admin-key", HTMLInputElement);
2020
+ keyInput.value = state.key;
2021
+ const params = new URLSearchParams(location.search);
2022
+ const queryKey = params.get("key");
2023
+ if (queryKey) {
2024
+ state.key = queryKey;
2025
+ keyInput.value = state.key;
2026
+ sessionStorage.setItem("mockingbird-admin-key", state.key);
2027
+ params.delete("key");
2028
+ const next = params.toString();
2029
+ history.replaceState(null, "", location.pathname + (next ? `?${next}` : ""));
2030
+ }
2031
+ const queryNamespace = params.get("namespace");
2032
+ if (queryNamespace)
2033
+ state.namespace = queryNamespace;
2034
+ const showError = (error) => {
2035
+ banner.textContent = error instanceof Error ? error.message : String(error);
2036
+ banner.classList.add("show");
2037
+ };
2038
+ const clearError = () => {
2039
+ banner.classList.remove("show");
2040
+ };
2041
+ const api = async (method, path, body) => {
2042
+ const headers = { accept: "application/json" };
2043
+ if (state.key !== "")
2044
+ headers[config.adminKeyHeader] = state.key;
2045
+ if (state.namespace !== "")
2046
+ headers["x-mockingbird-namespace"] = state.namespace;
2047
+ if (body !== void 0)
2048
+ headers["content-type"] = "application/json";
2049
+ const init = { method, headers };
2050
+ if (body !== void 0)
2051
+ init.body = JSON.stringify(body);
2052
+ const response = await fetch(config.adminPrefix + path, init);
2053
+ const text = await response.text();
2054
+ let data = null;
2055
+ if (text !== "") {
2056
+ try {
2057
+ data = readJson2(text);
2058
+ } catch {
2059
+ data = { raw: text };
2060
+ }
2061
+ }
2062
+ if (response.status === 401) {
2063
+ keyInput.focus();
2064
+ throw new Error(errorMessage(data, "Admin key required"));
2065
+ }
2066
+ if (!response.ok) {
2067
+ throw new Error(errorMessage(data, `${response.status} ${method} ${path}`));
2068
+ }
2069
+ return data;
2070
+ };
2071
+ const originGet = async (path) => {
2072
+ const response = await fetch(path, { headers: { accept: "application/json" } });
2073
+ if (!response.ok)
2074
+ throw new Error(`${response.status} ${path}`);
2075
+ const value = await response.json();
2076
+ return value;
2077
+ };
2078
+ const panelApi = {
2079
+ get: (path) => api("GET", path),
2080
+ send: (method, path, body) => api(method, path, body),
2081
+ namespace: () => state.namespace
2082
+ };
2083
+ const isPanelScript = (value) => typeof value === "function";
2084
+ const setTheme = (theme) => {
2085
+ if (theme)
2086
+ document.documentElement.dataset.theme = theme;
2087
+ else
2088
+ delete document.documentElement.dataset.theme;
2089
+ };
2090
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme");
2091
+ if (storedTheme)
2092
+ setTheme(storedTheme);
2093
+ el("theme", HTMLButtonElement).addEventListener("click", () => {
2094
+ const current = document.documentElement.dataset.theme;
2095
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches;
2096
+ const next = dark ? "light" : "dark";
2097
+ localStorage.setItem("mockingbird-admin-theme", next);
2098
+ setTheme(next);
2099
+ });
2100
+ const show = (view) => {
2101
+ state.view = view;
2102
+ for (const button of document.querySelectorAll("#nav button")) {
2103
+ if (!(button instanceof HTMLButtonElement))
2104
+ continue;
2105
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false");
2106
+ }
2107
+ for (const section of document.querySelectorAll("main .view")) {
2108
+ if (!(section instanceof HTMLElement))
2109
+ continue;
2110
+ section.hidden = section.id !== `view-${view}`;
2111
+ }
2112
+ };
2113
+ el("nav", HTMLElement).addEventListener("click", (event) => {
2114
+ const target = event.target;
2115
+ if (!(target instanceof Element))
2116
+ return;
2117
+ const button = target.closest("button[data-view]");
2118
+ if (!(button instanceof HTMLButtonElement))
2119
+ return;
2120
+ const view = button.dataset.view;
2121
+ if (view === void 0)
2122
+ return;
2123
+ show(view);
2124
+ refresh().catch(showError);
2125
+ });
2126
+ 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>`;
2127
+ const table = (columns, rows) => {
2128
+ if (rows.length === 0)
2129
+ return '<p class="empty">Nothing here yet.</p>';
2130
+ const head = `<tr>${columns.map((column) => `<th>${column.label}</th>`).join("")}</tr>`;
2131
+ const body = rows.map((row) => {
2132
+ const cells = columns.map((column) => `<td data-label="${column.label}">${column.cell(row)}</td>`).join("");
2133
+ const attrs = "attrs" in row && typeof row.attrs === "string" ? row.attrs : "";
2134
+ return `<tr${attrs}>${cells}</tr>`;
2135
+ }).join("");
2136
+ return `<table><thead>${head}</thead><tbody>${body}</tbody></table>`;
2137
+ };
2138
+ const preview = (value) => {
2139
+ const text = JSON.stringify(value) ?? "null";
2140
+ return esc(text.length > 180 ? `${text.slice(0, 180)}\u2026` : text);
2141
+ };
2142
+ const when = (epoch) => {
2143
+ const date = new Date(epoch);
2144
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString();
2145
+ };
2146
+ const clockCard = (epoch) => {
2147
+ const date = new Date(epoch);
2148
+ if (Number.isNaN(date.getTime()))
2149
+ return esc(String(epoch));
2150
+ const iso = date.toISOString();
2151
+ return `${esc(iso.slice(0, 10))}<span class="clock-time">${esc(iso.slice(11, 19))} UTC</span>`;
2152
+ };
2153
+ const decodeClock = (value) => {
2154
+ if (!isRecord2(value) || typeof value.now !== "number" || typeof value.offsetMs !== "number" || typeof value.frozen !== "boolean") {
2155
+ throw new Error("Clock response was not a clock");
2156
+ }
2157
+ return { now: value.now, offsetMs: value.offsetMs, frozen: value.frozen };
2158
+ };
2159
+ const decodeField = (value) => {
2160
+ if (!isRecord2(value) || typeof value.name !== "string" || !isFieldKind(value.kind)) {
2161
+ return void 0;
2162
+ }
2163
+ const field = {
2164
+ name: value.name,
2165
+ kind: value.kind,
2166
+ optional: value.optional === true
2167
+ };
2168
+ if (typeof value.description === "string")
2169
+ field.description = value.description;
2170
+ if (Array.isArray(value.fields)) {
2171
+ field.fields = value.fields.flatMap((item) => {
2172
+ const child = decodeField(item);
2173
+ return child === void 0 ? [] : [child];
2174
+ });
2175
+ }
2176
+ return field;
2177
+ };
2178
+ const decodeCollection = (value) => {
2179
+ if (!isRecord2(value) || typeof value.name !== "string")
2180
+ return void 0;
2181
+ const fields = Array.isArray(value.fields) ? value.fields.flatMap((item) => {
2182
+ const field = decodeField(item);
2183
+ return field === void 0 ? [] : [field];
2184
+ }) : [];
2185
+ const collection = {
2186
+ name: value.name,
2187
+ label: typeof value.label === "string" ? value.label : value.name,
2188
+ count: typeof value.count === "number" ? value.count : 0,
2189
+ source: isSource(value.source) ? value.source : "inferred",
2190
+ fields
2191
+ };
2192
+ if (typeof value.description === "string")
2193
+ collection.description = value.description;
2194
+ return collection;
2195
+ };
2196
+ const decodeState = (value) => {
2197
+ if (!isRecord2(value) || !Array.isArray(value.collections)) {
2198
+ throw new Error("State response has no collection list");
2199
+ }
2200
+ return {
2201
+ namespace: typeof value.namespace === "string" ? value.namespace : state.namespace,
2202
+ storageNamespace: typeof value.storageNamespace === "string" ? value.storageNamespace : "",
2203
+ collections: value.collections.flatMap((item) => {
2204
+ const collection = decodeCollection(item);
2205
+ return collection === void 0 ? [] : [collection];
2206
+ })
2207
+ };
2208
+ };
2209
+ const decodeRecords = (value) => requireList(isRecord2(value) ? value.records : void 0, "Records").flatMap((item) => {
2210
+ if (!isRecord2(item) || typeof item.id !== "string")
2211
+ return [];
2212
+ return [
2213
+ {
2214
+ id: item.id,
2215
+ seq: typeof item.seq === "number" ? item.seq : 0,
2216
+ value: item.value,
2217
+ attrs: ` class="clickable" data-id="${esc(item.id)}"`
2218
+ }
2219
+ ];
2220
+ });
2221
+ const textOf = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : "";
2222
+ const decodeJournal = (value) => requireList(isRecord2(value) ? value.requests : void 0, "Journal").flatMap((item) => {
2223
+ if (!isRecord2(item))
2224
+ return [];
2225
+ return [
2226
+ {
2227
+ at: textOf(item.at),
2228
+ method: textOf(item.method),
2229
+ path: textOf(item.path),
2230
+ status: textOf(item.status),
2231
+ durationMs: textOf(item.durationMs),
2232
+ operationId: textOf(item.operationId)
2233
+ }
2234
+ ];
2235
+ });
2236
+ const decodeFaults = (value) => requireList(isRecord2(value) ? value.faults : void 0, "Faults").flatMap((item) => {
2237
+ if (!isRecord2(item))
2238
+ return [];
2239
+ return [
2240
+ {
2241
+ id: textOf(item.id),
2242
+ method: typeof item.method === "string" ? item.method : void 0,
2243
+ pathPrefix: typeof item.pathPrefix === "string" ? item.pathPrefix : void 0,
2244
+ operationId: typeof item.operationId === "string" ? item.operationId : void 0,
2245
+ status: typeof item.status === "number" ? item.status : void 0,
2246
+ effect: typeof item.effect === "string" ? item.effect : void 0,
2247
+ drop: typeof item.drop === "boolean" ? item.drop : void 0,
2248
+ latencyMs: typeof item.latencyMs === "number" ? item.latencyMs : void 0
2249
+ }
2250
+ ];
2251
+ });
2252
+ const loadNamespaces = async () => {
2253
+ const data = await api("GET", "/namespaces");
2254
+ const select = el("namespace", HTMLSelectElement);
2255
+ const listed = requireList(isRecord2(data) ? data.namespaces : void 0, "Namespaces");
2256
+ const fallback = isRecord2(data) && typeof data.default === "string" && data.default !== "" ? data.default : "default";
2257
+ const names = (listed.length > 0 ? listed.map((name) => String(name)) : [fallback]).slice();
2258
+ if (!names.includes(state.namespace))
2259
+ names.unshift(state.namespace);
2260
+ select.innerHTML = names.map((name) => `<option value="${esc(name)}">${esc(name)}</option>`).join("");
2261
+ select.value = state.namespace;
2262
+ };
2263
+ const renderOverview = async () => {
2264
+ const [health, shape, clock, journal] = await Promise.all([
2265
+ originGet("/health"),
2266
+ api("GET", "/state"),
2267
+ api("GET", "/clock"),
2268
+ api("GET", "/requests?limit=8")
2269
+ ]);
2270
+ if (!isRecord2(health))
2271
+ throw new Error("Health response was not an object");
2272
+ const decoded = decodeState(shape);
2273
+ state.shape = decoded;
2274
+ const time = decodeClock(clock);
2275
+ el("overview-cards", HTMLElement).innerHTML = cards([
2276
+ {
2277
+ k: "Service",
2278
+ v: esc(typeof health.service === "string" && health.service !== "" ? health.service : config.service)
2279
+ },
2280
+ {
2281
+ k: "Status",
2282
+ v: esc(typeof health.status === "string" && health.status !== "" ? health.status : "ok")
2283
+ },
2284
+ { k: "Namespace", v: esc(state.namespace) },
2285
+ { k: "Collections", v: String(decoded.collections.length) },
2286
+ {
2287
+ k: "Records",
2288
+ v: String(decoded.collections.reduce((sum, item) => sum + item.count, 0))
2289
+ },
2290
+ { k: "Clock", v: clockCard(time.now) }
2291
+ ]);
2292
+ el("overview-requests", HTMLElement).innerHTML = table([
2293
+ { label: "Method", cell: (row) => esc(row.method) },
2294
+ { label: "Path", cell: (row) => esc(row.path) },
2295
+ {
2296
+ label: "Status",
2297
+ cell: (row) => `<span class="status-${row.status.charAt(0)}">${esc(row.status)}</span>`
2298
+ },
2299
+ { label: "Operation", cell: (row) => esc(row.operationId) }
2300
+ ], decodeJournal(journal));
2301
+ };
2302
+ const schemaChips = (collection) => {
2303
+ if (collection.fields.length === 0) {
2304
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>';
2305
+ }
2306
+ return `<div class="chips">${collection.fields.map((field) => `<span class="chip">${esc(field.name)} <i>${esc(field.kind)}${field.optional ? "?" : ""}</i></span>`).join("")}</div>`;
2307
+ };
2308
+ const renderState = async () => {
2309
+ const shape = decodeState(await api("GET", "/state"));
2310
+ state.shape = shape;
2311
+ const host = el("collections", HTMLElement);
2312
+ if (shape.collections.length === 0) {
2313
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>';
2314
+ el("schema", HTMLElement).innerHTML = "";
2315
+ el("records", HTMLElement).innerHTML = "";
2316
+ return;
2317
+ }
2318
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2319
+ const first = shape.collections[0];
2320
+ if (first === void 0)
2321
+ return;
2322
+ state.collection = first.name;
2323
+ }
2324
+ 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("");
2325
+ const selected = shape.collections.find((item) => item.name === state.collection);
2326
+ if (selected === void 0)
2327
+ return;
2328
+ const description = selected.description ? `<p class="lede">${esc(selected.description)}</p>` : "";
2329
+ el("schema", HTMLElement).innerHTML = `<h3>${esc(selected.label)}</h3>${description}${schemaChips(selected)}`;
2330
+ const page = await api("GET", `/state/${encodeURIComponent(state.collection)}?limit=50`);
2331
+ el("records", HTMLElement).innerHTML = table([
2332
+ { label: "Id", cell: (row) => `<code>${esc(row.id)}</code>` },
2333
+ { label: "Seq", cell: (row) => esc(row.seq) },
2334
+ { label: "Value", cell: (row) => preview(row.value) }
2335
+ ], decodeRecords(page));
2336
+ };
2337
+ const renderClock = async () => {
2338
+ const clock = decodeClock(await api("GET", "/clock"));
2339
+ 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>`;
2340
+ const freeze = el("freeze", HTMLButtonElement);
2341
+ freeze.textContent = clock.frozen ? "Unfreeze" : "Freeze";
2342
+ freeze.dataset.frozen = clock.frozen ? "1" : "0";
2343
+ };
2344
+ const renderFaults = async () => {
2345
+ const [faults, presets] = await Promise.all([
2346
+ api("GET", "/faults"),
2347
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2348
+ ]);
2349
+ const select = el("fault-preset", HTMLSelectElement);
2350
+ const current = select.value;
2351
+ const list = faultPresetList(presets).presets;
2352
+ select.innerHTML = `<option value="">Custom rule</option>${list.map((preset) => `<option value="${esc(preset.name)}">${esc(preset.name)}</option>`).join("")}`;
2353
+ select.value = current;
2354
+ el("fault-list", HTMLElement).innerHTML = table([
2355
+ { label: "Id", cell: (row) => esc(row.id) },
2356
+ {
2357
+ label: "Match",
2358
+ cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter((part) => Boolean(part)).join(" ") || "all")
2359
+ },
2360
+ {
2361
+ label: "Effect",
2362
+ cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || ""))
2363
+ }
2364
+ ], decodeFaults(faults));
2365
+ };
2366
+ const renderJournal = async () => {
2367
+ const journal = await api("GET", "/requests?limit=100");
2368
+ el("journal", HTMLElement).innerHTML = table([
2369
+ { label: "When", cell: (row) => esc(row.at) },
2370
+ { label: "Method", cell: (row) => esc(row.method) },
2371
+ { label: "Path", cell: (row) => esc(row.path) },
2372
+ { label: "Status", cell: (row) => esc(row.status) },
2373
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2374
+ ], decodeJournal(journal));
2375
+ };
2376
+ const renderRoutes = async () => {
2377
+ const data = await api("GET", "/");
2378
+ if (!isRecord2(data))
2379
+ throw new Error("Route list was not an object");
2380
+ const routes = requireList(data.routes, "Routes").map((route) => String(route));
2381
+ el("route-list", HTMLElement).innerHTML = routes.map((route) => {
2382
+ const extra = standard.has(route) ? "" : " <span class='badge'>extension</span>";
2383
+ const parts = route.split(" ");
2384
+ const method = parts[0] ?? "";
2385
+ const path = parts.slice(1).join(" ");
2386
+ 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>`;
2387
+ }).join("");
2388
+ };
2389
+ const renderers = {
2390
+ overview: renderOverview,
2391
+ state: renderState,
2392
+ clock: renderClock,
2393
+ faults: renderFaults,
2394
+ journal: renderJournal,
2395
+ routes: renderRoutes
2396
+ };
2397
+ async function refresh() {
2398
+ clearError();
2399
+ const render = renderers[state.view];
2400
+ if (render)
2401
+ await render();
2402
+ }
2403
+ el("namespace", HTMLSelectElement).addEventListener("change", () => {
2404
+ state.namespace = el("namespace", HTMLSelectElement).value;
2405
+ refresh().catch(showError);
2406
+ });
2407
+ keyInput.addEventListener("change", () => {
2408
+ state.key = keyInput.value.trim();
2409
+ sessionStorage.setItem("mockingbird-admin-key", state.key);
2410
+ refresh().catch(showError);
2411
+ });
2412
+ el("refresh", HTMLButtonElement).addEventListener("click", () => {
2413
+ refresh().catch(showError);
2414
+ });
2415
+ el("collections", HTMLElement).addEventListener("click", (event) => {
2416
+ const target = event.target;
2417
+ if (!(target instanceof Element))
2418
+ return;
2419
+ const button = target.closest("[data-collection]");
2420
+ if (!(button instanceof HTMLElement))
2421
+ return;
2422
+ const collection = button.dataset.collection;
2423
+ if (collection === void 0)
2424
+ return;
2425
+ state.collection = collection;
2426
+ renderState().catch(showError);
2427
+ });
2428
+ el("records", HTMLElement).addEventListener("click", (event) => {
2429
+ const target = event.target;
2430
+ if (!(target instanceof Element))
2431
+ return;
2432
+ const row = target.closest("[data-id]");
2433
+ if (!(row instanceof HTMLElement))
2434
+ return;
2435
+ const id = row.dataset.id;
2436
+ if (id === void 0)
2437
+ return;
2438
+ openEditor(id).catch(showError);
2439
+ });
2440
+ const editor = el("editor", HTMLDialogElement);
2441
+ const editorId = el("editor-id", HTMLInputElement);
2442
+ const editorValue = el("editor-value", HTMLTextAreaElement);
2443
+ const editorDelete = el("editor-delete", HTMLButtonElement);
2444
+ async function openEditor(id) {
2445
+ state.editing = id;
2446
+ el("editor-title", HTMLElement).textContent = id ? "Edit record" : "New record";
2447
+ editorId.value = id ?? "";
2448
+ editorId.readOnly = id !== null;
2449
+ editorDelete.hidden = id === null;
2450
+ if (id) {
2451
+ const record = await api("GET", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`);
2452
+ if (!isRecord2(record))
2453
+ throw new Error("Record response was not an object");
2454
+ editorValue.value = JSON.stringify(record.value, null, 2) ?? "";
2455
+ } else {
2456
+ editorValue.value = "{\n \n}";
2457
+ }
2458
+ editor.showModal();
2459
+ }
2460
+ el("new-record", HTMLButtonElement).addEventListener("click", () => {
2461
+ openEditor(null).catch(showError);
2462
+ });
2463
+ el("editor-form", HTMLFormElement).addEventListener("submit", (event) => {
2464
+ const submitter = event.submitter;
2465
+ if (!(submitter instanceof HTMLButtonElement) || submitter.value !== "save")
2466
+ return;
2467
+ event.preventDefault();
2468
+ let value;
2469
+ try {
2470
+ value = readJson2(editorValue.value);
2471
+ } catch {
2472
+ showError(new Error("Value is not JSON"));
2473
+ return;
2474
+ }
2475
+ const id = editorId.value.trim();
2476
+ const path = `/state/${encodeURIComponent(state.collection)}`;
2477
+ const request = state.editing ? api("PUT", `${path}/${encodeURIComponent(id)}`, { value }) : api("POST", path, { id: id || void 0, value });
2478
+ request.then(() => {
2479
+ editor.close();
2480
+ return renderState();
2481
+ }).catch(showError);
2482
+ });
2483
+ editorDelete.addEventListener("click", () => {
2484
+ const id = state.editing;
2485
+ if (!id)
2486
+ return;
2487
+ api("DELETE", `/state/${encodeURIComponent(state.collection)}/${encodeURIComponent(id)}`).then(() => {
2488
+ editor.close();
2489
+ return renderState();
2490
+ }).catch(showError);
2491
+ });
2492
+ for (const button of document.querySelectorAll("[data-advance]")) {
2493
+ if (!(button instanceof HTMLButtonElement))
2494
+ continue;
2495
+ button.addEventListener("click", () => {
2496
+ const raw = button.dataset.advance;
2497
+ if (raw === void 0)
2498
+ return;
2499
+ api("POST", "/clock", { advance: Number(raw) }).then(() => renderClock()).catch(showError);
2500
+ });
2501
+ }
2502
+ el("freeze", HTMLButtonElement).addEventListener("click", () => {
2503
+ const frozen = el("freeze", HTMLButtonElement).dataset.frozen === "1";
2504
+ api("POST", "/clock", { freeze: !frozen }).then(() => renderClock()).catch(showError);
2505
+ });
2506
+ el("clock-reset", HTMLButtonElement).addEventListener("click", () => {
2507
+ api("POST", "/clock", { reset: true }).then(() => renderClock()).catch(showError);
2508
+ });
2509
+ el("clock-set", HTMLFormElement).addEventListener("submit", (event) => {
2510
+ event.preventDefault();
2511
+ const raw = el("clock-instant", HTMLInputElement).value.trim();
2512
+ const set = /^-?\d+$/.test(raw) ? Number(raw) : raw;
2513
+ api("POST", "/clock", { set }).then(() => renderClock()).catch(showError);
2514
+ });
2515
+ el("fault-form", HTMLFormElement).addEventListener("submit", (event) => {
2516
+ event.preventDefault();
2517
+ const preset = el("fault-preset", HTMLSelectElement).value;
2518
+ if (preset !== "") {
2519
+ api("POST", "/faults", { preset }).then(() => renderFaults()).catch(showError);
2520
+ return;
2521
+ }
2522
+ const status = Number(el("fault-status", HTMLInputElement).value);
2523
+ if (!Number.isFinite(status)) {
2524
+ showError(new Error("Status must be a number, or choose a preset"));
2525
+ return;
2526
+ }
2527
+ const path = el("fault-path", HTMLInputElement).value;
2528
+ const method = el("fault-method", HTMLInputElement).value;
2529
+ api("POST", "/faults", {
2530
+ status,
2531
+ ...path !== "" ? { pathPrefix: path } : {},
2532
+ ...method !== "" ? { method } : {}
2533
+ }).then(() => renderFaults()).catch(showError);
2534
+ });
2535
+ el("fault-clear", HTMLButtonElement).addEventListener("click", () => {
2536
+ api("DELETE", "/faults").then(() => renderFaults()).catch(showError);
2537
+ });
2538
+ el("journal-clear", HTMLButtonElement).addEventListener("click", () => {
2539
+ api("DELETE", "/requests").then(() => renderJournal()).catch(showError);
2540
+ });
2541
+ el("route-list", HTMLElement).addEventListener("click", (event) => {
2542
+ const target = event.target;
2543
+ if (!(target instanceof Element))
2544
+ return;
2545
+ const button = target.closest("[data-route]");
2546
+ if (!(button instanceof HTMLElement))
2547
+ return;
2548
+ const route = button.dataset.route;
2549
+ if (route === void 0)
2550
+ return;
2551
+ state.route = route;
2552
+ el("route-title", HTMLElement).textContent = route;
2553
+ const method = route.split(" ")[0] ?? "";
2554
+ el("route-body", HTMLTextAreaElement).disabled = method === "GET" || method === "DELETE";
2555
+ });
2556
+ el("route-form", HTMLFormElement).addEventListener("submit", (event) => {
2557
+ event.preventDefault();
2558
+ const send = async () => {
2559
+ if (state.route === null)
2560
+ throw new Error("Choose a route first");
2561
+ const parts = state.route.split(" ");
2562
+ const method = parts[0];
2563
+ const path = parts.slice(1).join(" ");
2564
+ if (method === void 0)
2565
+ throw new Error("Choose a route first");
2566
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_match, key) => prompt(`Value for ${key}`) || "");
2567
+ let body;
2568
+ const routeBody = el("route-body", HTMLTextAreaElement);
2569
+ if (method !== "GET" && method !== "DELETE" && routeBody.value.trim() !== "") {
2570
+ try {
2571
+ body = readJson2(routeBody.value);
2572
+ } catch {
2573
+ throw new Error("Body is not JSON");
2574
+ }
2575
+ }
2576
+ const data = await api(method, concrete, body);
2577
+ el("route-result", HTMLElement).textContent = JSON.stringify(data, null, 2);
2578
+ };
2579
+ send().catch(showError);
2580
+ });
2581
+ const decodePanel = (value) => {
2582
+ if (!isRecord2(value) || typeof value.id !== "string" || typeof value.title !== "string") {
2583
+ return void 0;
2584
+ }
2585
+ const panel = {
2586
+ id: value.id,
2587
+ title: value.title,
2588
+ description: typeof value.description === "string" ? value.description : "",
2589
+ html: typeof value.html === "string" ? value.html : ""
2590
+ };
2591
+ if (typeof value.script === "string")
2592
+ panel.script = value.script;
2593
+ return panel;
2594
+ };
2595
+ const mountPanels = (panels) => {
2596
+ const nav = el("nav", HTMLElement);
2597
+ const views = el("views", HTMLElement);
2598
+ for (const panel of panels) {
2599
+ const button = document.createElement("button");
2600
+ button.type = "button";
2601
+ button.dataset.view = panel.id;
2602
+ button.textContent = panel.title;
2603
+ nav.append(button);
2604
+ const section = document.createElement("section");
2605
+ section.className = "view";
2606
+ section.id = `view-${panel.id}`;
2607
+ section.hidden = true;
2608
+ const title = document.createElement("h2");
2609
+ title.textContent = panel.title;
2610
+ const lede = document.createElement("p");
2611
+ lede.className = "lede";
2612
+ lede.textContent = panel.description;
2613
+ const body = document.createElement("div");
2614
+ body.className = "panel-body";
2615
+ body.id = `panel-${panel.id}`;
2616
+ body.innerHTML = panel.html;
2617
+ section.append(title, lede, body);
2618
+ views.append(section);
2619
+ if (panel.script === void 0)
2620
+ continue;
2621
+ try {
2622
+ const compiled = new Function("root", "api", panel.script);
2623
+ if (!isPanelScript(compiled))
2624
+ throw new Error("panel script did not compile");
2625
+ compiled(body, panelApi);
2626
+ } catch (error) {
2627
+ const note = document.createElement("p");
2628
+ note.className = "banner show";
2629
+ note.textContent = error instanceof Error ? error.message : String(error);
2630
+ body.append(note);
2631
+ }
2632
+ }
2633
+ };
2634
+ startAdminBrand({
2635
+ document,
2636
+ $: (id) => document.getElementById(id),
2637
+ params,
2638
+ location: { href: location.href, origin: location.origin },
2639
+ fetch,
2640
+ brandsUrl: config.brandsUrl
2641
+ });
2642
+ loadNamespaces().then(() => api("GET", "/ui/manifest")).then((manifest) => {
2643
+ const panels = requireList(isRecord2(manifest) ? manifest.panels : void 0, "Panels").flatMap((panel) => {
2644
+ const decoded = decodePanel(panel);
2645
+ return decoded === void 0 ? [] : [decoded];
2646
+ });
2647
+ mountPanels(panels);
2648
+ return refresh();
2649
+ }).catch(showError);
2650
+ }
2651
+ var clientPrelude = [isRecord2, mountAdminBrand, startAdminBrand, faultPresetList, bootAdmin].map((fn) => fn.toString()).join("\n");
2652
+ var adminClientSource = (config) => {
2653
+ const payload = JSON.stringify(config).replace(/</g, "\\u003c");
2654
+ return `<script>
2655
+ ${clientPrelude}
2656
+ bootAdmin(${payload});
2657
+ </script>`;
2658
+ };
2659
+
2660
+ // ../core/dist/surface.js
2661
+ var defineMock = (runtime) => runtime;
2662
+ var STANDARD_ADMIN_ROUTES = [
2663
+ "GET /",
2664
+ "POST /reset",
2665
+ "GET /namespaces",
2666
+ "GET /clock",
2667
+ "POST /clock",
2668
+ "GET /faults",
2669
+ "POST /faults",
2670
+ "DELETE /faults",
2671
+ "POST /snapshots",
2672
+ "POST /snapshots/:id/restore",
2673
+ "DELETE /snapshots/:id",
2674
+ "GET /timeline",
2675
+ "POST /checkpoints",
2676
+ "POST /branches/:name",
2677
+ "POST /branches/:name/checkout",
2678
+ "GET /requests",
2679
+ "DELETE /requests",
2680
+ "GET /metrics",
2681
+ "DELETE /metrics",
2682
+ "GET /credentials",
2683
+ "PUT /credentials",
2684
+ "DELETE /credentials",
2685
+ "GET /state",
2686
+ "GET /state/:collection",
2687
+ "GET /state/:collection/:id",
2688
+ "POST /state/:collection",
2689
+ "PUT /state/:collection/:id",
2690
+ "PATCH /state/:collection/:id",
2691
+ "DELETE /state/:collection/:id",
2692
+ "GET /ui",
2693
+ "GET /ui/",
2694
+ "GET /ui/manifest"
2695
+ ];
2696
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
2697
+ var assertAdminUi = (ui) => {
2698
+ if (!ui?.panels)
2699
+ return;
2700
+ const seen = /* @__PURE__ */ new Set();
2701
+ for (const panel of ui.panels) {
2702
+ if (!PANEL_ID.test(panel.id)) {
2703
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
2704
+ }
2705
+ if (seen.has(panel.id))
2706
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
2707
+ seen.add(panel.id);
2708
+ if (panel.title.trim() === "")
2709
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
2710
+ }
2711
+ };
2712
+
2713
+ // ../core/dist/admin-ui.js
2714
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
2715
+ switch (char) {
2716
+ case "&":
2717
+ return "&amp;";
2718
+ case "<":
2719
+ return "&lt;";
2720
+ case ">":
2721
+ return "&gt;";
2722
+ case '"':
2723
+ return "&quot;";
2724
+ default:
2725
+ return "&#39;";
2726
+ }
2727
+ });
2728
+ var ADMIN_BRANDS_URL = "https://mockingbird.chrisvouga.dev/brands.json";
2729
+ var renderAdminDocument = (service) => {
2730
+ const name = escapeHtml(service);
2731
+ const script = adminClientSource({
2732
+ standardRoutes: STANDARD_ADMIN_ROUTES,
2733
+ adminPrefix: ADMIN_PREFIX,
2734
+ adminKeyHeader: ADMIN_KEY_HEADER,
2735
+ brandsUrl: ADMIN_BRANDS_URL,
2736
+ service
2737
+ });
2738
+ return `<!DOCTYPE html>
2739
+ <html lang="en">
2740
+ <head>
2741
+ <meta charset="utf-8">
2742
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2743
+ <meta name="color-scheme" content="light dark">
2744
+ <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">
2745
+ <title>${name} admin</title>
2746
+ <style>
2747
+ ${CSS_RESET}
2748
+ :root {
2749
+ color-scheme: light;
2750
+ --bg: #fafafa;
2751
+ --bg-elev: #ffffff;
2752
+ --bg-muted: #f4f4f5;
2753
+ --bg-inset: #f4f4f5;
2754
+ --line: #dedee3;
2755
+ --line-strong: #c4c4cc;
2756
+ --ink: #18181b;
2757
+ --muted: #62626b;
2758
+ --faint: #71717a;
2759
+ --accent: #27272a;
2760
+ --accent-ink: #ffffff;
2761
+ --accent-soft: #f4f4f5;
2762
+ --ok: #166534;
2763
+ --ok-soft: #f0fdf4;
2764
+ --warn: #a16207;
2765
+ --warn-soft: #fefce8;
2766
+ --err: #a82d32;
2767
+ --err-soft: #fef2f2;
2768
+ --shadow: none;
2769
+ --sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
2770
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
2771
+ --radius: 10px;
2772
+ --header: 56px;
2773
+ --nav: 200px;
2774
+ }
2775
+ :root[data-theme="dark"] {
2776
+ color-scheme: dark;
2777
+ --bg: #111113;
2778
+ --bg-elev: #19191c;
2779
+ --bg-muted: #242428;
2780
+ --bg-inset: #111113;
2781
+ --line: #36363c;
2782
+ --line-strong: #52525b;
2783
+ --ink: #f4f4f5;
2784
+ --muted: #a9a9b2;
2785
+ --faint: #71717a;
2786
+ --accent: #e4e4e7;
2787
+ --accent-ink: #18181b;
2788
+ --accent-soft: #242428;
2789
+ --ok: #86efac;
2790
+ --ok-soft: #14241b;
2791
+ --warn: #fde68a;
2792
+ --warn-soft: #2a2410;
2793
+ --err: #ffaaaa;
2794
+ --err-soft: #2c1516;
2795
+ --shadow: none;
2796
+ }
2797
+ @media (prefers-color-scheme: dark) {
2798
+ :root:not([data-theme="light"]) {
2799
+ color-scheme: dark;
2800
+ --bg: #111113;
2801
+ --bg-elev: #19191c;
2802
+ --bg-muted: #242428;
2803
+ --bg-inset: #111113;
2804
+ --line: #36363c;
2805
+ --line-strong: #52525b;
2806
+ --ink: #f4f4f5;
2807
+ --muted: #a9a9b2;
2808
+ --faint: #71717a;
2809
+ --accent: #e4e4e7;
2810
+ --accent-ink: #18181b;
2811
+ --accent-soft: #242428;
2812
+ --ok: #86efac;
2813
+ --ok-soft: #14241b;
2814
+ --warn: #fde68a;
2815
+ --warn-soft: #2a2410;
2816
+ --err: #ffaaaa;
2817
+ --err-soft: #2c1516;
2818
+ --shadow: none;
2819
+ }
2820
+ }
2821
+ /* Fill the viewport, then grow with the content so the background covers the scroll. */
2822
+ html { height: 100%; }
2823
+ body {
2824
+ margin: 0;
2825
+ min-height: 100%;
2826
+ display: flex;
2827
+ flex-direction: column;
2828
+ font-family: var(--sans);
2829
+ background: var(--bg);
2830
+ color: var(--ink);
2831
+ line-height: 1.45;
2832
+ padding-left: env(safe-area-inset-left);
2833
+ padding-right: env(safe-area-inset-right);
2834
+ -webkit-text-size-adjust: 100%;
2835
+ }
2836
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
2837
+ .app { flex: 1 0 auto; display: flex; flex-direction: column; min-width: 0; width: 100%; }
2838
+ header.top {
2839
+ position: sticky; top: 0; z-index: 5;
2840
+ display: flex; align-items: center; gap: 12px;
2841
+ min-height: var(--header); padding: 10px 16px;
2842
+ background: var(--bg-elev);
2843
+ border-bottom: 1px solid var(--line);
2844
+ min-width: 0; max-width: 100%;
2845
+ }
2846
+ .brand {
2847
+ display: flex; flex-flow: row wrap; align-items: center; gap: 14px;
2848
+ min-width: 0; max-width: 100%; margin-right: auto;
2849
+ }
2850
+ .brand-id { display: flex; flex-direction: column; min-width: 0; flex: none; }
2851
+ .brand-id strong { font-size: 15px; letter-spacing: -0.01em; }
2852
+ .brand-id span { color: var(--faint); font-size: 12px; }
2853
+ .vendor {
2854
+ display: flex; flex-wrap: wrap; align-items: center; gap: 6px;
2855
+ min-width: 0; max-width: 100%; font-size: 12px; color: var(--muted);
2856
+ }
2857
+ .vendor[hidden] { display: none; }
2858
+ /* Logos are drawn for a light tile, same as the docs site, so the plate stays white. */
2859
+ .vendor img {
2860
+ width: 16px; height: 16px; padding: 2px; box-sizing: content-box;
2861
+ border-radius: 4px; border: 1px solid var(--line); background: #fff; object-fit: contain;
2862
+ }
2863
+ .vendor-name { color: var(--ink); font-weight: 600; }
2864
+ .vendor-sep { color: var(--faint); }
2865
+ .vendor-link { color: inherit; text-decoration: none; }
2866
+ .vendor-link:hover { color: var(--ink); text-decoration: underline; }
2867
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
2868
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
2869
+ label.field input, label.field select, .controls input[type="password"] {
2870
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
2871
+ padding: 7px 8px; min-height: 36px;
2872
+ }
2873
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
2874
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
2875
+ background: var(--bg-elev);
2876
+ }
2877
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
2878
+ .btn-quiet { background: transparent; }
2879
+ .btn-danger { color: var(--err); }
2880
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
2881
+ record or the full nav row would widen the page past the viewport. */
2882
+ .layout {
2883
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
2884
+ flex: 1 0 auto; min-width: 0;
2885
+ }
2886
+ nav.side {
2887
+ border-right: 1px solid var(--line); padding: 12px;
2888
+ display: flex; flex-direction: column; gap: 4px;
2889
+ background: var(--bg-elev);
2890
+ }
2891
+ nav.side button {
2892
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
2893
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
2894
+ }
2895
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
2896
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
2897
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
2898
+ .lede { margin: 0 0 16px; color: var(--muted); }
2899
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
2900
+ .card {
2901
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
2902
+ padding: 14px 16px; box-shadow: var(--shadow);
2903
+ }
2904
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
2905
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
2906
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
2907
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
2908
+ .collection {
2909
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
2910
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
2911
+ }
2912
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
2913
+ .collection small { display: block; color: var(--faint); }
2914
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
2915
+ .chip {
2916
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
2917
+ border-radius: 999px; padding: 4px 8px;
2918
+ }
2919
+ .chip i { color: var(--faint); font-style: normal; }
2920
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
2921
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
2922
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
2923
+ tr.clickable { cursor: pointer; }
2924
+ tr.clickable:hover { background: var(--bg-muted); }
2925
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
2926
+ pre {
2927
+ margin: 0; white-space: pre-wrap; word-break: break-word;
2928
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
2929
+ }
2930
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
2931
+ .banner {
2932
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
2933
+ background: var(--err-soft); color: var(--err);
2934
+ }
2935
+ .banner.show { display: block; }
2936
+ .empty { color: var(--muted); padding: 24px 8px; }
2937
+ dialog {
2938
+ border: 1px solid var(--line); border-radius: var(--radius); padding: 0; background: var(--bg-elev);
2939
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: none;
2940
+ }
2941
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
2942
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
2943
+ textarea {
2944
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
2945
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
2946
+ font-family: var(--mono); font-size: 12px;
2947
+ }
2948
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
2949
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
2950
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
2951
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
2952
+ .status-2 { color: var(--ok); }
2953
+ .status-4, .status-5, .status-0 { color: var(--err); }
2954
+ .stack { display: flex; flex-direction: column; gap: 12px; }
2955
+ .route {
2956
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
2957
+ padding: 8px 0; border-bottom: 1px solid var(--line);
2958
+ }
2959
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
2960
+ @media (max-width: 800px) {
2961
+ header.top {
2962
+ align-items: stretch; flex-direction: column;
2963
+ padding-top: max(10px, env(safe-area-inset-top));
2964
+ }
2965
+ input, select, textarea { font-size: 16px; }
2966
+ .brand, .vendor, .controls { width: 100%; }
2967
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
2968
+ .layout { grid-template-columns: minmax(0, 1fr); }
2969
+ nav.side {
2970
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
2971
+ border-right: 0; border-bottom: 1px solid var(--line);
2972
+ padding: 8px;
2973
+ }
2974
+ nav.side button { white-space: nowrap; flex: none; }
2975
+ .split { grid-template-columns: minmax(0, 1fr); }
2976
+ main { padding: 14px; }
2977
+ table, thead, tbody, tr, th, td { display: block; }
2978
+ thead { display: none; }
2979
+ tr {
2980
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
2981
+ background: var(--bg-elev); min-width: 0;
2982
+ }
2983
+ td {
2984
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
2985
+ min-width: 0; overflow-wrap: anywhere;
2986
+ }
2987
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
2988
+ .route { grid-template-columns: 72px 1fr; }
2989
+ .route button { grid-column: 1 / -1; }
2990
+ }
2991
+ </style>
2992
+ </head>
2993
+ <body>
2994
+ <div class="app" data-service="${name}" data-mockingbird-admin>
2995
+ <header class="top">
2996
+ <div class="brand">
2997
+ <div class="brand-id">
2998
+ <strong>${name}</strong>
2999
+ <span>Admin</span>
3000
+ </div>
3001
+ <div class="vendor" id="vendor" hidden></div>
3002
+ </div>
3003
+ <div class="controls">
3004
+ <label class="field">Namespace
3005
+ <select id="namespace" aria-label="Namespace"></select>
3006
+ </label>
3007
+ <label class="field">Admin key
3008
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
3009
+ </label>
3010
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
3011
+ <button class="btn" id="refresh" type="button">Refresh</button>
3012
+ </div>
3013
+ </header>
3014
+ <div class="layout">
3015
+ <nav class="side" id="nav" aria-label="Admin sections">
3016
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
3017
+ <button type="button" data-view="state">State</button>
3018
+ <button type="button" data-view="clock">Clock</button>
3019
+ <button type="button" data-view="faults">Faults</button>
3020
+ <button type="button" data-view="journal">Journal</button>
3021
+ <button type="button" data-view="routes">Routes</button>
3022
+ </nav>
3023
+ <main id="views">
3024
+ <p class="banner" id="banner" role="alert"></p>
3025
+ <section class="view" id="view-overview">
3026
+ <h2>Overview</h2>
3027
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
3028
+ <div class="grid" id="overview-cards"></div>
3029
+ <h3>Recent requests</h3>
3030
+ <div id="overview-requests"></div>
3031
+ </section>
3032
+ <section class="view" id="view-state" hidden>
3033
+ <h2>State</h2>
3034
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
3035
+ <div class="split">
3036
+ <div id="collections"></div>
3037
+ <div>
3038
+ <div id="schema"></div>
3039
+ <div class="row-actions">
3040
+ <button class="btn-primary" id="new-record" type="button">New record</button>
3041
+ </div>
3042
+ <div id="records"></div>
3043
+ </div>
3044
+ </div>
3045
+ </section>
3046
+ <section class="view" id="view-clock" hidden>
3047
+ <h2>Clock</h2>
3048
+ <p class="lede">The clock every timestamp in this mock reads.</p>
3049
+ <div class="card" id="clock-readout"></div>
3050
+ <div class="row-actions">
3051
+ <button class="btn" type="button" data-advance="60000">+1m</button>
3052
+ <button class="btn" type="button" data-advance="900000">+15m</button>
3053
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
3054
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
3055
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
3056
+ <button class="btn" id="freeze" type="button">Freeze</button>
3057
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
3058
+ </div>
3059
+ <form id="clock-set" class="row-actions">
3060
+ <label class="field">Set instant
3061
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
3062
+ </label>
3063
+ <button class="btn-primary" type="submit">Set</button>
3064
+ </form>
3065
+ </section>
3066
+ <section class="view" id="view-faults" hidden>
3067
+ <h2>Faults</h2>
3068
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
3069
+ <form id="fault-form" class="card stack">
3070
+ <label class="field">Preset
3071
+ <select id="fault-preset"><option value="">Custom rule</option></select>
3072
+ </label>
3073
+ <label class="field">Status
3074
+ <input id="fault-status" inputmode="numeric" placeholder="503">
3075
+ </label>
3076
+ <label class="field">Path prefix
3077
+ <input id="fault-path" placeholder="/v1">
3078
+ </label>
3079
+ <label class="field">Method
3080
+ <input id="fault-method" placeholder="GET">
3081
+ </label>
3082
+ <div class="dialog-actions">
3083
+ <button class="btn-primary" type="submit">Add fault</button>
3084
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
3085
+ </div>
3086
+ </form>
3087
+ <div id="fault-list"></div>
3088
+ </section>
3089
+ <section class="view" id="view-journal" hidden>
3090
+ <h2>Journal</h2>
3091
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
3092
+ <div class="row-actions">
3093
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
3094
+ </div>
3095
+ <div id="journal"></div>
3096
+ </section>
3097
+ <section class="view" id="view-routes" hidden>
3098
+ <h2>Routes</h2>
3099
+ <p class="lede">Shared controls, plus any routes this mock adds. Extra routes are how a bespoke workflow shows up beside the default UI.</p>
3100
+ <div id="route-list"></div>
3101
+ <form id="route-form" class="card stack">
3102
+ <strong id="route-title">Select a route</strong>
3103
+ <label class="field">JSON body
3104
+ <textarea id="route-body" placeholder="{ }"></textarea>
3105
+ </label>
3106
+ <div class="dialog-actions">
3107
+ <button class="btn-primary" type="submit">Send</button>
3108
+ </div>
3109
+ <pre id="route-result">Response will show here.</pre>
3110
+ </form>
3111
+ </section>
3112
+ </main>
3113
+ </div>
3114
+ </div>
3115
+ <dialog id="editor">
3116
+ <form method="dialog" id="editor-form">
3117
+ <strong id="editor-title">Record</strong>
3118
+ <label class="field">Id
3119
+ <input id="editor-id" required>
3120
+ </label>
3121
+ <label class="field">JSON value
3122
+ <textarea id="editor-value"></textarea>
3123
+ </label>
3124
+ <div class="dialog-actions">
3125
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
3126
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
3127
+ <button class="btn-primary" type="submit" value="save">Save</button>
3128
+ </div>
3129
+ </form>
3130
+ </dialog>
3131
+ ${script}
3132
+ </body>
3133
+ </html>`;
3134
+ };
3135
+ var htmlResponse = (body) => new Response(body, {
3136
+ status: 200,
3137
+ headers: {
3138
+ "content-type": "text/html; charset=utf-8",
3139
+ "cache-control": "no-store"
3140
+ }
3141
+ });
3142
+ var json3 = (body) => new Response(JSON.stringify(body), {
3143
+ status: 200,
3144
+ headers: { "content-type": "application/json; charset=utf-8" }
3145
+ });
3146
+ var adminUiRoutes = (service, ui) => {
3147
+ const shell = () => renderAdminDocument(service);
3148
+ const document3 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
3149
+ return {
3150
+ "GET /ui": () => htmlResponse(document3()),
3151
+ "GET /ui/": () => htmlResponse(document3()),
3152
+ "GET /ui/manifest": () => json3({
3153
+ service,
3154
+ panels: (ui?.panels ?? []).map((panel) => ({
3155
+ id: panel.id,
3156
+ title: panel.title,
3157
+ ...panel.description !== void 0 ? { description: panel.description } : {},
3158
+ html: panel.html,
3159
+ ...panel.script !== void 0 ? { script: panel.script } : {}
3160
+ }))
3161
+ })
3162
+ };
3163
+ };
3164
+
1432
3165
  // ../../openapi/metadata/dist/types.js
1433
3166
  var EXTENSION_KEYS = {
1434
3167
  operation: "x-mockingbird",
@@ -1441,11 +3174,11 @@ var EXTENSION_KEYS = {
1441
3174
  };
1442
3175
 
1443
3176
  // ../../openapi/metadata/dist/read.js
1444
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3177
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1445
3178
  var extensionOf = (holder, key) => holder[key];
1446
3179
  var operationMetadata = (operation) => {
1447
3180
  const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1448
- const ext = isRecord2(raw) ? raw : {};
3181
+ const ext = isRecord3(raw) ? raw : {};
1449
3182
  const supported = ext.supported ?? true;
1450
3183
  const parity = ext.parity ?? {};
1451
3184
  return {
@@ -1555,9 +3288,9 @@ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1555
3288
  this.name = "OperationRegistryError";
1556
3289
  }
1557
3290
  };
1558
- var verifyOperations = (document2, handlers) => {
3291
+ var verifyOperations = (document3, handlers) => {
1559
3292
  const problems = [];
1560
- const operations = listOperations(document2);
3293
+ const operations = listOperations(document3);
1561
3294
  const seen = /* @__PURE__ */ new Set();
1562
3295
  for (const operation of operations) {
1563
3296
  if (seen.has(operation.operationId))
@@ -1666,8 +3399,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1666
3399
  });
1667
3400
  };
1668
3401
 
3402
+ // ../core/dist/state-view.js
3403
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
3404
+ var RECORD_ID = /^[^\s/]{1,256}$/;
3405
+ var SAMPLE = 25;
3406
+ var WALK_LIMIT = 1e4;
3407
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
3408
+ var fail = (status, message) => ({ ok: false, status, message });
3409
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3410
+ var kindOf = (value) => {
3411
+ if (value === null)
3412
+ return "null";
3413
+ if (Array.isArray(value))
3414
+ return "array";
3415
+ switch (typeof value) {
3416
+ case "string":
3417
+ return "string";
3418
+ case "number":
3419
+ return Number.isFinite(value) ? "number" : "unknown";
3420
+ case "boolean":
3421
+ return "boolean";
3422
+ case "object":
3423
+ return "object";
3424
+ default:
3425
+ return "unknown";
3426
+ }
3427
+ };
3428
+ var humanize = (name) => {
3429
+ const words = name.replace(/[@:_-]+/g, " ").trim();
3430
+ if (words === "")
3431
+ return name;
3432
+ return words.charAt(0).toUpperCase() + words.slice(1);
3433
+ };
3434
+ var jsonValue = (value) => {
3435
+ if (value === void 0)
3436
+ return fail(400, "value is required");
3437
+ try {
3438
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
3439
+ } catch {
3440
+ return fail(400, "value must be JSON");
3441
+ }
3442
+ };
3443
+ var ctorName = (value) => {
3444
+ const ctor = value.constructor;
3445
+ return typeof ctor?.name === "string" ? ctor.name : "";
3446
+ };
3447
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
3448
+ var discoverCollections = (root) => {
3449
+ const found = [];
3450
+ const seen = /* @__PURE__ */ new Set();
3451
+ const visit = (value, depth) => {
3452
+ if (found.length + seen.size > WALK_LIMIT)
3453
+ return;
3454
+ if (value === null || typeof value !== "object")
3455
+ return;
3456
+ if (seen.has(value))
3457
+ return;
3458
+ seen.add(value);
3459
+ if (value instanceof Collection) {
3460
+ found.push(value);
3461
+ return;
3462
+ }
3463
+ if (value instanceof Map) {
3464
+ for (const child of value.values())
3465
+ visit(child, depth + 1);
3466
+ return;
3467
+ }
3468
+ if (value instanceof Set) {
3469
+ for (const child of value.values())
3470
+ visit(child, depth + 1);
3471
+ return;
3472
+ }
3473
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
3474
+ return;
3475
+ if (Array.isArray(value)) {
3476
+ const cap = Math.min(value.length, 32);
3477
+ for (let i = 0; i < cap; i++)
3478
+ visit(value[i], depth + 1);
3479
+ return;
3480
+ }
3481
+ let children;
3482
+ try {
3483
+ children = Object.values(value);
3484
+ } catch {
3485
+ return;
3486
+ }
3487
+ for (const child of children)
3488
+ visit(child, depth + 1);
3489
+ };
3490
+ visit(root, 0);
3491
+ return found;
3492
+ };
3493
+ var storedNames = (sqlite, namespace) => {
3494
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
3495
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
3496
+ return [...records, ...sequences].map((row) => row.name);
3497
+ };
3498
+ var blankAccum = (name) => ({
3499
+ name,
3500
+ kinds: /* @__PURE__ */ new Set(),
3501
+ present: 0,
3502
+ nested: /* @__PURE__ */ new Map()
3503
+ });
3504
+ var absorb = (accum, value) => {
3505
+ const kind = kindOf(value);
3506
+ accum.kinds.add(kind);
3507
+ accum.present++;
3508
+ if (!isRecord4(value))
3509
+ return;
3510
+ for (const [key, child] of Object.entries(value)) {
3511
+ const nested = accum.nested.get(key) ?? blankAccum(key);
3512
+ absorb(nested, child);
3513
+ accum.nested.set(key, nested);
3514
+ }
3515
+ };
3516
+ var finishField = (accum, samples) => {
3517
+ const kinds = [...accum.kinds];
3518
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
3519
+ const field = {
3520
+ name: accum.name,
3521
+ kind,
3522
+ optional: accum.present < samples || kinds.includes("null")
3523
+ };
3524
+ if (accum.nested.size > 0) {
3525
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
3526
+ }
3527
+ return field;
3528
+ };
3529
+ var inferFields = (records) => {
3530
+ if (records.length === 0)
3531
+ return [];
3532
+ const sample = records.slice(0, SAMPLE);
3533
+ const objects = sample.filter((record) => isRecord4(record.value));
3534
+ if (objects.length === 0) {
3535
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
3536
+ const list = [...kinds];
3537
+ return [
3538
+ {
3539
+ name: "(value)",
3540
+ kind: list.length === 1 ? list[0] : "unknown",
3541
+ optional: false
3542
+ }
3543
+ ];
3544
+ }
3545
+ const root = /* @__PURE__ */ new Map();
3546
+ for (const record of objects) {
3547
+ for (const [key, value] of Object.entries(record.value)) {
3548
+ const accum = root.get(key) ?? blankAccum(key);
3549
+ absorb(accum, value);
3550
+ root.set(key, accum);
3551
+ }
3552
+ }
3553
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
3554
+ };
3555
+ var mergeFields = (declared, inferred) => {
3556
+ const byName = /* @__PURE__ */ new Map();
3557
+ for (const field of inferred)
3558
+ byName.set(field.name, field);
3559
+ const ordered = [];
3560
+ const seen = /* @__PURE__ */ new Set();
3561
+ for (const field of declared ?? []) {
3562
+ const found = byName.get(field.name);
3563
+ seen.add(field.name);
3564
+ if (!found) {
3565
+ ordered.push({ ...field, optional: field.optional });
3566
+ continue;
3567
+ }
3568
+ ordered.push({
3569
+ ...found,
3570
+ kind: field.kind === "unknown" ? found.kind : field.kind,
3571
+ optional: field.optional || found.optional,
3572
+ ...field.description !== void 0 ? { description: field.description } : {},
3573
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
3574
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
3575
+ });
3576
+ }
3577
+ for (const field of inferred) {
3578
+ if (!seen.has(field.name))
3579
+ ordered.push(field);
3580
+ }
3581
+ return ordered;
3582
+ };
3583
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
3584
+ var readRecord = (collection, id) => {
3585
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
3586
+ const row = rows.find((entry) => entry.id === id);
3587
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
3588
+ };
3589
+ var inspectState = (scope) => {
3590
+ const declared = /* @__PURE__ */ new Map();
3591
+ for (const declaration of scope.declarations ?? []) {
3592
+ if (COLLECTION_NAME.test(declaration.name))
3593
+ declared.set(declaration.name, declaration);
3594
+ }
3595
+ const names = new Set(declared.keys());
3596
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
3597
+ names.add(name);
3598
+ for (const collection of discoverCollections(scope.root)) {
3599
+ if (collection.namespace === scope.storageNamespace)
3600
+ names.add(collection.collectionName);
3601
+ }
3602
+ const collections = [];
3603
+ for (const name of names) {
3604
+ if (!COLLECTION_NAME.test(name))
3605
+ continue;
3606
+ const declaration = declared.get(name);
3607
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3608
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
3609
+ const inferred = inferFields(records);
3610
+ const fields = mergeFields(declaration?.fields, inferred);
3611
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
3612
+ collections.push({
3613
+ name,
3614
+ label: declaration?.label ?? humanize(name),
3615
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
3616
+ count: collection.count(),
3617
+ source,
3618
+ fields,
3619
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
3620
+ });
3621
+ }
3622
+ const order = /* @__PURE__ */ new Map();
3623
+ for (const [index, item] of (scope.declarations ?? []).entries())
3624
+ order.set(item.name, index);
3625
+ collections.sort((a, b) => {
3626
+ const left = order.get(a.name);
3627
+ const right = order.get(b.name);
3628
+ if (left !== void 0 && right !== void 0)
3629
+ return left - right;
3630
+ if (left !== void 0)
3631
+ return -1;
3632
+ if (right !== void 0)
3633
+ return 1;
3634
+ return a.name.localeCompare(b.name);
3635
+ });
3636
+ return {
3637
+ namespace: scope.namespace,
3638
+ storageNamespace: scope.storageNamespace,
3639
+ collections
3640
+ };
3641
+ };
3642
+ var pageOf = (sqlite, storageNamespace, name, query) => {
3643
+ if (!COLLECTION_NAME.test(name))
3644
+ return fail(400, "collection name is not allowed");
3645
+ const limit = query.limit ?? 50;
3646
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
3647
+ return fail(400, "limit must be an integer from 1 to 200");
3648
+ }
3649
+ const order = query.order ?? "newest";
3650
+ if (order !== "newest" && order !== "oldest")
3651
+ return fail(400, 'order must be "newest" or "oldest"');
3652
+ const collection = collectionOf(sqlite, storageNamespace, name);
3653
+ const rows = collection.list({ order }).filter((row) => {
3654
+ if (query.after === void 0)
3655
+ return true;
3656
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
3657
+ });
3658
+ const slice = rows.slice(0, limit);
3659
+ const last = slice.at(-1);
3660
+ return {
3661
+ ok: true,
3662
+ value: {
3663
+ collection: name,
3664
+ count: collection.count(),
3665
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
3666
+ next: rows.length > limit && last ? last.seq : null
3667
+ }
3668
+ };
3669
+ };
3670
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
3671
+ var readStateRecord = (scope, name, id) => {
3672
+ if (!COLLECTION_NAME.test(name))
3673
+ return fail(400, "collection name is not allowed");
3674
+ if (!RECORD_ID.test(id))
3675
+ return fail(400, "record id is not allowed");
3676
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
3677
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
3678
+ };
3679
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
3680
+ var createStateRecord = (scope, name, input) => {
3681
+ if (!COLLECTION_NAME.test(name))
3682
+ return fail(400, "collection name is not allowed");
3683
+ const parsed = jsonValue(input.value);
3684
+ if (!parsed.ok)
3685
+ return parsed;
3686
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3687
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
3688
+ const checked = requireId(id);
3689
+ if (!checked.ok)
3690
+ return checked;
3691
+ if (collection.has(checked.value))
3692
+ return fail(409, `record ${checked.value} already exists`);
3693
+ const stored = collection.insert(checked.value, parsed.value);
3694
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
3695
+ };
3696
+ var replaceStateRecord = (scope, name, id, value) => {
3697
+ if (!COLLECTION_NAME.test(name))
3698
+ return fail(400, "collection name is not allowed");
3699
+ const checked = requireId(id);
3700
+ if (!checked.ok)
3701
+ return checked;
3702
+ const parsed = jsonValue(value);
3703
+ if (!parsed.ok)
3704
+ return parsed;
3705
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3706
+ if (!collection.has(checked.value))
3707
+ return fail(404, `no record ${checked.value} in ${name}`);
3708
+ const stored = collection.update(checked.value, parsed.value);
3709
+ if (!stored)
3710
+ return fail(404, `no record ${checked.value} in ${name}`);
3711
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
3712
+ };
3713
+ var patchStateRecord = (scope, name, id, value) => {
3714
+ const current = readStateRecord(scope, name, id);
3715
+ if (!current.ok)
3716
+ return current;
3717
+ const parsed = jsonValue(value);
3718
+ if (!parsed.ok)
3719
+ return parsed;
3720
+ const next = isRecord4(current.value.value) && isRecord4(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
3721
+ return replaceStateRecord(scope, name, id, next);
3722
+ };
3723
+ var deleteStateRecord = (scope, name, id) => {
3724
+ if (!COLLECTION_NAME.test(name))
3725
+ return fail(400, "collection name is not allowed");
3726
+ const checked = requireId(id);
3727
+ if (!checked.ok)
3728
+ return checked;
3729
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
3730
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
3731
+ };
3732
+ var json4 = (status, body) => new Response(JSON.stringify(body), {
3733
+ status,
3734
+ headers: { "content-type": "application/json; charset=utf-8" }
3735
+ });
3736
+ var adminError2 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
3737
+ var fromResult = (result, status) => result.ok ? json4(status, result.value) : adminError2(result.status, result.message);
3738
+ var integerParam = (value) => {
3739
+ if (value === null)
3740
+ return void 0;
3741
+ if (!/^-?\d+$/.test(value))
3742
+ return "bad";
3743
+ return Number(value);
3744
+ };
3745
+ var stateAdminRoutes = (routes) => {
3746
+ const open = (namespace) => {
3747
+ try {
3748
+ return { ok: true, value: routes.open(namespace) };
3749
+ } catch (error) {
3750
+ return fail(400, error instanceof Error ? error.message : String(error));
3751
+ }
3752
+ };
3753
+ const wrote = (namespace) => {
3754
+ routes.afterWrite?.(namespace);
3755
+ };
3756
+ return {
3757
+ "GET /state": ({ namespace }) => {
3758
+ const scope = open(namespace);
3759
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
3760
+ },
3761
+ "GET /state/:collection": ({ namespace, params, url }) => {
3762
+ const scope = open(namespace);
3763
+ if (!scope.ok)
3764
+ return fromResult(scope, 200);
3765
+ const limit = integerParam(url.searchParams.get("limit"));
3766
+ const after = integerParam(url.searchParams.get("after"));
3767
+ if (limit === "bad")
3768
+ return adminError2(400, "limit: expected an integer");
3769
+ if (after === "bad")
3770
+ return adminError2(400, "after: expected a sequence number");
3771
+ const order = url.searchParams.get("order");
3772
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
3773
+ ...limit !== void 0 ? { limit } : {},
3774
+ ...after !== void 0 ? { after } : {},
3775
+ ...order === "newest" || order === "oldest" ? { order } : {}
3776
+ }), 200);
3777
+ },
3778
+ "GET /state/:collection/:id": ({ namespace, params }) => {
3779
+ const scope = open(namespace);
3780
+ if (!scope.ok)
3781
+ return fromResult(scope, 200);
3782
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
3783
+ },
3784
+ "POST /state/:collection": ({ namespace, params, body }) => {
3785
+ const scope = open(namespace);
3786
+ if (!scope.ok)
3787
+ return fromResult(scope, 201);
3788
+ if (!isRecord4(body) || !("value" in body)) {
3789
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
3790
+ }
3791
+ const id = body.id;
3792
+ if (id !== void 0 && typeof id !== "string")
3793
+ return adminError2(400, "id must be a string");
3794
+ const created = createStateRecord(scope.value, params.collection ?? "", {
3795
+ ...typeof id === "string" ? { id } : {},
3796
+ value: body.value
3797
+ });
3798
+ if (created.ok)
3799
+ wrote(namespace);
3800
+ return fromResult(created, 201);
3801
+ },
3802
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
3803
+ const scope = open(namespace);
3804
+ if (!scope.ok)
3805
+ return fromResult(scope, 200);
3806
+ if (!isRecord4(body) || !("value" in body))
3807
+ return adminError2(400, 'expected {"value": <json>}');
3808
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3809
+ if (replaced.ok)
3810
+ wrote(namespace);
3811
+ return fromResult(replaced, 200);
3812
+ },
3813
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
3814
+ const scope = open(namespace);
3815
+ if (!scope.ok)
3816
+ return fromResult(scope, 200);
3817
+ if (!isRecord4(body) || !("value" in body))
3818
+ return adminError2(400, 'expected {"value": <json>}');
3819
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3820
+ if (patched.ok)
3821
+ wrote(namespace);
3822
+ return fromResult(patched, 200);
3823
+ },
3824
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
3825
+ const scope = open(namespace);
3826
+ if (!scope.ok)
3827
+ return fromResult(scope, 200);
3828
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
3829
+ if (removed.ok)
3830
+ wrote(namespace);
3831
+ return fromResult(removed, 200);
3832
+ }
3833
+ };
3834
+ };
3835
+
1669
3836
  // ../core/dist/version.js
1670
- var PACKAGE_VERSION = true ? "1.3.0" : UNRELEASED_VERSION;
3837
+ var PACKAGE_VERSION = true ? "1.5.0" : UNRELEASED_VERSION;
1671
3838
 
1672
3839
  // ../core/dist/signing.js
1673
3840
  var encoder = new TextEncoder();
@@ -2002,11 +4169,11 @@ var createWebhookHub = (options) => {
2002
4169
  };
2003
4170
  return hub;
2004
4171
  };
2005
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2006
- var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2007
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4172
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4173
+ var adminError3 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
4174
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2008
4175
  var parseEndpoint = (value) => {
2009
- if (!isRecord3(value) || typeof value.url !== "string")
4176
+ if (!isRecord5(value) || typeof value.url !== "string")
2010
4177
  return "each endpoint needs a url";
2011
4178
  try {
2012
4179
  new URL(value.url);
@@ -2023,18 +4190,18 @@ var parseEndpoint = (value) => {
2023
4190
  const events = value.events ?? value.enabledEvents;
2024
4191
  if (Array.isArray(events))
2025
4192
  endpoint.events = events.map(String);
2026
- if (isRecord3(value.tags)) {
4193
+ if (isRecord5(value.tags)) {
2027
4194
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
2028
4195
  }
2029
4196
  if (typeof value.account === "string")
2030
4197
  endpoint.tags = { ...endpoint.tags, account: value.account };
2031
- if (isRecord3(value.headers)) {
4198
+ if (isRecord5(value.headers)) {
2032
4199
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
2033
4200
  }
2034
4201
  return endpoint;
2035
4202
  };
2036
4203
  var webhookAdminRoutes = (hub) => ({
2037
- "GET /webhooks": ({ url, namespace }) => json3(200, {
4204
+ "GET /webhooks": ({ url, namespace }) => json5(200, {
2038
4205
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
2039
4206
  const type = url.searchParams.get("type");
2040
4207
  return type === null || d.type === type;
@@ -2042,51 +4209,51 @@ var webhookAdminRoutes = (hub) => ({
2042
4209
  }),
2043
4210
  "GET /webhooks/events": ({ url, namespace }) => {
2044
4211
  const type = url.searchParams.get("type");
2045
- return json3(200, {
4212
+ return json5(200, {
2046
4213
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
2047
4214
  });
2048
4215
  },
2049
4216
  "POST /webhooks/:id/replay": async ({ params }) => {
2050
4217
  const replayed = await hub.replay(params.id);
2051
- return replayed ? json3(200, replayed) : adminError2(404, `no delivery ${params.id}`);
4218
+ return replayed ? json5(200, replayed) : adminError3(404, `no delivery ${params.id}`);
2052
4219
  },
2053
4220
  "POST /webhooks/flush": async () => {
2054
4221
  await hub.flush();
2055
- return json3(200, { status: "ok" });
4222
+ return json5(200, { status: "ok" });
2056
4223
  },
2057
4224
  "POST /webhooks/faults": ({ body, namespace }) => {
2058
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2059
- return adminError2(400, "mode must be duplicate, reorder or drop");
4225
+ if (!isRecord5(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
4226
+ return adminError3(400, "mode must be duplicate, reorder or drop");
2060
4227
  }
2061
4228
  const fault = { mode: body.mode };
2062
4229
  if (typeof body.count === "number")
2063
4230
  fault.count = body.count;
2064
4231
  hub.fault(namespace, fault);
2065
- return json3(201, { namespace, ...fault });
4232
+ return json5(201, { namespace, ...fault });
2066
4233
  },
2067
- "GET /webhook-endpoints": ({ namespace }) => json3(200, {
4234
+ "GET /webhook-endpoints": ({ namespace }) => json5(200, {
2068
4235
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
2069
4236
  ...rest,
2070
4237
  secret: secret ? "(set)" : null
2071
4238
  }))
2072
4239
  }),
2073
4240
  "PUT /webhook-endpoints": ({ body, namespace }) => {
2074
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
4241
+ const list = Array.isArray(body) ? body : isRecord5(body) ? body.endpoints : void 0;
2075
4242
  if (!Array.isArray(list))
2076
- return adminError2(400, "expected [{url, secret?, events?}]");
4243
+ return adminError3(400, "expected [{url, secret?, events?}]");
2077
4244
  const parsed = [];
2078
4245
  for (const each of list) {
2079
4246
  const endpoint = parseEndpoint(each);
2080
4247
  if (typeof endpoint === "string")
2081
- return adminError2(400, endpoint);
4248
+ return adminError3(400, endpoint);
2082
4249
  parsed.push(endpoint);
2083
4250
  }
2084
4251
  const set = hub.setEndpoints(namespace, parsed);
2085
- return json3(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
4252
+ return json5(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2086
4253
  },
2087
4254
  "DELETE /webhook-endpoints": ({ namespace }) => {
2088
4255
  hub.setEndpoints(namespace, []);
2089
- return json3(200, { status: "ok" });
4256
+ return json5(200, { status: "ok" });
2090
4257
  }
2091
4258
  });
2092
4259
  var parsePayload = (message) => {
@@ -2141,8 +4308,8 @@ var DroppedConnectionError = class extends TypeError {
2141
4308
  this.name = "TypeError";
2142
4309
  }
2143
4310
  };
2144
- var operationMatcher = (document2) => {
2145
- const matchers = listOperations(document2).map((operation) => ({
4311
+ var operationMatcher = (document3) => {
4312
+ const matchers = listOperations(document3).map((operation) => ({
2146
4313
  operationId: operation.operationId,
2147
4314
  method: operation.method.toUpperCase(),
2148
4315
  pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
@@ -2151,6 +4318,7 @@ var operationMatcher = (document2) => {
2151
4318
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2152
4319
  };
2153
4320
  var createRuntime = (options) => {
4321
+ assertAdminUi(options.adminUi);
2154
4322
  const sqlite = bootSqlite(options.sqlite);
2155
4323
  const clock = options.clock ?? createClock();
2156
4324
  const rng = createRng(options.seed ?? 0);
@@ -2236,10 +4404,10 @@ var createRuntime = (options) => {
2236
4404
  const ensureBranch = (namespace, branch2, at) => {
2237
4405
  if (!BRANCH_PATTERN2.test(branch2))
2238
4406
  throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
2239
- const history = timeline(namespace);
4407
+ const history2 = timeline(namespace);
2240
4408
  if (branch2 === "main") {
2241
4409
  if (at !== void 0) {
2242
- const point = history.checkout("main", at);
4410
+ const point = history2.checkout("main", at);
2243
4411
  restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
2244
4412
  captured.set(namespace, point.value.snapshot);
2245
4413
  rng.setState(point.value.rngState);
@@ -2252,10 +4420,10 @@ var createRuntime = (options) => {
2252
4420
  return namespace;
2253
4421
  }
2254
4422
  const storage = physicalBranch(namespace, branch2);
2255
- if (!history.hasBranch(branch2)) {
4423
+ if (!history2.hasBranch(branch2)) {
2256
4424
  if (at === void 0)
2257
- history.commit(capture(namespace));
2258
- const point = history.fork(branch2, at === void 0 ? {} : { from: at });
4425
+ history2.commit(capture(namespace));
4426
+ const point = history2.fork(branch2, at === void 0 ? {} : { from: at });
2259
4427
  const branchRng = createRng(options.seed ?? 0);
2260
4428
  if (point)
2261
4429
  branchRng.setState(point.value.rngState);
@@ -2264,8 +4432,8 @@ var createRuntime = (options) => {
2264
4432
  restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2265
4433
  if (point)
2266
4434
  captured.set(storage, point.value.snapshot);
2267
- } else if (at !== void 0 && history.head(branch2)?.id !== at) {
2268
- const point = history.checkout(branch2, at);
4435
+ } else if (at !== void 0 && history2.head(branch2)?.id !== at) {
4436
+ const point = history2.checkout(branch2, at);
2269
4437
  if (!instances.has(storage)) {
2270
4438
  const branchRng = createRng(options.seed ?? 0);
2271
4439
  branchRng.setState(point.value.rngState);
@@ -2276,7 +4444,7 @@ var createRuntime = (options) => {
2276
4444
  captured.set(storage, point.value.snapshot);
2277
4445
  } else {
2278
4446
  if (!instances.has(storage)) {
2279
- const point = history.head(branch2);
4447
+ const point = history2.head(branch2);
2280
4448
  const branchRng = createRng(options.seed ?? 0);
2281
4449
  if (point)
2282
4450
  branchRng.setState(point.value.rngState);
@@ -2300,8 +4468,8 @@ var createRuntime = (options) => {
2300
4468
  const checkout = (checkpointId, checkoutOptions = {}) => {
2301
4469
  const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
2302
4470
  const branchName = checkoutOptions.branch ?? "main";
2303
- const history = timeline(namespace);
2304
- const point = history.checkout(branchName, checkpointId);
4471
+ const history2 = timeline(namespace);
4472
+ const point = history2.checkout(branchName, checkpointId);
2305
4473
  const storage = ensureBranch(namespace, branchName);
2306
4474
  restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2307
4475
  captured.set(storage, point.value.snapshot);
@@ -2351,12 +4519,25 @@ var createRuntime = (options) => {
2351
4519
  instance(name);
2352
4520
  restoreNamespace(sqlite, storageNamespace(name), from);
2353
4521
  captured.set(name, from);
2354
- const history = timelines.get(name);
2355
- if (history)
2356
- history.commit(capture(name), { branch: "main" });
4522
+ const history2 = timelines.get(name);
4523
+ if (history2)
4524
+ history2.commit(capture(name), { branch: "main" });
2357
4525
  else
2358
4526
  timeline(name);
2359
4527
  };
4528
+ const declarationsFor = (namespace) => {
4529
+ const declared = options.state;
4530
+ if (!declared)
4531
+ return [];
4532
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
4533
+ };
4534
+ const stateScope = (namespace) => ({
4535
+ sqlite,
4536
+ namespace,
4537
+ storageNamespace: storageNamespace(namespace),
4538
+ root: instance(namespace),
4539
+ declarations: declarationsFor(namespace)
4540
+ });
2360
4541
  const runtime = {
2361
4542
  name: options.name,
2362
4543
  sqlite,
@@ -2395,6 +4576,7 @@ var createRuntime = (options) => {
2395
4576
  branch,
2396
4577
  checkout,
2397
4578
  timeline,
4579
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2398
4580
  fetch: async (incoming) => {
2399
4581
  let request = incoming;
2400
4582
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2568,10 +4750,10 @@ var createRuntime = (options) => {
2568
4750
  },
2569
4751
  release: (name, checkpointId) => timeline(name).release(checkpointId),
2570
4752
  inspect: (name) => {
2571
- const history = timeline(name);
4753
+ const history2 = timeline(name);
2572
4754
  return {
2573
- branches: history.branches(),
2574
- checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
4755
+ branches: history2.branches(),
4756
+ checkpoints: history2.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
2575
4757
  id,
2576
4758
  branch: branchName,
2577
4759
  parent,
@@ -2586,13 +4768,22 @@ var createRuntime = (options) => {
2586
4768
  } : {},
2587
4769
  routes: {
2588
4770
  ...credentialRoutes(credentials),
2589
- ...options.presets ? presetRoutes(options.presets, runtime) : {},
2590
4771
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2591
- ...options.admin?.(runtime) ?? {}
4772
+ ...options.admin?.(runtime) ?? {},
4773
+ // Shell routes win a colliding key. Fault presets are one of them: the admin page
4774
+ // maps `presets`, and a service route must not replace that list with a record.
4775
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
4776
+ ...stateAdminRoutes({
4777
+ open: stateScope,
4778
+ afterWrite: (namespace) => {
4779
+ checkpoint(namespace, "main");
4780
+ }
4781
+ }),
4782
+ ...adminUiRoutes(options.name, options.adminUi)
2592
4783
  },
2593
4784
  adminKey: options.adminKey
2594
4785
  });
2595
- return runtime;
4786
+ return defineMock(runtime);
2596
4787
  };
2597
4788
  var mutableResponse = (response) => {
2598
4789
  try {
@@ -2656,9 +4847,12 @@ var credentialRoutes = (registry) => ({
2656
4847
  }
2657
4848
  });
2658
4849
  var presetRoutes = (presets, runtime) => ({
2659
- "GET /faults/presets": () => adminJson(200, {
2660
- presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
2661
- }),
4850
+ "GET /faults/presets": () => {
4851
+ const body = {
4852
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
4853
+ };
4854
+ return adminJson(200, body);
4855
+ },
2662
4856
  "POST /faults/presets/:name": ({ params, body, namespace }) => {
2663
4857
  const name = params.name;
2664
4858
  if (!presets[name])
@@ -2669,7 +4863,7 @@ var presetRoutes = (presets, runtime) => ({
2669
4863
  });
2670
4864
 
2671
4865
  // src/generated/openapi.ts
2672
- var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Customer.io CDP + App API (Mockingbird subset)","description":"Stateful mock subset of Customer.io: the Segment-compatible CDP ingestion endpoints\\n(\`identify\`, \`track\`, \`batch\`, as \`@customerio/cdp-analytics-node\` posts them), the App API\\ntransactional sends (email, SMS, inbox message) and transactional-message catalog, and the\\nlink-tracking click endpoint. One process serves all three hosts (\`cdp.customer.io\`,\\n\`api.customer.io\`, the tracking domain); their paths do not collide.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from Customer.io's CDP (Segment spec) and App API reference, trimmed to what our consumer sends: customer-io.client.service.ts / notification-adapter.ts / transactional-email-adapter.ts (backend), transactional-client.ts (notification-processor), customerio-trigger-name-validator.ts (notification-service) and mobile-links-click-reporter.service.ts."}},"servers":[{"url":"https://api.customer.io"},{"url":"https://cdp.customer.io"}],"paths":{"/v1/identify":{"post":{"operationId":"CdpIdentify","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IdentifyEvent"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed event","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/track":{"post":{"operationId":"CdpTrack","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TrackEvent"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed event","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/batch":{"post":{"operationId":"CdpBatch","description":"What \`@customerio/cdp-analytics-node\` posts: \`{batch: [...]}\`.","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["batch"],"properties":{"batch":{"type":"array","maxItems":5,"items":{"anyOf":[{"$ref":"#/components/schemas/IdentifyEvent"},{"$ref":"#/components/schemas/TrackEvent"}]}},"sentAt":{"type":"string"},"context":{"type":"object"}}}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed batch","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/send/email":{"post":{"operationId":"SendEmail","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendEmailRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/send/sms":{"post":{"operationId":"SendSms","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendSmsRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/send/inbox_message":{"post":{"operationId":"SendInboxMessage","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendInboxRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/transactional":{"get":{"operationId":"ListTransactionalMessages","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Every transactional message in the workspace (no pagination)","content":{"application/json":{"schema":{"type":"object","required":["messages"],"properties":{"messages":{"type":"array","items":{"$ref":"#/components/schemas/TransactionalMessage"}}}}}}},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/transactional/{transactional_id}":{"parameters":[{"name":"transactional_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"transactional_message","missing":"999999"}}}],"get":{"operationId":"GetTransactionalMessage","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"One transactional message","content":{"application/json":{"schema":{"type":"object","required":["message"],"properties":{"message":{"$ref":"#/components/schemas/TransactionalMessage"}}}}}},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/click/{linkId}":{"parameters":[{"name":"linkId","in":"path","required":true,"schema":{"type":"string","pattern":"^[A-Za-z0-9_~-][A-Za-z0-9._~-]{0,63}$"}}],"post":{"operationId":"ReportClick","description":"Link-tracking click report on the tracking domain (our backend posts it when a smart\\nlink opens the app directly). Unauthenticated.\\n","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Click recorded (no body)"},"404":{"description":"Unknown link","content":{"text/plain":{"schema":{"type":"string"}}}}}},"get":{"operationId":"FollowClick","description":"A browser following a tracked link; redirects to the original URL.","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"302":{"description":"Redirect to the original URL"},"404":{"description":"Unknown link","content":{"text/plain":{"schema":{"type":"string"}}}}}}}},"components":{"securitySchemes":{"cdpWriteKey":{"type":"http","scheme":"basic","description":"\`Basic base64(<write key>:)\` (the CDP source write key as the username)."},"appApiKey":{"type":"http","scheme":"bearer","description":"\`Bearer <App API key>\`."}},"responses":{"Queued":{"description":"Queued for delivery","content":{"application/json":{"schema":{"type":"object","required":["delivery_id","queued_at"],"properties":{"delivery_id":{"type":"string","x-mockingbird-resource":{"type":"delivery","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"queued_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}}}}}}},"AppError":{"description":"An App API error","content":{"application/json":{"schema":{"type":"object","required":["meta"],"properties":{"meta":{"type":"object","required":["error"],"properties":{"error":{"type":"string"}}}}}}}}},"schemas":{"CdpSuccess":{"type":"object","required":["success"],"properties":{"success":{"type":"boolean"}}},"CdpError":{"type":"object","required":["error"],"properties":{"error":{"type":"string"}}},"IdentifyEvent":{"type":"object","properties":{"type":{"type":"string","enum":["identify"]},"userId":{"type":"string","minLength":1,"maxLength":64},"anonymousId":{"type":"string","minLength":1,"maxLength":64},"traits":{"type":"object","additionalProperties":true},"context":{"type":"object"},"integrations":{"type":"object"},"timestamp":{"type":"string"},"messageId":{"type":"string","maxLength":128},"_metadata":{"type":"object"}}},"TrackEvent":{"type":"object","required":["event"],"properties":{"type":{"type":"string","enum":["track"]},"userId":{"type":"string","minLength":1,"maxLength":64},"anonymousId":{"type":"string","minLength":1,"maxLength":64},"event":{"type":"string","minLength":1,"maxLength":150},"properties":{"type":"object","additionalProperties":true},"context":{"type":"object"},"integrations":{"type":"object"},"timestamp":{"type":"string"},"messageId":{"type":"string","maxLength":128},"_metadata":{"type":"object"}}},"Identifiers":{"type":"object","properties":{"id":{"type":"string","minLength":1,"maxLength":64},"email":{"type":"string","format":"email","maxLength":120},"cio_id":{"type":"string","maxLength":64}}},"TransactionalMessageId":{"oneOf":[{"type":"string","minLength":1,"maxLength":150},{"type":"integer","minimum":1}]},"SendEmailRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"to":{"type":"string","maxLength":200},"from":{"type":"string","maxLength":200},"subject":{"type":"string","maxLength":300},"body":{"type":"string"},"message_data":{"type":"object","additionalProperties":true},"send_to_unsubscribed":{"type":"boolean"},"tracked":{"type":"boolean"},"disable_message_retention":{"type":"boolean"},"headers":{"type":"object","additionalProperties":{"type":"string"}},"attachments":{"description":"Customer.io documents a \`{filename: base64}\` map; our backend sends an array of \`{filename, content, content_type}\`. Both are accepted.","oneOf":[{"type":"object","additionalProperties":{"type":"string"}},{"type":"array","items":{"type":"object","required":["filename","content"],"properties":{"filename":{"type":"string"},"content":{"type":"string"},"content_type":{"type":"string"}}}}]}}},"SendSmsRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"to":{"type":"string","maxLength":20},"message_data":{"type":"object","additionalProperties":true},"send_to_unsubscribed":{"type":"boolean"},"tracked":{"type":"boolean"},"disable_message_retention":{"type":"boolean"}}},"SendInboxRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"message_data":{"type":"object","additionalProperties":true}}},"TransactionalMessage":{"type":"object","required":["id","name"],"properties":{"id":{"type":"integer"},"name":{"type":"string"},"trigger_name":{"type":"string","x-mockingbird-resource":{"type":"transactional_message","identity":true}},"description":{"type":"string"},"send_to_unsubscribed":{"type":"boolean"},"link_tracking":{"type":"boolean"},"open_tracking":{"type":"boolean"},"hide_message_body":{"type":"boolean"},"queue_drafts":{"type":"boolean"},"created_at":{"type":"integer"},"updated_at":{"type":"integer"}}}}}}`);
4866
+ var document2 = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Customer.io CDP + App API (Mockingbird subset)","description":"Stateful mock subset of Customer.io: the Segment-compatible CDP ingestion endpoints\\n(\`identify\`, \`track\`, \`batch\`, as \`@customerio/cdp-analytics-node\` posts them), the App API\\ntransactional sends (email, SMS, inbox message) and transactional-message catalog, and the\\nlink-tracking click endpoint. One process serves all three hosts (\`cdp.customer.io\`,\\n\`api.customer.io\`, the tracking domain); their paths do not collide.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from Customer.io's CDP (Segment spec) and App API reference, trimmed to what our consumer sends: customer-io.client.service.ts / notification-adapter.ts / transactional-email-adapter.ts (backend), transactional-client.ts (notification-processor), customerio-trigger-name-validator.ts (notification-service) and mobile-links-click-reporter.service.ts."}},"servers":[{"url":"https://api.customer.io"},{"url":"https://cdp.customer.io"}],"paths":{"/v1/identify":{"post":{"operationId":"CdpIdentify","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IdentifyEvent"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed event","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/track":{"post":{"operationId":"CdpTrack","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TrackEvent"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed event","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/batch":{"post":{"operationId":"CdpBatch","description":"What \`@customerio/cdp-analytics-node\` posts: \`{batch: [...]}\`.","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["batch"],"properties":{"batch":{"type":"array","maxItems":5,"items":{"anyOf":[{"$ref":"#/components/schemas/IdentifyEvent"},{"$ref":"#/components/schemas/TrackEvent"}]}},"sentAt":{"type":"string"},"context":{"type":"object"}}}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed batch","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/send/email":{"post":{"operationId":"SendEmail","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendEmailRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/send/sms":{"post":{"operationId":"SendSms","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendSmsRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/send/inbox_message":{"post":{"operationId":"SendInboxMessage","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendInboxRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/transactional":{"get":{"operationId":"ListTransactionalMessages","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Every transactional message in the workspace (no pagination)","content":{"application/json":{"schema":{"type":"object","required":["messages"],"properties":{"messages":{"type":"array","items":{"$ref":"#/components/schemas/TransactionalMessage"}}}}}}},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/transactional/{transactional_id}":{"parameters":[{"name":"transactional_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"transactional_message","missing":"999999"}}}],"get":{"operationId":"GetTransactionalMessage","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"One transactional message","content":{"application/json":{"schema":{"type":"object","required":["message"],"properties":{"message":{"$ref":"#/components/schemas/TransactionalMessage"}}}}}},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/click/{linkId}":{"parameters":[{"name":"linkId","in":"path","required":true,"schema":{"type":"string","pattern":"^[A-Za-z0-9_~-][A-Za-z0-9._~-]{0,63}$"}}],"post":{"operationId":"ReportClick","description":"Link-tracking click report on the tracking domain (our backend posts it when a smart\\nlink opens the app directly). Unauthenticated.\\n","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Click recorded (no body)"},"404":{"description":"Unknown link","content":{"text/plain":{"schema":{"type":"string"}}}}}},"get":{"operationId":"FollowClick","description":"A browser following a tracked link; redirects to the original URL.","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"302":{"description":"Redirect to the original URL"},"404":{"description":"Unknown link","content":{"text/plain":{"schema":{"type":"string"}}}}}}}},"components":{"securitySchemes":{"cdpWriteKey":{"type":"http","scheme":"basic","description":"\`Basic base64(<write key>:)\` (the CDP source write key as the username)."},"appApiKey":{"type":"http","scheme":"bearer","description":"\`Bearer <App API key>\`."}},"responses":{"Queued":{"description":"Queued for delivery","content":{"application/json":{"schema":{"type":"object","required":["delivery_id","queued_at"],"properties":{"delivery_id":{"type":"string","x-mockingbird-resource":{"type":"delivery","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"queued_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}}}}}}},"AppError":{"description":"An App API error","content":{"application/json":{"schema":{"type":"object","required":["meta"],"properties":{"meta":{"type":"object","required":["error"],"properties":{"error":{"type":"string"}}}}}}}}},"schemas":{"CdpSuccess":{"type":"object","required":["success"],"properties":{"success":{"type":"boolean"}}},"CdpError":{"type":"object","required":["error"],"properties":{"error":{"type":"string"}}},"IdentifyEvent":{"type":"object","properties":{"type":{"type":"string","enum":["identify"]},"userId":{"type":"string","minLength":1,"maxLength":64},"anonymousId":{"type":"string","minLength":1,"maxLength":64},"traits":{"type":"object","additionalProperties":true},"context":{"type":"object"},"integrations":{"type":"object"},"timestamp":{"type":"string"},"messageId":{"type":"string","maxLength":128},"_metadata":{"type":"object"}}},"TrackEvent":{"type":"object","required":["event"],"properties":{"type":{"type":"string","enum":["track"]},"userId":{"type":"string","minLength":1,"maxLength":64},"anonymousId":{"type":"string","minLength":1,"maxLength":64},"event":{"type":"string","minLength":1,"maxLength":150},"properties":{"type":"object","additionalProperties":true},"context":{"type":"object"},"integrations":{"type":"object"},"timestamp":{"type":"string"},"messageId":{"type":"string","maxLength":128},"_metadata":{"type":"object"}}},"Identifiers":{"type":"object","properties":{"id":{"type":"string","minLength":1,"maxLength":64},"email":{"type":"string","format":"email","maxLength":120},"cio_id":{"type":"string","maxLength":64}}},"TransactionalMessageId":{"oneOf":[{"type":"string","minLength":1,"maxLength":150},{"type":"integer","minimum":1}]},"SendEmailRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"to":{"type":"string","maxLength":200},"from":{"type":"string","maxLength":200},"subject":{"type":"string","maxLength":300},"body":{"type":"string"},"message_data":{"type":"object","additionalProperties":true},"send_to_unsubscribed":{"type":"boolean"},"tracked":{"type":"boolean"},"disable_message_retention":{"type":"boolean"},"headers":{"type":"object","additionalProperties":{"type":"string"}},"attachments":{"description":"Customer.io documents a \`{filename: base64}\` map; our backend sends an array of \`{filename, content, content_type}\`. Both are accepted.","oneOf":[{"type":"object","additionalProperties":{"type":"string"}},{"type":"array","items":{"type":"object","required":["filename","content"],"properties":{"filename":{"type":"string"},"content":{"type":"string"},"content_type":{"type":"string"}}}}]}}},"SendSmsRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"to":{"type":"string","maxLength":20},"message_data":{"type":"object","additionalProperties":true},"send_to_unsubscribed":{"type":"boolean"},"tracked":{"type":"boolean"},"disable_message_retention":{"type":"boolean"}}},"SendInboxRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"message_data":{"type":"object","additionalProperties":true}}},"TransactionalMessage":{"type":"object","required":["id","name"],"properties":{"id":{"type":"integer"},"name":{"type":"string"},"trigger_name":{"type":"string","x-mockingbird-resource":{"type":"transactional_message","identity":true}},"description":{"type":"string"},"send_to_unsubscribed":{"type":"boolean"},"link_tracking":{"type":"boolean"},"open_tracking":{"type":"boolean"},"hide_message_body":{"type":"boolean"},"queue_drafts":{"type":"boolean"},"created_at":{"type":"integer"},"updated_at":{"type":"integer"}}}}}}`);
2673
4867
  var operationIds = ["CdpIdentify", "CdpTrack", "CdpBatch", "SendEmail", "SendSms", "SendInboxMessage", "ListTransactionalMessages", "GetTransactionalMessage", "FollowClick", "ReportClick"];
2674
4868
  var supportedOperationIds = ["CdpIdentify", "CdpTrack", "CdpBatch", "SendEmail", "SendSms", "SendInboxMessage", "ListTransactionalMessages", "GetTransactionalMessage", "FollowClick", "ReportClick"];
2675
4869
 
@@ -2890,9 +5084,9 @@ var CUSTOMERIO_PRESETS = {
2890
5084
  webhook: { mode: "drop" }
2891
5085
  }
2892
5086
  };
2893
- var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2894
- var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2895
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5087
+ var json6 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
5088
+ var adminError4 = (status, message) => json6(status, { error: { type: "mockingbird_admin", message } });
5089
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2896
5090
  var adminRoutes = (runtime) => ({
2897
5091
  ...outboxAdminRoutes(
2898
5092
  runtime,
@@ -2909,21 +5103,21 @@ var adminRoutes = (runtime) => ({
2909
5103
  const userId = url.searchParams.get("userId");
2910
5104
  const type = url.searchParams.get("type");
2911
5105
  const event = url.searchParams.get("event");
2912
- return json4(200, {
5106
+ return json6(200, {
2913
5107
  events: runtime.instance(namespace).state.cdp.list({
2914
5108
  order: "oldest",
2915
5109
  where: (e) => (userId === null || e.userId === userId) && (type === null || e.type === type) && (event === null || e.event === event)
2916
5110
  }).map((row) => row.value)
2917
5111
  });
2918
5112
  },
2919
- "GET /profiles": ({ namespace }) => json4(200, { profiles: runtime.instance(namespace).profiles() }),
5113
+ "GET /profiles": ({ namespace }) => json6(200, { profiles: runtime.instance(namespace).profiles() }),
2920
5114
  "GET /profiles/:id": ({ params, namespace }) => {
2921
5115
  const profile = runtime.instance(namespace).state.profile(params.id);
2922
- return profile ? json4(200, profile) : adminError3(404, `no profile ${params.id}`);
5116
+ return profile ? json6(200, profile) : adminError4(404, `no profile ${params.id}`);
2923
5117
  },
2924
5118
  "POST /reporting-events": ({ body, namespace }) => {
2925
- if (!isRecord4(body) || typeof body.metric !== "string") {
2926
- return adminError3(
5119
+ if (!isRecord6(body) || typeof body.metric !== "string") {
5120
+ return adminError4(
2927
5121
  400,
2928
5122
  'expected {"metric": "unsubscribed"|"subscribed"|"spammed"|"cio_subscription_preferences_changed"|\u2026, "userId"?, "email"?, "deliveryId"?, "objectType"?, "preferences"?}'
2929
5123
  );
@@ -2934,20 +5128,20 @@ var adminRoutes = (runtime) => ({
2934
5128
  const value = text(key);
2935
5129
  if (value !== void 0) input[key] = value;
2936
5130
  }
2937
- if (isRecord4(body.preferences))
5131
+ if (isRecord6(body.preferences))
2938
5132
  input.preferences = body.preferences;
2939
5133
  const event = runtime.instance(namespace).report(input);
2940
- return typeof event === "string" ? adminError3(404, event) : json4(201, event);
5134
+ return typeof event === "string" ? adminError4(404, event) : json6(201, event);
2941
5135
  },
2942
- "GET /transactional": ({ namespace }) => json4(200, { messages: runtime.instance(namespace).state.catalog() }),
5136
+ "GET /transactional": ({ namespace }) => json6(200, { messages: runtime.instance(namespace).state.catalog() }),
2943
5137
  "PUT /transactional": ({ body, namespace }) => {
2944
- const list = Array.isArray(body) ? body : isRecord4(body) ? body.messages : void 0;
2945
- if (!Array.isArray(list)) return adminError3(400, "expected [{id, name, trigger_name, \u2026}]");
5138
+ const list = Array.isArray(body) ? body : isRecord6(body) ? body.messages : void 0;
5139
+ if (!Array.isArray(list)) return adminError4(400, "expected [{id, name, trigger_name, \u2026}]");
2946
5140
  const state = runtime.instance(namespace).state;
2947
5141
  for (const row of state.catalog()) state.messages.delete(String(row.id));
2948
5142
  for (const [index, raw] of list.entries()) {
2949
- if (!isRecord4(raw) || typeof raw.trigger_name !== "string") {
2950
- return adminError3(400, `messages[${index}]: trigger_name is required`);
5143
+ if (!isRecord6(raw) || typeof raw.trigger_name !== "string") {
5144
+ return adminError4(400, `messages[${index}]: trigger_name is required`);
2951
5145
  }
2952
5146
  const id = typeof raw.id === "number" ? raw.id : index + 1;
2953
5147
  state.messages.insert(String(id), {
@@ -2964,16 +5158,16 @@ var adminRoutes = (runtime) => ({
2964
5158
  updated_at: 1735689600
2965
5159
  });
2966
5160
  }
2967
- return json4(200, { messages: state.catalog() });
5161
+ return json6(200, { messages: state.catalog() });
2968
5162
  },
2969
- "GET /settings": ({ namespace }) => json4(200, runtime.instance(namespace).state.current()),
5163
+ "GET /settings": ({ namespace }) => json6(200, runtime.instance(namespace).state.current()),
2970
5164
  "PUT /settings": ({ body, namespace }) => {
2971
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
5165
+ if (!isRecord6(body)) return adminError4(400, "expected a JSON object");
2972
5166
  const patch = {};
2973
5167
  if (typeof body.strictMessages === "boolean") patch.strictMessages = body.strictMessages;
2974
5168
  if (typeof body.trackingBase === "string") patch.trackingBase = body.trackingBase;
2975
5169
  if (Array.isArray(body.keys)) patch.keys = body.keys.map(String);
2976
- return json4(200, runtime.instance(namespace).state.update(patch));
5170
+ return json6(200, runtime.instance(namespace).state.update(patch));
2977
5171
  }
2978
5172
  });
2979
5173
  var createRuntime2 = (options = {}) => {
@@ -2992,7 +5186,7 @@ var createRuntime2 = (options = {}) => {
2992
5186
  });
2993
5187
  const runtime = createRuntime({
2994
5188
  name: CUSTOMERIO_NAMESPACE,
2995
- document,
5189
+ document: document2,
2996
5190
  ...options.sqlite ? { sqlite: options.sqlite } : {},
2997
5191
  ...options.clock ? { clock: options.clock } : {},
2998
5192
  ...options.seed !== void 0 ? { seed: options.seed } : {},
@@ -3035,7 +5229,7 @@ var APP_OPERATIONS = /* @__PURE__ */ new Set([
3035
5229
  var clickNotFound = () => new Response("404 page not found", { status: 404, headers: { "content-type": "text/plain" } });
3036
5230
  var cdpError = (status, error) => jsonRes(status, { error });
3037
5231
  var appError = (status, error) => jsonRes(status, { meta: { error } });
3038
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5232
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3039
5233
  var URL_PATTERN = /https?:\/\/[^\s"'<>]+/g;
3040
5234
  var urlsIn = (value, out = []) => {
3041
5235
  if (typeof value === "string") {
@@ -3044,7 +5238,7 @@ var urlsIn = (value, out = []) => {
3044
5238
  }
3045
5239
  } else if (Array.isArray(value)) {
3046
5240
  for (const item of value) urlsIn(item, out);
3047
- } else if (isRecord5(value)) {
5241
+ } else if (isRecord7(value)) {
3048
5242
  for (const item of Object.values(value)) urlsIn(item, out);
3049
5243
  }
3050
5244
  return out;
@@ -3087,7 +5281,7 @@ var CustomerIoAPI = class {
3087
5281
  FollowClick: (context) => this.click(context, "get")
3088
5282
  });
3089
5283
  this.service = createService({
3090
- document,
5284
+ document: document2,
3091
5285
  handlers,
3092
5286
  sqlite,
3093
5287
  namespace,
@@ -3130,7 +5324,7 @@ var CustomerIoAPI = class {
3130
5324
  }
3131
5325
  // ---------------------------------------------------------------- CDP
3132
5326
  cdp(context, kind) {
3133
- if (context.body.kind !== "json" || !isRecord5(context.body.value)) {
5327
+ if (context.body.kind !== "json" || !isRecord7(context.body.value)) {
3134
5328
  return cdpError(400, "Invalid JSON body");
3135
5329
  }
3136
5330
  const issue = bodyIssues(context)[0];
@@ -3163,8 +5357,8 @@ var CustomerIoAPI = class {
3163
5357
  userId: typeof item.userId === "string" ? item.userId : null,
3164
5358
  anonymousId: typeof item.anonymousId === "string" ? item.anonymousId : null,
3165
5359
  event: typeof item.event === "string" ? item.event : null,
3166
- traits: isRecord5(item.traits) ? item.traits : {},
3167
- properties: isRecord5(item.properties) ? item.properties : {},
5360
+ traits: isRecord7(item.traits) ? item.traits : {},
5361
+ properties: isRecord7(item.properties) ? item.properties : {},
3168
5362
  timestamp: typeof item.timestamp === "string" ? item.timestamp : null,
3169
5363
  receivedAt: at,
3170
5364
  duplicate
@@ -3187,7 +5381,7 @@ var CustomerIoAPI = class {
3187
5381
  }
3188
5382
  // ---------------------------------------------------------------- App API sends
3189
5383
  send(context, channel) {
3190
- if (context.body.kind !== "json" || !isRecord5(context.body.value)) {
5384
+ if (context.body.kind !== "json" || !isRecord7(context.body.value)) {
3191
5385
  return appError(400, "invalid JSON body");
3192
5386
  }
3193
5387
  const issue = bodyIssues(context)[0];
@@ -3224,7 +5418,7 @@ var CustomerIoAPI = class {
3224
5418
  }
3225
5419
  const tracked = body.tracked === true || body.tracked === void 0 && !!message?.link_tracking;
3226
5420
  const deliveryId = this.state.deliveryId();
3227
- const messageData = isRecord5(body.message_data) ? body.message_data : {};
5421
+ const messageData = isRecord7(body.message_data) ? body.message_data : {};
3228
5422
  const retain = body.disable_message_retention !== true;
3229
5423
  const links = urlsIn([messageData, body.body ?? ""]).map((url) => {
3230
5424
  if (!tracked) return url;
@@ -3235,7 +5429,7 @@ var CustomerIoAPI = class {
3235
5429
  const sendToUnsubscribed = body.send_to_unsubscribed === true || body.send_to_unsubscribed === void 0 && !!message?.send_to_unsubscribed;
3236
5430
  const channelOff = channel !== "inbox" && !!profile?.channelsOff.includes(channel === "sms" ? "sms" : "email");
3237
5431
  const suppressed = !sendToUnsubscribed && (!!profile?.unsubscribed || channelOff);
3238
- const attachments = Array.isArray(body.attachments) ? body.attachments.map((a) => a.filename) : isRecord5(body.attachments) ? Object.keys(body.attachments) : [];
5432
+ const attachments = Array.isArray(body.attachments) ? body.attachments.map((a) => a.filename) : isRecord7(body.attachments) ? Object.keys(body.attachments) : [];
3239
5433
  const queuedAt = Math.floor(this.now() / 1e3);
3240
5434
  const delivery = {
3241
5435
  id: deliveryId,
@@ -3252,7 +5446,7 @@ var CustomerIoAPI = class {
3252
5446
  tracked,
3253
5447
  sendToUnsubscribed,
3254
5448
  disableMessageRetention: !retain,
3255
- headers: isRecord5(body.headers) ? body.headers : {},
5449
+ headers: isRecord7(body.headers) ? body.headers : {},
3256
5450
  attachments,
3257
5451
  state: suppressed ? "suppressed" : "sent",
3258
5452
  queuedAt,
@@ -3351,7 +5545,7 @@ var CustomerIoAPI = class {
3351
5545
  };
3352
5546
 
3353
5547
  export {
3354
- document,
5548
+ document2 as document,
3355
5549
  operationIds,
3356
5550
  supportedOperationIds,
3357
5551
  DEFAULT_SETTINGS,
@@ -3365,4 +5559,4 @@ export {
3365
5559
  customerIoCredential,
3366
5560
  CustomerIoAPI
3367
5561
  };
3368
- //# sourceMappingURL=chunk-SULJ3UI6.js.map
5562
+ //# sourceMappingURL=chunk-I5K5QTF3.js.map