@brad-frost-web/eddie-render 0.65.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.
@@ -0,0 +1,947 @@
1
+ const C = /* @__PURE__ */ new Set(["component", "children", "slots", "accessibility", "action", "metadata", "catalogId", "id"]), F = "Text";
2
+ function D(i) {
3
+ return String(i).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
4
+ }
5
+ function X(i) {
6
+ return String(i).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
7
+ }
8
+ function L(i, e) {
9
+ if (i && typeof i == "object" && !Array.isArray(i) && "path" in i) {
10
+ const t = String(i.path);
11
+ let n = e;
12
+ for (const o of t.replace(/^\//, "").split("/").filter(Boolean)) {
13
+ if (n === null || typeof n != "object") return;
14
+ n = n[o.replace(/~1/g, "/").replace(/~0/g, "~")];
15
+ }
16
+ return n;
17
+ }
18
+ return i;
19
+ }
20
+ function K(i, e) {
21
+ const t = [];
22
+ for (const [n, o] of Object.entries(i)) {
23
+ if (C.has(n)) continue;
24
+ const r = L(o, e);
25
+ r != null && (typeof r == "string" || typeof r == "number" || typeof r == "boolean") && t.push([n, r]);
26
+ }
27
+ return t;
28
+ }
29
+ function z(i, e, t) {
30
+ const o = (i.metadata.extensions.eddie_expansion ?? `<${i.metadata.extensions.eddie_tag}>{{children}}</${i.metadata.extensions.eddie_tag}>`).replace(/\{\{(?!children\}\})([a-zA-Z_][\w]*)\}\}/g, (a, s) => {
31
+ const c = L(e[s], t);
32
+ return c == null ? "" : D(c);
33
+ }), r = o.indexOf("{{children}}");
34
+ return r === -1 ? { before: o, after: "" } : { before: o.slice(0, r), after: o.slice(r + 12) };
35
+ }
36
+ function Y(i, e) {
37
+ const t = [];
38
+ let n = "";
39
+ const o = /* @__PURE__ */ new Set(), r = (s, c) => {
40
+ const d = i.elements[s];
41
+ if (!(!d || o.has(s))) {
42
+ o.add(s);
43
+ try {
44
+ a(s, d, c);
45
+ } finally {
46
+ o.delete(s);
47
+ }
48
+ }
49
+ }, a = (s, c, d) => {
50
+ const f = e.components[c.component], u = d ? ` slot="${D(d)}"` : "";
51
+ if (t.push({ start: n.length, id: s }), !f) {
52
+ n += `<unknown data-eddie-id="${D(s)}"${u}></unknown>`;
53
+ return;
54
+ }
55
+ const w = f.metadata.extensions;
56
+ if (w.eddie_kind === "text" || c.component === F) {
57
+ const g = typeof c.tagName == "string" ? c.tagName : "", p = X(L(c.text, i.dataModel) ?? "");
58
+ n += g ? `<${g}${u}>${p}</${g}>` : p;
59
+ return;
60
+ }
61
+ const y = () => {
62
+ for (const g of c.children ?? []) r(String(g));
63
+ for (const [g, p] of Object.entries(c.slots ?? {})) {
64
+ const x = w.eddie_slotAttrs?.[g] ?? g;
65
+ for (const k of p) r(String(k), x);
66
+ }
67
+ };
68
+ if (w.eddie_kind === "composition") {
69
+ const { before: g, after: p } = z(f, c, i.dataModel);
70
+ n += d ? g.replace(/^(<[a-zA-Z][^>\s]*)/, `$1${u}`) : g, y(), n += p;
71
+ return;
72
+ }
73
+ const N = K(c, i.dataModel).map(([g, p]) => p === !0 ? ` ${g}` : p === !1 ? "" : ` ${g}="${D(p)}"`).join("");
74
+ n += `<${w.eddie_tag}${N}${u}>`, y(), n += `</${w.eddie_tag}>`;
75
+ };
76
+ return i.root && r(i.root), {
77
+ markup: n,
78
+ idOf: (s) => {
79
+ let c;
80
+ for (const d of t) d.start <= s && (c = d.id);
81
+ return c;
82
+ }
83
+ };
84
+ }
85
+ function U() {
86
+ return { root: null, elements: {}, dataModel: {} };
87
+ }
88
+ function T(i) {
89
+ return JSON.parse(JSON.stringify(i));
90
+ }
91
+ const Q = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
92
+ function B(i) {
93
+ if (i === "" || i === "/") return [];
94
+ if (!i.startsWith("/")) throw new Error(`Invalid JSON Pointer "${i}": must start with "/"`);
95
+ const e = i.slice(1).split("/").map((t) => t.replace(/~1/g, "/").replace(/~0/g, "~"));
96
+ for (const t of e)
97
+ if (Q.has(t)) throw new Error(`Refusing JSON Pointer segment "${t}"`);
98
+ return e;
99
+ }
100
+ function j(i, e) {
101
+ let t = i;
102
+ for (const n of B(e)) {
103
+ if (t === null || typeof t != "object") return;
104
+ t = Array.isArray(t) ? t[Number(n)] : t[n];
105
+ }
106
+ return t;
107
+ }
108
+ function O(i, e, t) {
109
+ const n = B(e);
110
+ if (n.length === 0) throw new Error("Cannot set the document root by pointer");
111
+ let o = i;
112
+ for (let a = 0; a < n.length - 1; a++) {
113
+ const s = n[a];
114
+ let c = Array.isArray(o) ? o[Number(s)] : o[s];
115
+ (c === null || typeof c != "object") && (c = /^\d+$/.test(n[a + 1]) ? [] : {}, Array.isArray(o) ? o[Number(s)] = c : o[s] = c), o = c;
116
+ }
117
+ const r = n[n.length - 1];
118
+ Array.isArray(o) ? t === void 0 ? o.splice(Number(r), 1) : r === "-" ? o.push(t) : o[Number(r)] = t : t === void 0 ? delete o[r] : o[r] = t;
119
+ }
120
+ function J(i, e) {
121
+ const t = i;
122
+ switch (e.op) {
123
+ case "noop":
124
+ return;
125
+ case "add":
126
+ case "replace":
127
+ if (!e.path) throw new Error(`${e.op} needs a path`);
128
+ O(t, e.path, e.value);
129
+ return;
130
+ case "remove":
131
+ if (!e.path) throw new Error("remove needs a path");
132
+ O(t, e.path, void 0);
133
+ return;
134
+ case "move": {
135
+ if (!e.path || !e.from) throw new Error("move needs from and path");
136
+ const n = j(t, e.from);
137
+ O(t, e.from, void 0), O(t, e.path, n);
138
+ return;
139
+ }
140
+ case "copy": {
141
+ if (!e.path || !e.from) throw new Error("copy needs from and path");
142
+ const n = j(t, e.from);
143
+ O(t, e.path, n === void 0 ? void 0 : JSON.parse(JSON.stringify(n)));
144
+ return;
145
+ }
146
+ case "test": {
147
+ if (!e.path) throw new Error("test needs a path");
148
+ if (JSON.stringify(j(t, e.path)) !== JSON.stringify(e.value)) throw new Error(`test failed at ${e.path}`);
149
+ return;
150
+ }
151
+ default:
152
+ throw new Error(`Unknown patch op "${e.op}"`);
153
+ }
154
+ }
155
+ function I(i) {
156
+ const e = i.trim();
157
+ if (!e || !e.startsWith("{")) return null;
158
+ try {
159
+ const t = JSON.parse(e);
160
+ return typeof t == "object" && t && typeof t.op == "string" ? t : null;
161
+ } catch {
162
+ return null;
163
+ }
164
+ }
165
+ function ee(i) {
166
+ const e = I(i);
167
+ if (e) return e;
168
+ let t = i.trim();
169
+ if (!t.startsWith("{")) return null;
170
+ t = t.replace(/,\s*$/, "").replace(/:\s*$/, ": null").replace(/,\s*"[^"]*$/, "");
171
+ let n = !1;
172
+ const o = [];
173
+ for (let r = 0; r < t.length; r++) {
174
+ const a = t[r];
175
+ if (n) {
176
+ a === "\\" ? r++ : a === '"' && (n = !1);
177
+ continue;
178
+ }
179
+ a === '"' ? n = !0 : a === "{" ? o.push("}") : a === "[" ? o.push("]") : (a === "}" || a === "]") && o.pop();
180
+ }
181
+ for (n && (t += '"'); o.length; ) t += o.pop();
182
+ return I(t);
183
+ }
184
+ function ue() {
185
+ let i = "";
186
+ const e = [], t = (n) => {
187
+ const o = I(n);
188
+ return !o && n.trim() && e.push(n), o;
189
+ };
190
+ return {
191
+ dropped: e,
192
+ push(n) {
193
+ i += n;
194
+ const o = [];
195
+ let r;
196
+ for (; (r = i.indexOf(`
197
+ `)) !== -1; ) {
198
+ const a = i.slice(0, r);
199
+ i = i.slice(r + 1);
200
+ const s = t(a);
201
+ s && o.push(s);
202
+ }
203
+ return o;
204
+ },
205
+ end() {
206
+ const n = i;
207
+ if (i = "", !n.trim()) return [];
208
+ const o = I(n) ?? ee(n);
209
+ return o ? [o] : (e.push(n), []);
210
+ }
211
+ };
212
+ }
213
+ function he(i, e) {
214
+ const t = Array.isArray(e) ? e : e.split(`
215
+ `), n = [], o = [];
216
+ for (const r of t) {
217
+ const a = I(r);
218
+ if (a)
219
+ try {
220
+ J(i, a), n.push(a);
221
+ } catch (s) {
222
+ o.push({ op: a, error: s instanceof Error ? s.message : String(s) });
223
+ }
224
+ }
225
+ return { applied: n, failed: o };
226
+ }
227
+ function V(i) {
228
+ const { id: e, component: t, ...n } = i;
229
+ if (typeof t == "string")
230
+ return [e, { component: t, ...n }];
231
+ const [o, r] = Object.entries(t)[0] ?? ["", {}], a = { component: o };
232
+ for (const [s, c] of Object.entries(r ?? {}))
233
+ c && typeof c == "object" && "literalString" in c ? a[s] = c.literalString : c && typeof c == "object" && "explicitList" in c ? a[s] = c.explicitList : a[s] = c;
234
+ return a.child !== void 0 && a.children === void 0 && (a.children = [String(a.child)], delete a.child), [e, a];
235
+ }
236
+ function te(i, e) {
237
+ if (e.createSurface) {
238
+ const n = e.createSurface;
239
+ i.root = null, i.elements = {}, i.dataModel = n.dataModel ? JSON.parse(JSON.stringify(n.dataModel)) : {};
240
+ const o = [];
241
+ for (const a of n.components ?? []) {
242
+ const [s, c] = V(a);
243
+ i.elements[s] = c, o.push(s);
244
+ }
245
+ const r = n.metadata?.extensions ?? {};
246
+ return i.root = n.root ?? (typeof r.eddie_root == "string" ? r.eddie_root : null) ?? (o.includes("root") ? "root" : o[0] ?? null), { kind: "createSurface", surfaceId: n.surfaceId, ids: o };
247
+ }
248
+ if (e.beginRendering) {
249
+ const n = e.beginRendering;
250
+ return i.root === null && Object.keys(i.elements).length === 0 && (i.dataModel = i.dataModel ?? {}), i.root = n.root, { kind: "createSurface", surfaceId: n.surfaceId, ids: [] };
251
+ }
252
+ const t = e.updateComponents ?? e.surfaceUpdate;
253
+ if (t) {
254
+ const n = [];
255
+ for (const o of t.components ?? []) {
256
+ const [r, a] = V(o);
257
+ i.elements[r] = a, n.push(r);
258
+ }
259
+ return i.root === null && n.includes("root") && (i.root = "root"), { kind: "updateComponents", surfaceId: t.surfaceId, ids: n };
260
+ }
261
+ if (e.updateDataModel) {
262
+ const { path: n, value: o, surfaceId: r } = e.updateDataModel;
263
+ return !n || n === "/" || n === "" ? i.dataModel = o && typeof o == "object" ? JSON.parse(JSON.stringify(o)) : {} : O(i.dataModel, n, o === null ? void 0 : o), { kind: "updateDataModel", surfaceId: r, ids: [] };
264
+ }
265
+ if (e.dataModelUpdate) {
266
+ const { path: n, value: o, contents: r, surfaceId: a } = e.dataModelUpdate;
267
+ if (Array.isArray(r))
268
+ for (const s of r) {
269
+ const c = String(s.key), d = s.valueString ?? s.valueNumber ?? s.valueBoolean ?? s.valueMap;
270
+ O(i.dataModel, `${n ?? ""}/${c}`, d);
271
+ }
272
+ else n && O(i.dataModel, n, o);
273
+ return { kind: "updateDataModel", surfaceId: a, ids: [] };
274
+ }
275
+ if (e.deleteSurface)
276
+ return i.root = null, i.elements = {}, i.dataModel = {}, { kind: "deleteSurface", surfaceId: e.deleteSurface.surfaceId, ids: [] };
277
+ throw new Error(`Unrecognised A2UI message: ${Object.keys(e).join(", ") || "empty"}`);
278
+ }
279
+ function H(i) {
280
+ const e = /* @__PURE__ */ new Set(), t = [], n = (o) => {
281
+ if (e.has(o)) return;
282
+ e.add(o);
283
+ const r = i.elements[o];
284
+ if (r) {
285
+ t.push(o);
286
+ for (const a of r.children ?? []) n(a);
287
+ for (const a of Object.values(r.slots ?? {})) for (const s of a) n(s);
288
+ }
289
+ };
290
+ return i.root && n(i.root), t;
291
+ }
292
+ class S extends Error {
293
+ constructor(e, t) {
294
+ super(`Invalid anti-pattern selector "${e}": ${t}`), this.name = "SelectorSyntaxError";
295
+ }
296
+ }
297
+ const W = /^(?:ed-[a-z0-9-]+|h[1-6]|a|p|img|button|span|div|ul|ol|li)$/, G = /^[a-zA-Z][\w-]*$/;
298
+ function ne(i, e) {
299
+ let t = i.trim();
300
+ const n = t.match(/^(\*|[a-z][a-z0-9-]*)/);
301
+ if (!n) throw new S(e, `expected a tag or "*" at "${t}"`);
302
+ const o = n[1];
303
+ if (o !== "*" && !W.test(o))
304
+ throw new S(e, `"${o}" is not an Eddie tag or an allowed native element`);
305
+ t = t.slice(o.length);
306
+ const r = { tag: o, not: [] };
307
+ for (; t.length > 0; ) {
308
+ const a = t.match(/^\[slot=([^\]]*)\]/);
309
+ if (a) {
310
+ const c = a[1].replace(/^["']|["']$/g, "");
311
+ if (!G.test(c)) throw new S(e, `bad slot name "${a[1]}"`);
312
+ if (r.slot) throw new S(e, "a compound may carry one [slot=] clause");
313
+ r.slot = c, t = t.slice(a[0].length);
314
+ continue;
315
+ }
316
+ const s = t.match(/^:not\(([^)]*)\)/);
317
+ if (s) {
318
+ const c = s[1].trim(), d = c.match(/^\[slot=([^\]]*)\]$/);
319
+ if (d) {
320
+ const f = d[1].replace(/^["']|["']$/g, "");
321
+ if (!G.test(f)) throw new S(e, `bad slot name in :not(): "${c}"`);
322
+ r.not.push({ slot: f });
323
+ } else if (W.test(c))
324
+ r.not.push({ tag: c });
325
+ else
326
+ throw new S(e, `:not() accepts one tag or one [slot=name], got "${c}"`);
327
+ t = t.slice(s[0].length);
328
+ continue;
329
+ }
330
+ throw new S(e, `unexpected "${t}"`);
331
+ }
332
+ if (r.tag === "*" && r.not.length === 0 && !r.slot)
333
+ throw new S(e, '"*" alone matches everything; qualify it with [slot=] or :not()');
334
+ return r;
335
+ }
336
+ function oe(i) {
337
+ const e = i.trim().replace(/\s+/g, " ");
338
+ if (!e) throw new S(i, "empty selector");
339
+ const t = e.split(" ").filter(Boolean), n = [], o = [];
340
+ let r = !1, a = !0;
341
+ for (const s of t) {
342
+ if (s === ">") {
343
+ if (a) throw new S(e, '">" needs a compound on both sides');
344
+ r = !0, a = !0;
345
+ continue;
346
+ }
347
+ a ? n.length > 0 && o.push(r ? "child" : "descendant") : o.push("descendant"), n.push(ne(s, e)), r = !1, a = !1;
348
+ }
349
+ if (a) throw new S(e, "selector ends with a combinator");
350
+ if (n.length < 2)
351
+ throw new S(e, "an anti-pattern describes a relationship: it needs a parent and a child");
352
+ return { text: e, compounds: n, combinators: o };
353
+ }
354
+ const re = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]), q = /<!--[\s\S]*?-->|<(\/?)([a-zA-Z][\w:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)(\/?)>/g;
355
+ function se(i) {
356
+ const e = i.match(/\bslot\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i);
357
+ if (e)
358
+ return (e[1] ?? e[2] ?? e[3]).trim();
359
+ }
360
+ function ie(i) {
361
+ const e = [], t = [];
362
+ q.lastIndex = 0;
363
+ let n;
364
+ for (; (n = q.exec(i)) !== null; ) {
365
+ if (n[0].startsWith("<!--")) continue;
366
+ const o = n[1] === "/", r = n[2].toLowerCase(), a = n[3] ?? "", s = n[4] === "/" || re.has(r);
367
+ if (o) {
368
+ for (let u = t.length - 1; u >= 0; u--)
369
+ if (t[u].tag === r) {
370
+ t.length = u;
371
+ break;
372
+ }
373
+ continue;
374
+ }
375
+ const c = { tag: r, index: n.index, children: [] }, d = se(a);
376
+ d !== void 0 && (c.slot = d);
377
+ const f = t[t.length - 1];
378
+ f ? (c.parent = f, f.children.push(c)) : e.push(c), s || t.push(c);
379
+ }
380
+ return e;
381
+ }
382
+ function* Z(i) {
383
+ for (const e of i)
384
+ yield e, yield* Z(e.children);
385
+ }
386
+ function M(i, e) {
387
+ if (i.tag !== "*" && i.tag !== e.tag || i.slot !== void 0 && e.slot !== i.slot) return !1;
388
+ for (const t of i.not)
389
+ if (t.tag !== void 0 && e.tag === t.tag || t.slot !== void 0 && e.slot === t.slot) return !1;
390
+ return !0;
391
+ }
392
+ function ae(i, e) {
393
+ const { compounds: t, combinators: n } = i, o = t.length - 1;
394
+ if (!M(t[o], e)) return !1;
395
+ const r = (a, s) => {
396
+ if (a < 0) return !0;
397
+ if (n[a] === "child")
398
+ return !!s && M(t[a], s) && r(a - 1, s.parent);
399
+ for (let d = s; d; d = d.parent)
400
+ if (M(t[a], d) && r(a - 1, d.parent)) return !0;
401
+ return !1;
402
+ };
403
+ return r(o - 1, e.parent);
404
+ }
405
+ function ce(i, e) {
406
+ if (e.length === 0) return [];
407
+ const t = e.map((o) => ({ pattern: o, selector: oe(o.selector) })), n = [];
408
+ for (const o of Z(ie(i)))
409
+ for (const { pattern: r, selector: a } of t)
410
+ ae(a, o) && n.push({ pattern: r, node: o, index: o.index });
411
+ return n.sort((o, r) => o.index - r.index);
412
+ }
413
+ const le = /^h([1-6])$/;
414
+ function P(i, e, t = {}) {
415
+ const n = [];
416
+ let o;
417
+ try {
418
+ o = typeof i == "string" ? JSON.parse(i) : i;
419
+ } catch (l) {
420
+ return {
421
+ ok: !1,
422
+ issues: [{ code: "VALIDATION_FAILED", severity: "error", message: `Spec is not JSON: ${l instanceof Error ? l.message : String(l)}` }]
423
+ };
424
+ }
425
+ if (!o || typeof o != "object" || typeof o.elements != "object")
426
+ return {
427
+ ok: !1,
428
+ issues: [{ code: "VALIDATION_FAILED", severity: "error", message: "Spec must be an object with `root`, `elements`, and `dataModel`." }]
429
+ };
430
+ const r = t.autoFix ? JSON.parse(JSON.stringify(o)) : o;
431
+ let a = !1;
432
+ const s = (l) => n.push(l), c = (l) => e.components[l];
433
+ r.root ? r.elements[r.root] || s({
434
+ code: "MISSING_ROOT",
435
+ severity: "error",
436
+ id: r.root,
437
+ message: `Root "${r.root}" is not in elements.`,
438
+ fix: "Emit the root element before referring to it."
439
+ }) : s({
440
+ code: "MISSING_ROOT",
441
+ severity: "error",
442
+ message: "The spec has no root element.",
443
+ fix: 'Add {"op":"add","path":"/root","value":"<id>"} naming the page-shape node.'
444
+ });
445
+ for (const [l, h] of Object.entries(r.elements)) {
446
+ if (!h || typeof h != "object" || typeof h.component != "string") {
447
+ s({
448
+ code: "VALIDATION_FAILED",
449
+ severity: "error",
450
+ id: l,
451
+ message: `Element "${l}" has no component name.`,
452
+ path: `/elements/${l}/component`
453
+ });
454
+ continue;
455
+ }
456
+ const b = c(h.component);
457
+ if (!b) {
458
+ s({
459
+ code: "UNKNOWN_COMPONENT",
460
+ severity: "error",
461
+ id: l,
462
+ message: `"${h.component}" is not in the ${e.profile ?? "default"} catalog.`,
463
+ fix: "Use a node from the catalog; the closest names are listed in the index (eddie_get_catalog).",
464
+ path: `/elements/${l}/component`
465
+ });
466
+ continue;
467
+ }
468
+ const $ = b.properties ?? {};
469
+ for (const m of b.required ?? [])
470
+ m === "component" || m === "children" || h[m] === void 0 && s({ code: "VALIDATION_FAILED", severity: "error", id: l, message: `"${h.component}" requires "${m}".`, path: `/elements/${l}/${m}` });
471
+ for (const [m, v] of Object.entries(h)) {
472
+ if (C.has(m)) continue;
473
+ const A = $[m];
474
+ if (!A) {
475
+ s({
476
+ code: "UNKNOWN_PROP",
477
+ severity: "warning",
478
+ id: l,
479
+ message: `"${h.component}" has no prop "${m}"; it will be ignored.`,
480
+ path: `/elements/${l}/${m}`
481
+ }), t.autoFix && (delete r.elements[l][m], a = !0);
482
+ continue;
483
+ }
484
+ if (v && typeof v == "object" && "path" in v) continue;
485
+ if (Array.isArray(A.enum) && !A.enum.includes(v)) {
486
+ s({
487
+ code: "VALIDATION_FAILED",
488
+ severity: "error",
489
+ id: l,
490
+ message: `"${m}" on "${h.component}" must be one of ${A.enum.map(String).join(", ")}; got ${JSON.stringify(v)}.`,
491
+ path: `/elements/${l}/${m}`
492
+ });
493
+ continue;
494
+ }
495
+ const R = A.type;
496
+ R === "string" && typeof v != "string" && s({
497
+ code: "VALIDATION_FAILED",
498
+ severity: "error",
499
+ id: l,
500
+ message: `"${m}" on "${h.component}" must be a string.`,
501
+ path: `/elements/${l}/${m}`
502
+ }), R === "number" && typeof v != "number" && s({
503
+ code: "VALIDATION_FAILED",
504
+ severity: "error",
505
+ id: l,
506
+ message: `"${m}" on "${h.component}" must be a number.`,
507
+ path: `/elements/${l}/${m}`
508
+ }), R === "boolean" && typeof v != "boolean" && s({
509
+ code: "VALIDATION_FAILED",
510
+ severity: "error",
511
+ id: l,
512
+ message: `"${m}" on "${h.component}" must be a boolean.`,
513
+ path: `/elements/${l}/${m}`
514
+ });
515
+ }
516
+ const E = $.slots?.properties ?? {};
517
+ for (const m of Object.keys(h.slots ?? {}))
518
+ E[m] || s({
519
+ code: "UNKNOWN_SLOT",
520
+ severity: "error",
521
+ id: l,
522
+ message: `"${h.component}" has no slot "${m}"; slotted content would be silently dropped.`,
523
+ fix: Object.keys(E).length ? `Use one of: ${Object.keys(E).join(", ")}, or put the content in children.` : "This node has no named slots; put the content in children.",
524
+ path: `/elements/${l}/slots/${m}`
525
+ });
526
+ h.children !== void 0 && !Array.isArray(h.children) && s({
527
+ code: "VALIDATION_FAILED",
528
+ severity: "error",
529
+ id: l,
530
+ message: `"children" on "${l}" must be an array of ids.`,
531
+ path: `/elements/${l}/children`
532
+ });
533
+ }
534
+ const d = /* @__PURE__ */ new Set(), f = /* @__PURE__ */ new Set(), u = (l, h) => {
535
+ if (d.has(l)) {
536
+ s({
537
+ code: "CYCLE",
538
+ severity: "error",
539
+ id: l,
540
+ message: `"${l}" is its own ancestor.`,
541
+ fix: "Remove the child reference that points back up the tree."
542
+ });
543
+ return;
544
+ }
545
+ if (f.has(l)) return;
546
+ const b = r.elements[l];
547
+ if (!b) {
548
+ if (t.streaming) return;
549
+ s({
550
+ code: "DANGLING_CHILD",
551
+ severity: "error",
552
+ id: l,
553
+ message: `"${h}" references "${l}", which does not exist.`,
554
+ fix: `Emit /elements/${l} or drop it from the parent's children.`,
555
+ path: h ? `/elements/${h}/children` : void 0
556
+ });
557
+ return;
558
+ }
559
+ d.add(l);
560
+ const $ = c(b.component), E = h ? r.elements[h] : void 0, m = E ? E.component : "Surface";
561
+ if ($) {
562
+ $.allowedParents && !$.allowedParents.includes(m) && s({
563
+ code: "UNALLOWED_PARENT",
564
+ severity: "error",
565
+ id: l,
566
+ message: `"${b.component}" may only sit under ${$.allowedParents.join(", ")}; it is under "${m}".`,
567
+ fix: $.allowedParents.includes("Surface") ? `Make "${l}" the root, or move it under an allowed parent.` : `Move "${l}" under one of: ${$.allowedParents.join(", ")}.`
568
+ });
569
+ const v = E ? c(E.component) : void 0;
570
+ v?.allowedChildren && !v.allowedChildren.includes(b.component) && s({
571
+ code: "UNALLOWED_CHILD",
572
+ severity: "error",
573
+ id: l,
574
+ message: `"${m}" does not allow "${b.component}" inside it.`,
575
+ fix: `Use one of the nodes "${m}" allows (${v.allowedChildren.slice(0, 8).join(", ")}${v.allowedChildren.length > 8 ? ", …" : ""}), or a different page shape.`,
576
+ path: `/elements/${h}/children`
577
+ });
578
+ }
579
+ for (const v of b.children ?? []) u(String(v), l);
580
+ for (const v of Object.values(b.slots ?? {})) for (const A of v) u(String(A), l);
581
+ d.delete(l), f.add(l);
582
+ };
583
+ r.root && u(r.root, null);
584
+ const w = new Set(H(r));
585
+ for (const l of Object.keys(r.elements))
586
+ w.has(l) || s({ code: "ORPHAN", severity: "warning", id: l, message: `"${l}" is not reachable from the root and will not render.` });
587
+ const y = e.antiPatterns ?? [], N = n.some((l) => l.code === "CYCLE");
588
+ if (y.length && !N && r.root && r.elements[r.root]) {
589
+ const { markup: l, idOf: h } = Y(r, e);
590
+ for (const b of ce(l, y))
591
+ s({
592
+ code: "ANTI_PATTERN",
593
+ severity: b.pattern.severity,
594
+ id: h(b.index),
595
+ message: `${b.pattern.selector}: ${b.pattern.reason}`,
596
+ fix: b.pattern.fix
597
+ });
598
+ }
599
+ const g = [];
600
+ let p = 0;
601
+ for (const l of H(r)) {
602
+ const h = r.elements[l], $ = c(h.component)?.metadata.extensions.eddie_tag, E = typeof h.tagName == "string" ? h.tagName : void 0;
603
+ if ($ === "ed-heading" && E) {
604
+ const v = E.match(le);
605
+ if (v) {
606
+ const A = Number(v[1]);
607
+ A === 1 && p++, g.length && A > g[g.length - 1] + 1 && s({
608
+ code: "A11Y",
609
+ severity: "warning",
610
+ id: l,
611
+ message: `Heading level jumps from h${g[g.length - 1]} to h${A}.`,
612
+ fix: "Step heading levels by one."
613
+ }), g.push(A);
614
+ }
615
+ }
616
+ $ && /^ed-(text|textarea|select|checkbox|radio)-field$/.test($) && !h.label && !h.slots?.label && s({
617
+ code: "A11Y",
618
+ severity: "warning",
619
+ id: l,
620
+ message: `"${h.component}" has no label.`,
621
+ fix: "Set the `label` prop so the field is announced."
622
+ });
623
+ const m = h.text && typeof h.text == "object" && "path" in h.text;
624
+ h.component === F && typeof h.text != "string" && !m && s({
625
+ code: "VALIDATION_FAILED",
626
+ severity: "error",
627
+ id: l,
628
+ message: "Text needs a string `text` (or a `{ path }` binding).",
629
+ path: "/elements//text"
630
+ });
631
+ }
632
+ p > 1 && s({ code: "A11Y", severity: "warning", message: `${p} h1 headings; a page has one.`, fix: "Keep one h1 and demote the rest." });
633
+ const k = { ok: !n.some((l) => l.severity === "error"), issues: n };
634
+ return t.autoFix && a && (k.fixed = r), k;
635
+ }
636
+ function pe(i, e) {
637
+ return i.filter((t) => t.severity === "error").map((t) => ({
638
+ version: "v1.0",
639
+ error: {
640
+ code: t.code === "UNALLOWED_PARENT" || t.code === "UNALLOWED_CHILD" ? t.code : "VALIDATION_FAILED",
641
+ surfaceId: e,
642
+ ...t.path ? { path: t.path } : {},
643
+ message: t.fix ? `${t.message} ${t.fix}` : t.message
644
+ }
645
+ }));
646
+ }
647
+ const de = "data-eddie-pending", _ = "data-eddie-id";
648
+ class fe extends EventTarget {
649
+ element;
650
+ surfaceId;
651
+ ready;
652
+ catalog = null;
653
+ committed = U();
654
+ mounted = /* @__PURE__ */ new Map();
655
+ surfaceRoot = null;
656
+ refusalRegion;
657
+ opts;
658
+ loadedScripts = /* @__PURE__ */ new Set();
659
+ constructor(e, t) {
660
+ super(), this.element = e, this.opts = t, this.surfaceId = t.surfaceId ?? "main", this.refusalRegion = t.refusalRegion ?? this.createRefusalRegion(), this.ready = this.loadCatalog(t.catalog), e.addEventListener("click", (n) => this.onActivate(n));
661
+ }
662
+ /** The committed (rendered, canonical) spec. A copy; mutate through a turn. */
663
+ get spec() {
664
+ return T(this.committed);
665
+ }
666
+ get catalogDocument() {
667
+ return this.catalog;
668
+ }
669
+ /** Validate a spec against this host's catalog without touching the surface. */
670
+ validate(e) {
671
+ return P(e, this.requireCatalog());
672
+ }
673
+ /** Apply messages as one turn: validate strictly, then commit or refuse. */
674
+ apply(e) {
675
+ const t = this.beginTurn();
676
+ return t.message(e), t.end();
677
+ }
678
+ /** Apply SpecStream lines as one turn. */
679
+ applyPatchLines(e) {
680
+ const t = this.beginTurn();
681
+ return t.push(e), t.end();
682
+ }
683
+ /** Clear the surface (a `deleteSurface`). */
684
+ reset() {
685
+ this.committed = U(), this.render(this.committed, { provisional: !1 }), this.clearRefusals();
686
+ }
687
+ beginTurn() {
688
+ const e = this.requireCatalog(), t = T(this.committed);
689
+ let n = !0;
690
+ const o = /* @__PURE__ */ new Set();
691
+ let r = !1;
692
+ const a = () => {
693
+ if (!P(t, e, { streaming: !0 }).issues.some((c) => c.severity === "error" && c.code !== "DANGLING_CHILD" && c.code !== "MISSING_ROOT"))
694
+ for (const c of this.render(t, { provisional: !0 })) o.add(c);
695
+ };
696
+ return {
697
+ working: t,
698
+ push: (s) => {
699
+ if (!n) throw new Error("Turn already ended");
700
+ const c = Array.isArray(s) ? s : s.split(`
701
+ `), d = [];
702
+ for (const f of c) {
703
+ const u = I(f);
704
+ if (u)
705
+ try {
706
+ J(t, u), d.push(u);
707
+ } catch {
708
+ }
709
+ }
710
+ return d.length && a(), d;
711
+ },
712
+ pushOp: (s) => {
713
+ if (!n) throw new Error("Turn already ended");
714
+ J(t, s), a();
715
+ },
716
+ message: (s) => {
717
+ if (!n) throw new Error("Turn already ended");
718
+ for (const c of Array.isArray(s) ? s : [s])
719
+ te(t, c).kind === "deleteSurface" ? r = !0 : r = !1;
720
+ r || a();
721
+ },
722
+ end: () => {
723
+ if (!n) throw new Error("Turn already ended");
724
+ if (n = !1, r)
725
+ return this.reset(), this.dispatchEvent(new CustomEvent("render", { detail: { spec: T(this.committed), issues: [], touched: [] } })), { ok: !0, issues: [], outcome: "committed", touched: [] };
726
+ const s = P(t, e);
727
+ if (s.ok) {
728
+ this.committed = t;
729
+ for (const d of this.render(t, { provisional: !1 })) o.add(d);
730
+ const c = [...o];
731
+ return this.clearRefusals(), this.dispatchEvent(new CustomEvent("render", { detail: { spec: T(t), issues: s.issues, touched: c } })), { ...s, outcome: "committed", touched: c };
732
+ }
733
+ return this.render(this.committed, { provisional: !1 }), this.showRefusals(s.issues), this.dispatchEvent(new CustomEvent("refusal", { detail: { issues: s.issues, surfaceId: this.surfaceId } })), { ...s, outcome: "refused", touched: [] };
734
+ },
735
+ abort: () => {
736
+ n = !1, this.render(this.committed, { provisional: !1 });
737
+ }
738
+ };
739
+ }
740
+ // -------------------------------------------------------------------------
741
+ // Rendering
742
+ // -------------------------------------------------------------------------
743
+ /** Render a spec into the this. Returns the ids whose elements were created or replaced. */
744
+ render(e, { provisional: t }) {
745
+ const n = this.requireCatalog(), o = this.element.ownerDocument, r = [], a = /* @__PURE__ */ new Set();
746
+ this.opts.scripts !== !1 && this.ensureScripts(e, n);
747
+ const s = e.dataModel, c = (f) => {
748
+ const u = L(f, s);
749
+ if (u && typeof u == "object" && !Array.isArray(u) && u.bind === "client") {
750
+ const w = typeof f == "object" && f && "path" in f ? String(f.path) : "";
751
+ return this.opts.bind ? this.opts.bind(w) : void 0;
752
+ }
753
+ return u;
754
+ }, d = (f, u) => {
755
+ a.add(f);
756
+ const w = e.elements[f], y = this.mounted.get(f);
757
+ if (!w) {
758
+ if (y?.kind === "pending") return y.el;
759
+ const x = o.createElement("span");
760
+ return x.setAttribute(de, f), x.hidden = !0, this.mounted.set(f, { el: x, key: "pending", childHost: null, anchor: null, kind: "pending" }), x;
761
+ }
762
+ const N = n.components[w.component], g = this.keyFor(w, c, u);
763
+ let p = y;
764
+ if ((!p || p.key !== g || p.kind === "pending") && (p = this.create(o, f, w, N, c, g), y && y.el.parentNode && y.el.replaceWith(p.el), this.mounted.set(f, p), r.push(f)), p.el instanceof Element && (u ? p.el.setAttribute("slot", u) : p.el.removeAttribute("slot")), p.childHost) {
765
+ const x = [];
766
+ for (const k of w.children ?? []) x.push(d(String(k)));
767
+ for (const [k, l] of Object.entries(w.slots ?? {})) {
768
+ const h = N?.metadata.extensions.eddie_slotAttrs?.[k] ?? k;
769
+ for (const b of l) x.push(d(String(b), h));
770
+ }
771
+ this.syncChildren(p.childHost, p.anchor, x);
772
+ }
773
+ return p.el;
774
+ };
775
+ if (e.root && e.elements[e.root]) {
776
+ const f = d(e.root);
777
+ this.surfaceRoot !== f && (this.surfaceRoot?.parentNode ? this.surfaceRoot.replaceWith(f) : this.element.appendChild(f), this.surfaceRoot = f);
778
+ } else this.surfaceRoot && (this.surfaceRoot.remove(), this.surfaceRoot = null);
779
+ for (const f of [...this.mounted.keys()])
780
+ a.has(f) || (this.mounted.get(f).el.remove(), this.mounted.delete(f));
781
+ return t ? this.element.setAttribute("data-eddie-provisional", "") : this.element.removeAttribute("data-eddie-provisional"), r;
782
+ }
783
+ keyFor(e, t, n) {
784
+ const o = {};
785
+ for (const [r, a] of Object.entries(e))
786
+ r === "children" || r === "slots" || (o[r] = C.has(r) ? a : t(a));
787
+ return JSON.stringify([o, n ?? ""]);
788
+ }
789
+ create(e, t, n, o, r, a) {
790
+ if (!o) {
791
+ const d = e.createElement("span");
792
+ return d.setAttribute(_, t), d.setAttribute("data-eddie-unknown", n.component), d.hidden = !0, { el: d, key: a, childHost: null, anchor: null, kind: "unknown" };
793
+ }
794
+ const s = o.metadata.extensions;
795
+ if (s.eddie_kind === "text" || n.component === F) {
796
+ const d = String(r(n.text) ?? ""), f = typeof n.tagName == "string" ? n.tagName : "";
797
+ if (!f) return { el: e.createTextNode(d), key: a, childHost: null, anchor: null, kind: "text" };
798
+ const u = e.createElement(f);
799
+ return u.textContent = d, u.setAttribute(_, t), { el: u, key: a, childHost: null, anchor: null, kind: "text" };
800
+ }
801
+ if (s.eddie_kind === "composition") {
802
+ const { before: d, after: f } = z(o, n, this.resolvedProps(n, r)), u = e.createElement("template");
803
+ u.innerHTML = `${d}<!--eddie:children-->${f}`;
804
+ const w = u.content;
805
+ let y;
806
+ w.children.length === 1 ? y = w.firstElementChild : (y = e.createElement("div"), y.append(w));
807
+ const N = e.createTreeWalker(
808
+ y,
809
+ 128
810
+ /* NodeFilter.SHOW_COMMENT */
811
+ );
812
+ let g = null;
813
+ for (let p = N.nextNode(); p; p = N.nextNode())
814
+ if (p.nodeValue === "eddie:children") {
815
+ g = p;
816
+ break;
817
+ }
818
+ return y.setAttribute(_, t), this.applyCommon(y, n), { el: y, key: a, childHost: g?.parentElement ?? y, anchor: g, kind: "composition" };
819
+ }
820
+ const c = e.createElement(s.eddie_tag);
821
+ c.setAttribute(_, t);
822
+ for (const [d, f] of K(n, {})) {
823
+ const u = r(f);
824
+ u === !0 ? c.setAttribute(d, "") : u === !1 || u === void 0 || u === null ? c.removeAttribute(d) : c.setAttribute(d, String(u));
825
+ }
826
+ for (const [d, f] of Object.entries(n)) {
827
+ if (C.has(d)) continue;
828
+ const u = r(f);
829
+ u && typeof u == "object" && (c[d] = u);
830
+ }
831
+ return this.applyCommon(c, n), { el: c, key: a, childHost: c, anchor: null, kind: "primitive" };
832
+ }
833
+ resolvedProps(e, t) {
834
+ const n = {};
835
+ for (const [o, r] of Object.entries(e)) C.has(o) || (n[o] = t(r));
836
+ return n;
837
+ }
838
+ applyCommon(e, t) {
839
+ const n = t.accessibility;
840
+ n?.label && e.setAttribute("aria-label", n.label), n?.description && e.setAttribute("aria-description", n.description), n?.live && e.setAttribute("aria-live", n.live), n?.hidden && e.setAttribute("hidden", ""), t.action && e.setAttribute("data-eddie-action", t.action.name);
841
+ }
842
+ /** Put `desired` under `host` (before `anchor` when there is one) in order, removing nothing that is not ours. */
843
+ syncChildren(e, t, n) {
844
+ const o = new Set(n), r = /* @__PURE__ */ new Set();
845
+ for (const s of this.mounted.values()) r.add(s.el);
846
+ for (const s of [...e.childNodes])
847
+ r.has(s) && !o.has(s) && s.remove();
848
+ let a = t ?? null;
849
+ for (let s = n.length - 1; s >= 0; s--) {
850
+ const c = n[s];
851
+ a ? (c.nextSibling !== a || c.parentNode !== e) && e.insertBefore(c, a) : (c.parentNode !== e || c.nextSibling !== null) && e.appendChild(c), a = c;
852
+ }
853
+ }
854
+ // -------------------------------------------------------------------------
855
+ // Refusals, actions, scripts, catalog
856
+ // -------------------------------------------------------------------------
857
+ createRefusalRegion() {
858
+ const t = this.element.ownerDocument.createElement("div");
859
+ return t.setAttribute("data-eddie-refusals", ""), t.setAttribute("aria-live", "polite"), this.element.parentNode?.insertBefore(t, this.element), t;
860
+ }
861
+ showRefusals(e) {
862
+ const t = this.element.ownerDocument, n = e.filter((a) => a.severity === "error"), o = t.createElement("ed-alert");
863
+ o.setAttribute("variant", "error"), o.setAttribute("heading", `Refused ${n.length} change${n.length === 1 ? "" : "s"}`);
864
+ for (const a of n.slice(0, 6)) {
865
+ const s = t.createElement("p");
866
+ s.textContent = `${a.code}${a.id ? ` (${a.id})` : ""}: ${a.message}${a.fix ? ` ${a.fix}` : ""}`, o.appendChild(s);
867
+ }
868
+ this.refusalRegion.appendChild(o);
869
+ const r = this.opts.maxRefusals ?? 3;
870
+ for (; this.refusalRegion.children.length > r; ) this.refusalRegion.firstElementChild?.remove();
871
+ }
872
+ clearRefusals() {
873
+ this.refusalRegion.replaceChildren();
874
+ }
875
+ onActivate(e) {
876
+ const n = e.target?.closest?.("[data-eddie-action]");
877
+ if (!n || !this.element.contains(n)) return;
878
+ const o = n.getAttribute(_), r = o ? this.committed.elements[o] : void 0;
879
+ if (!o || !r?.action) return;
880
+ const a = {
881
+ name: r.action.name,
882
+ surfaceId: this.surfaceId,
883
+ sourceComponentId: o,
884
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
885
+ ...r.action.context ? { context: r.action.context } : {}
886
+ };
887
+ this.dispatchEvent(new CustomEvent("action", { detail: a }));
888
+ }
889
+ ensureScripts(e, t) {
890
+ const n = this.element.ownerDocument;
891
+ for (const o of H(e)) {
892
+ const a = t.components[e.elements[o]?.component ?? ""]?.metadata.extensions.eddie_scriptTag;
893
+ if (a)
894
+ for (const s of a.matchAll(/src="([^"]+)"/g)) {
895
+ const c = s[1];
896
+ if (this.loadedScripts.has(c) || n.querySelector(`script[src="${c}"]`)) continue;
897
+ const d = n.createElement("script");
898
+ d.type = "module", d.src = c, n.head.appendChild(d), this.loadedScripts.add(c);
899
+ }
900
+ }
901
+ }
902
+ async loadCatalog(e) {
903
+ if (typeof e != "string") {
904
+ this.catalog = e;
905
+ return;
906
+ }
907
+ const t = await fetch(e);
908
+ if (!t.ok) throw new Error(`Catalog fetch failed: HTTP ${t.status} for ${e}`);
909
+ this.catalog = await t.json();
910
+ }
911
+ requireCatalog() {
912
+ if (!this.catalog) throw new Error("Catalog not loaded yet — await this.ready first.");
913
+ return this.catalog;
914
+ }
915
+ /** The committed surface as markup (what the validator's anti-pattern pass sees). */
916
+ toMarkup() {
917
+ return Y(this.committed, this.requireCatalog()).markup;
918
+ }
919
+ }
920
+ function me(i, e) {
921
+ return new fe(i, e);
922
+ }
923
+ export {
924
+ C as RESERVED_KEYS,
925
+ fe as SurfaceHost,
926
+ F as TEXT_NODE,
927
+ te as applyMessage,
928
+ he as applyPatchLines,
929
+ J as applyPatchOp,
930
+ T as cloneSpec,
931
+ ue as createSpecStreamCompiler,
932
+ me as createSurfaceHost,
933
+ U as emptySpec,
934
+ z as expand,
935
+ j as getAtPointer,
936
+ ee as healJsonLine,
937
+ V as normaliseWireComponent,
938
+ I as parsePatchLine,
939
+ B as parsePointer,
940
+ H as reachableIds,
941
+ L as resolveValue,
942
+ Y as serializeSpec,
943
+ O as setAtPointer,
944
+ pe as toA2uiErrors,
945
+ P as validateSpec
946
+ };
947
+ //# sourceMappingURL=eddie-render.js.map