@eldrajs/theme-core 0.0.0 → 0.1.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +301 -0
  2. package/LICENSE +21 -0
  3. package/README.md +68 -1
  4. package/dist/bridge-DfNINXLL.js +314 -0
  5. package/dist/bridge.d.ts +2 -0
  6. package/dist/bridge.js +2 -0
  7. package/dist/design-tokens.d.ts +68 -0
  8. package/dist/design-tokens.js +486 -0
  9. package/dist/dynamic-route.d.ts +2 -0
  10. package/dist/dynamic-route.js +3 -0
  11. package/dist/dynamicRoute-CxXY-Y_8.js +126 -0
  12. package/dist/dynamicRoute-pRTBoYT6.d.ts +55 -0
  13. package/dist/i18n.d.ts +107 -0
  14. package/dist/i18n.js +192 -0
  15. package/dist/image-framing.d.ts +2 -0
  16. package/dist/image-framing.js +109 -0
  17. package/dist/imageFraming-BUZ-yqho.d.ts +51 -0
  18. package/dist/index-DxrkKyG4.d.ts +488 -0
  19. package/dist/index.d.ts +407 -0
  20. package/dist/index.js +1136 -0
  21. package/dist/layout-CWq_v6ws.d.ts +244 -0
  22. package/dist/layout.d.ts +2 -0
  23. package/dist/layout.js +930 -0
  24. package/dist/links.d.ts +113 -0
  25. package/dist/links.js +184 -0
  26. package/dist/overlay-Bgi0tIbN.d.ts +201 -0
  27. package/dist/overlay-BvkEOiMB.js +2908 -0
  28. package/dist/overlay.d.ts +2 -0
  29. package/dist/overlay.js +6 -0
  30. package/dist/preview-router.d.ts +2 -0
  31. package/dist/preview-router.js +130 -0
  32. package/dist/reusable.d.ts +66 -0
  33. package/dist/reusable.js +92 -0
  34. package/dist/reusableExpansion-Bqm83nCJ.js +229 -0
  35. package/dist/reusableExpansion-CXvs_ckx.d.ts +42 -0
  36. package/dist/stega.d.ts +17 -0
  37. package/dist/stega.js +69 -0
  38. package/dist/template-layout.d.ts +3 -0
  39. package/dist/template-layout.js +328 -0
  40. package/dist/templateLayout-MjNs0gbF.d.ts +254 -0
  41. package/package.json +89 -2
package/dist/index.js ADDED
@@ -0,0 +1,1136 @@
1
+ import { decodeStega, encodeStega, stripStega } from "./stega.js";
2
+ import { a as parseDynamicRoutePattern, i as matchDynamicRoutePattern, n as buildDynamicRoutePath, o as resolveRoute, r as catalogRouteTarget, s as resolvePagePath, t as MAX_DYNAMIC_ROUTE_PATTERN_BYTES } from "./dynamicRoute-CxXY-Y_8.js";
3
+ import { DEFAULT_IMAGE_FRAMING, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, clampFocal, clampImageFraming, focalBand, framingDrag, framingZoom, imageFramingAttrs, imageFramingStyle, normalizeImageFraming, parseImageFramingValueAttr, unscaledFrameRect } from "./image-framing.js";
4
+ import { a as RICH_TEXT_PAD_ATTR, c as domRangeToPositions, d as restampRichTextPositions, f as richTextMarkNameOf, h as layoutIdentityOf, i as RICH_TEXT_MARK_ELEMENTS, l as resolveDomPoint, m as richTextText, n as createOverlayRuntime, o as computeRichTextPositions, p as richTextNodeSize, r as RICH_TEXT_LEAF_TYPES, s as describeSelectionContext, t as classifyBeforeInput, u as resolveDomPosition } from "./overlay-BvkEOiMB.js";
5
+ import { DEFAULT_LAYOUT_BREAKPOINTS, EDIT_MODE_HIDDEN_OPACITY, LAYOUT_BREAKPOINTS, LayoutValidationError, activeLayoutBreakpoint, createLayoutRenderModel, generateLayoutCss, hiddenLayoutBreakpoints, layoutNodeClass, layoutRenderNodeId, normalizeLayoutDocument, resolveLayoutBreakpoints, resolveLayoutDocument, validateLayoutDocument } from "./layout.js";
6
+ import { PREVIEW_ROUTER_MESSAGE_TYPES, createPreviewMessageRouter } from "./preview-router.js";
7
+ import { r as createProjectionResolver } from "./reusableExpansion-Bqm83nCJ.js";
8
+ import { buildTemplateBlockRenames, createTemplateLayoutRenderModel } from "./template-layout.js";
9
+ import { ReusableComponentSnapshotCache, createReusableLayoutRenderModel } from "./reusable.js";
10
+ import { DesignTokenValidationError, applyDesignTokenOverrides, designTokenRevisionHash, generateDesignTokenCss, generateTailwindThemeCss, normalizeColorSelection, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, resolveColorSelection, resolveDesignTokenCatalog, responsiveValue } from "./design-tokens.js";
11
+ //#region src/blockFields.ts
12
+ let registeredBlockFields = {};
13
+ /**
14
+ * Registers the theme's block field metadata so `isBlockFieldLocalized` can
15
+ * resolve it without importing a virtual module id — the SDK packages are
16
+ * published plain and cannot resolve `virtual:eldra/block-fields` at their
17
+ * own build time the way an app entry bundled by `@eldrajs/vite-plugin-theme`
18
+ * can. The themed app's bootstrap (theme-nuxt's runtime plugin, or an
19
+ * equivalent entry for another adapter) imports `virtual:eldra/block-fields`
20
+ * and calls this once at startup with the resolved map; call it again (e.g.
21
+ * on the plugin's HMR rescan) to replace the registered map.
22
+ */
23
+ function registerBlockFields(fields) {
24
+ registeredBlockFields = fields;
25
+ }
26
+ /**
27
+ * Whether the manifest marks this block field `localized`. A rich-text
28
+ * renderer uses it to default an omitted `locale` to the preview's active
29
+ * content locale — a localized field's draft is keyed per locale, so the
30
+ * marking attributes (and therefore every §18 v3 rich-text report) must carry
31
+ * the locale the render actually used. Returns false for an unknown
32
+ * block/field and outside a themed build.
33
+ *
34
+ * `metadata.toolbar` is deliberately not read here: §18 v3 keeps the toolbar
35
+ * to Studio, which gets the control list from Core's field definitions. The
36
+ * vite plugin still validates the ids at build time.
37
+ */
38
+ function isBlockFieldLocalized(apiId, fieldId) {
39
+ if (apiId === void 0) return false;
40
+ return registeredBlockFields[apiId]?.find((field) => field.fieldId === fieldId)?.localized === true;
41
+ }
42
+ /**
43
+ * Resolves the manifest `type` of a block field from its dot-separated data
44
+ * path, descending into `list` (via `metadata.item`, projected verbatim by
45
+ * `blockFieldsModuleSource`) and `composite` (via `metadata.fields`) field
46
+ * definitions as the path requires. A path segment that is purely digits
47
+ * (`"0"`, `"12"`, ...) is a list array index, not a field id, and is skipped
48
+ * rather than matched — `"items.0.variant"` resolves `variant` inside the
49
+ * `items` list's item definition, the same shape `stegaWalk.ts`'s `walk`
50
+ * produces for a `select` nested inside a `list`'s composite item. Trailing
51
+ * numeric segments past a field of any other type (notably a `multiple`
52
+ * `select`, whose resolved value is an array of `{value,label}` rather than
53
+ * a nested `list` item schema) resolve to that field's own type — repeated
54
+ * selected values, not a nested field. A path that runs out of matching
55
+ * fields, or that tries to descend through non-numeric segments past a field
56
+ * type other than `list`/`composite`, resolves to `undefined` — never a
57
+ * guess.
58
+ */
59
+ function resolveBlockFieldType(fields, segments) {
60
+ const [head, ...rest] = segments;
61
+ if (head === void 0) return void 0;
62
+ const field = fields?.find((f) => f.fieldId === head);
63
+ if (field === void 0) return void 0;
64
+ if (rest.length === 0) return field.type;
65
+ if (field.type === "list") {
66
+ const item = field.metadata?.item;
67
+ if (item === null || typeof item !== "object" || Array.isArray(item)) return void 0;
68
+ const itemDef = item;
69
+ const afterIndex = /^\d+$/.test(rest[0] ?? "") ? rest.slice(1) : rest;
70
+ if (afterIndex.length === 0) return typeof itemDef.type === "string" ? itemDef.type : void 0;
71
+ if (itemDef.type !== "composite") return void 0;
72
+ return resolveBlockFieldType(Array.isArray(itemDef.metadata?.fields) ? itemDef.metadata.fields : void 0, afterIndex);
73
+ }
74
+ if (field.type === "composite") {
75
+ const metaFields = field.metadata?.fields;
76
+ return resolveBlockFieldType(Array.isArray(metaFields) ? metaFields : void 0, rest);
77
+ }
78
+ if (rest.every((segment) => /^\d+$/.test(segment))) return field.type;
79
+ }
80
+ /**
81
+ * Whether the manifest marks the block field at `path` (a top-level field
82
+ * id, or a dot-separated data path reaching into a `list`'s composite item —
83
+ * see `resolveBlockFieldType`) `type: "select"`. `encodeEntryDataStega` and
84
+ * the public/preview read path's `{value,label}` unwrap both use this to
85
+ * recognize a select field's resolved value (a plain string like
86
+ * `"primary"`/`"subtle"`, or `{value,label}` before unwrapping): a
87
+ * `Block.vue` compares that value with `===` against literal option
88
+ * strings, so it must never be stega-encoded, and any two-string-key
89
+ * `{value,label}` object that is *not* a registered select (an ordinary
90
+ * composite field a theme author happens to name `value`/`label`) must
91
+ * never be unwrapped. Returns false for an unknown block/field, a path that
92
+ * does not resolve, and outside a themed build (or for any schema with no
93
+ * registered block fields at all, e.g. a non-block entry such as a page) —
94
+ * absence of a registration is never treated as permission to unwrap or to
95
+ * skip encoding.
96
+ */
97
+ function isBlockFieldSelect(apiId, path) {
98
+ if (apiId === void 0) return false;
99
+ return resolveBlockFieldType(registeredBlockFields[apiId], path.split(".")) === "select";
100
+ }
101
+ /** Ceiling on the *computed* backoff. A `Retry-After` is honoured beyond it. */
102
+ const DEFAULT_RETRY_MAX_DELAY_MS = 5e3;
103
+ /**
104
+ * Ceiling on a honoured `Retry-After`. The header is the gateway's own answer
105
+ * and is followed as given — but a build must not be hostage to one: a limit
106
+ * counted per minute never needs longer than this, and a header that asks for
107
+ * an hour (a misconfiguration, or a proxy in front of the gateway) would
108
+ * otherwise hang a build with nothing said.
109
+ */
110
+ const MAX_RETRY_AFTER_MS = 6e4;
111
+ /** `429` is the rate limit itself; `503` is a gateway that is not up yet. */
112
+ const RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 503]);
113
+ /**
114
+ * Methods that may be repeated. Idempotence is the whole test: a `POST` that
115
+ * timed out may well have been applied, so asking again could duplicate it.
116
+ * Every gateway *read* is one of these.
117
+ */
118
+ const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
119
+ "GET",
120
+ "HEAD",
121
+ "OPTIONS"
122
+ ]);
123
+ /**
124
+ * Transport failures worth repeating. `fetch` reports a dropped connection as a
125
+ * `TypeError` whose `cause` carries the real code, and a raw socket error
126
+ * carries one of these codes directly.
127
+ */
128
+ const RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
129
+ "ECONNRESET",
130
+ "ECONNREFUSED",
131
+ "ETIMEDOUT",
132
+ "EPIPE",
133
+ "EAI_AGAIN",
134
+ "UND_ERR_SOCKET",
135
+ "UND_ERR_CONNECT_TIMEOUT",
136
+ "UND_ERR_HEADERS_TIMEOUT",
137
+ "UND_ERR_BODY_TIMEOUT"
138
+ ]);
139
+ /**
140
+ * What a runtime says when the *network* failed, lower-cased and matched as a
141
+ * prefix. `fetch` raises a bare `TypeError` for two unrelated things — a
142
+ * connection that failed, and a request that was malformed (an unparseable
143
+ * URL, an invalid header name, a `GET` with a body) — and only the first is
144
+ * worth repeating: a malformed request will fail identically every time, so
145
+ * retrying it spends four waits per read, multiplied by a build's route count,
146
+ * on a bug that cannot succeed. The message is the only thing that separates
147
+ * them when no `code` is attached, so these are the known spellings, and a
148
+ * runtime whose wording is not here simply fails on the first attempt the way
149
+ * it did before any of this existed.
150
+ */
151
+ const NETWORK_ERROR_MESSAGES = [
152
+ "fetch failed",
153
+ "failed to fetch",
154
+ "load failed",
155
+ "networkerror when attempting to fetch",
156
+ "network error",
157
+ "error sending request",
158
+ "terminated"
159
+ ];
160
+ /**
161
+ * The policy a client was built with, with every unset or nonsensical value
162
+ * filled in. `attempts` counts the first try, so `1` — and `0`, which is what a
163
+ * consumer writes to mean "do not retry" — is one request and no waiting.
164
+ */
165
+ function resolveRetryPolicy(options) {
166
+ return {
167
+ attempts: positive(options?.attempts, 5, 1),
168
+ baseDelayMs: positive(options?.baseDelayMs, 250, 0),
169
+ maxDelayMs: positive(options?.maxDelayMs, DEFAULT_RETRY_MAX_DELAY_MS, 0)
170
+ };
171
+ }
172
+ function positive(value, fallback, floor) {
173
+ if (value === void 0 || !Number.isFinite(value)) return fallback;
174
+ return Math.max(floor, value);
175
+ }
176
+ function isIdempotentMethod(method) {
177
+ return IDEMPOTENT_METHODS.has((method ?? "GET").toUpperCase());
178
+ }
179
+ function isRetryableStatus(status) {
180
+ return RETRYABLE_STATUS.has(status);
181
+ }
182
+ /** Whether this rejection is the caller's own abort rather than a failure. */
183
+ function isAbortError(cause) {
184
+ return typeof cause === "object" && cause !== null && cause.name === "AbortError";
185
+ }
186
+ function isRetryableFetchError(cause) {
187
+ if (isAbortError(cause)) return false;
188
+ const code = errorCodeOf(cause);
189
+ if (code !== void 0) return RETRYABLE_ERROR_CODES.has(code);
190
+ if (!(cause instanceof TypeError)) return false;
191
+ const message = cause.message.toLowerCase();
192
+ return NETWORK_ERROR_MESSAGES.some((known) => message.startsWith(known));
193
+ }
194
+ /**
195
+ * The error's own `code`, or the one on its `cause` — `fetch` wraps a socket
196
+ * error in a `TypeError` and puts the code one level down.
197
+ */
198
+ function errorCodeOf(cause) {
199
+ const own = cause?.code;
200
+ if (typeof own === "string") return own;
201
+ const inner = cause?.cause?.code;
202
+ return typeof inner === "string" ? inner : void 0;
203
+ }
204
+ /**
205
+ * `Retry-After` as milliseconds to wait, or `null` when the header is absent or
206
+ * is neither a delay in seconds nor an HTTP-date. An HTTP-date already in the
207
+ * past is "now", never a negative wait.
208
+ */
209
+ function parseRetryAfter(value, nowMs) {
210
+ if (value === null || value === void 0) return null;
211
+ const raw = value.trim();
212
+ if (raw === "") return null;
213
+ if (/^\d+(?:\.\d+)?$/.test(raw)) return clampRetryAfter(Number(raw) * 1e3);
214
+ const date = Date.parse(raw);
215
+ if (!Number.isFinite(date)) return null;
216
+ return clampRetryAfter(date - nowMs);
217
+ }
218
+ function clampRetryAfter(ms) {
219
+ return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, ms));
220
+ }
221
+ /**
222
+ * `baseDelayMs × 2^attempt`, capped, with equal jitter: half the window is
223
+ * fixed and half is random, so several builds (or several reads of one build)
224
+ * throttled by the same burst do not all come back in the same millisecond.
225
+ * `attempt` is zero-based — the index of the try that just failed.
226
+ */
227
+ function backoffDelayMs(attempt, policy, random = Math.random) {
228
+ const window = Math.min(policy.baseDelayMs * 2 ** attempt, policy.maxDelayMs);
229
+ return window / 2 + random() * (window / 2);
230
+ }
231
+ /**
232
+ * `fetch`, repeated while the answer is "not now".
233
+ *
234
+ * The caller's `AbortSignal` ends it immediately, during a wait as much as
235
+ * during a request: the rejection is the signal's own reason, so an aborted
236
+ * read is indistinguishable from one `fetch` aborted itself. A response that is
237
+ * going to be retried has its body released first — an unread body keeps the
238
+ * connection open, and a build makes thousands of these.
239
+ */
240
+ async function fetchWithRetry(doFetch, url, init, policy, deps = {}) {
241
+ const random = deps.random ?? Math.random;
242
+ const now = deps.now ?? Date.now;
243
+ const signal = init.signal ?? void 0;
244
+ const mayRetry = policy.attempts > 1 && isIdempotentMethod(init.method);
245
+ for (let attempt = 0;; attempt += 1) {
246
+ const lastAttempt = attempt >= policy.attempts - 1;
247
+ let response;
248
+ try {
249
+ response = await doFetch(url, init);
250
+ } catch (cause) {
251
+ if (!mayRetry || lastAttempt || !isRetryableFetchError(cause)) throw cause;
252
+ await wait(backoffDelayMs(attempt, policy, random), signal);
253
+ continue;
254
+ }
255
+ if (!mayRetry || lastAttempt || !isRetryableStatus(response.status)) return response;
256
+ const retryAfter = parseRetryAfter(headerOf(response, "retry-after"), now());
257
+ releaseBody(response);
258
+ await wait(retryAfter ?? backoffDelayMs(attempt, policy, random), signal);
259
+ }
260
+ }
261
+ function headerOf(response, name) {
262
+ return response.headers?.get?.(name) ?? null;
263
+ }
264
+ function releaseBody(response) {
265
+ try {
266
+ response.body?.cancel?.().catch(() => {});
267
+ } catch {}
268
+ }
269
+ function wait(ms, signal) {
270
+ return new Promise((resolve, reject) => {
271
+ if (signal?.aborted === true) {
272
+ reject(abortReason(signal));
273
+ return;
274
+ }
275
+ let onAbort;
276
+ const timer = setTimeout(() => {
277
+ if (onAbort !== void 0) signal?.removeEventListener("abort", onAbort);
278
+ resolve();
279
+ }, ms);
280
+ if (signal !== void 0) {
281
+ onAbort = () => {
282
+ clearTimeout(timer);
283
+ reject(abortReason(signal));
284
+ };
285
+ signal.addEventListener("abort", onAbort, { once: true });
286
+ }
287
+ });
288
+ }
289
+ function abortReason(signal) {
290
+ const reason = signal.reason;
291
+ if (reason !== void 0) return reason;
292
+ return new DOMException("This operation was aborted", "AbortError");
293
+ }
294
+ //#endregion
295
+ //#region src/stegaWalk.ts
296
+ const LOCALE_KEY = /^[A-Za-z0-9]{1,8}(?:-[A-Za-z0-9]{1,8})*$/;
297
+ /**
298
+ * A resolved `select` field's public-read shape: the CMS gateway replaces
299
+ * the stored plain string with `{ value, label }` so a schema-blind consumer
300
+ * can show a human label.
301
+ * Themes only ever declare `select` fields as their plain value union
302
+ * (generated from `block.json`), so `Block.vue` compares the field directly
303
+ * against those literals — never against this wrapper. Left unprojected in
304
+ * the live-editing draft, a `select`/`variant` field never matches and a
305
+ * block silently keeps its default/no-variant markup while editing.
306
+ *
307
+ * This shape check alone is not enough to unwrap: a theme-authored composite
308
+ * field can legitimately declare two string sub-fields literally named
309
+ * `value`/`label`. `project` below additionally confirms, via
310
+ * `isBlockFieldSelect`, that the *registered* field at the current path
311
+ * really is `type: "select"` before unwrapping.
312
+ */
313
+ function looksLikeSelectValue$1(value) {
314
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
315
+ const record = value;
316
+ return Object.keys(record).length === 2 && typeof record.value === "string" && typeof record.label === "string";
317
+ }
318
+ /**
319
+ * Projects a complete localized CMS draft into the active-locale shape used
320
+ * by theme renderers. The input is never mutated, so Studio can keep sending
321
+ * and persisting the complete document.
322
+ *
323
+ * `apiId` (the entry's own `schemaApiId`, when known) gates the
324
+ * `{value,label}` select unwrap above on `isBlockFieldSelect`, tracking the
325
+ * dot-separated field path as the walk descends (the same convention
326
+ * `encodeEntryDataStega`'s `walk` uses), so it only fires for a field the
327
+ * theme's manifest actually registered as `type: "select"` — including one
328
+ * nested inside a `list`'s composite item, e.g. `"items.0.variant"`. When
329
+ * `apiId` is omitted, or the schema has no registered block fields at all
330
+ * (a non-block entry, such as a page, never appears in the block-fields
331
+ * registry), `isBlockFieldSelect` returns false for every path and nothing
332
+ * is unwrapped — safe by construction, never a guess.
333
+ *
334
+ * Entering a nested resolved entry doc (`{id, data, schemaApiId, ...}` —
335
+ * the shape a page's embedded `blocks[]` array carries, or any other
336
+ * resolved reference field) re-derives `apiId` from that doc's own
337
+ * `schemaApiId` and resets the path, mirroring `encodeEntryDataStega`'s
338
+ * `walkNode`: a page's own schema is never registered as a block, so
339
+ * threading the outer `apiId` straight through would make every nested
340
+ * block's own select fields silently fail to unwrap forever, exactly the
341
+ * "non-block entry" case above — but the nested doc has its own registered
342
+ * fields once its own `schemaApiId` is used.
343
+ */
344
+ function projectEntryDataLocale(data, locale, apiId) {
345
+ const project = (value, path, currentApiId) => {
346
+ if (Array.isArray(value)) return value.map((item, i) => project(item, path === "" ? String(i) : `${path}.${i}`, currentApiId));
347
+ if (typeof value !== "object" || value === null) return value;
348
+ if (looksLikeSelectValue$1(value) && isBlockFieldSelect(currentApiId, path)) return value.value;
349
+ if (looksLikeCatalogReference(value)) return value;
350
+ if (looksLikeEntryDoc$1(value)) {
351
+ const nestedApiId = typeof value.schemaApiId === "string" ? value.schemaApiId : void 0;
352
+ return {
353
+ ...value,
354
+ data: project(value.data, "", nestedApiId)
355
+ };
356
+ }
357
+ const entries = Object.entries(value);
358
+ if (locale !== null && entries.length > 0 && entries.every(([key]) => LOCALE_KEY.test(key)) && Object.prototype.hasOwnProperty.call(value, locale)) return project(value[locale], path, currentApiId);
359
+ return Object.fromEntries(entries.map(([key, child]) => [key, project(child, path === "" ? key : `${path}.${key}`, currentApiId)]));
360
+ };
361
+ return project(data, "", apiId);
362
+ }
363
+ /** A resolved reference embedded by the gateway looks like an entry doc: { id, data: {...} }. */
364
+ function looksLikeEntryDoc$1(v) {
365
+ return typeof v === "object" && v !== null && typeof v.id === "string" && typeof v.data === "object" && v.data !== null && !Array.isArray(v.data);
366
+ }
367
+ /**
368
+ * A catalog reference — a product or a collection a `reference` field points at
369
+ * (`{ id, _type: 'collection', slug, status, productCount, … }`, resolved, or
370
+ * just `{ id, _type }` at depth 0, for an archived collection, and in a
371
+ * page-builder draft overlay). It
372
+ * carries no `data`, so it is never an entry doc, and every field on it is
373
+ * catalog control data a block looks the thing up by — `slug` above all, which
374
+ * a theme block hands straight to the storefront. Encoding it would send that
375
+ * request after a collection nobody has, exactly like an encoded media URL
376
+ * (`looksLikeMediaAsset`) requests an asset nobody has. `translations` is also
377
+ * locale-keyed without being one of the theme's own localized fields, so the
378
+ * locale projection has to leave it whole too.
379
+ */
380
+ function looksLikeCatalogReference(v) {
381
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
382
+ const record = v;
383
+ return typeof record.id === "string" && (record._type === "collection" || record._type === "product") && record.data === void 0;
384
+ }
385
+ /** An unresolved CMS reference keeps its identity fields as transport metadata. */
386
+ function looksLikeEntryReference(v) {
387
+ return typeof v === "object" && v !== null && typeof v.id === "string" && typeof v._type === "string";
388
+ }
389
+ /** Core's ordered compatibility mirror represents references as
390
+ * `{ position, type: 'entry', value: '<uuid>' }`. These transport fields must
391
+ * remain structural so the preview overlay can resolve them after stega. */
392
+ function looksLikePositionedEntryReference(v) {
393
+ return typeof v === "object" && v !== null && Number.isInteger(v.position) && v.type === "entry" && typeof v.value === "string";
394
+ }
395
+ /** Hydrated media is renderer control data. Encoding its URL (or any other
396
+ * asset metadata) changes the requested resource and makes preview images
397
+ * fail even though the original URL is valid. */
398
+ function looksLikeMediaAsset(v) {
399
+ return typeof v === "object" && v !== null && typeof v.assetId === "string" && typeof v.url === "string";
400
+ }
401
+ /** Deep-copies `data`, stega-encoding every string leaf with its dot path.
402
+ * Entering a nested resolved entry doc re-roots entryId and fieldPath.
403
+ *
404
+ * `apiId` (the entry's own `schemaApiId`, when known) is used only to skip
405
+ * encoding a registered `select` field's resolved value (e.g. `variant`,
406
+ * top-level or nested inside a `list`'s composite item — see
407
+ * `isBlockFieldSelect`): that string is never displayed as editable text,
408
+ * only compared with `===` inside a `Block.vue`, and stega's invisible
409
+ * tracking characters make that comparison silently fail forever. Entering
410
+ * a nested resolved entry doc (a page's embedded block) re-derives `apiId`
411
+ * from that doc's own `schemaApiId`, so a block's own select fields are
412
+ * protected the same way whether it is fetched directly or embedded inside
413
+ * a page. */
414
+ function encodeEntryDataStega(entryId, data, locale, apiId) {
415
+ const cloneStructural = (value) => {
416
+ if (Array.isArray(value)) return value.map(cloneStructural);
417
+ if (typeof value !== "object" || value === null) return value;
418
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, cloneStructural(child)]));
419
+ };
420
+ const walkRichTextNode = (value, ownerId, path) => {
421
+ const out = {};
422
+ for (const [key, child] of Object.entries(value)) {
423
+ const childPath = path === "" ? key : `${path}.${key}`;
424
+ if (key === "type" || key === "attrs" || key === "marks") out[key] = cloneStructural(child);
425
+ else if (key === "content" && Array.isArray(child)) out[key] = child.map((nested, index) => {
426
+ const nestedPath = `${childPath}.${index}`;
427
+ return looksLikeRichTextNode(nested) ? walkRichTextNode(nested, ownerId, nestedPath) : walkNode(nested, ownerId, nestedPath);
428
+ });
429
+ else out[key] = walkNode(child, ownerId, childPath);
430
+ }
431
+ return out;
432
+ };
433
+ const walk = (value, ownerId, path) => {
434
+ if (typeof value === "string") {
435
+ if (isBlockFieldSelect(apiId, path)) return value;
436
+ return encodeStega(value, {
437
+ entryId: ownerId,
438
+ fieldPath: path,
439
+ locale
440
+ });
441
+ }
442
+ if (Array.isArray(value)) return value.map((item, i) => walkNode(item, ownerId, path === "" ? String(i) : `${path}.${i}`));
443
+ if (typeof value === "object" && value !== null) {
444
+ const out = {};
445
+ for (const [key, v] of Object.entries(value)) out[key] = walkNode(v, ownerId, path === "" ? key : `${path}.${key}`);
446
+ return out;
447
+ }
448
+ return value;
449
+ };
450
+ const walkNode = (value, ownerId, path) => {
451
+ if (looksLikeRichTextRoot(value)) return walkRichTextNode(value, ownerId, path);
452
+ if (looksLikeMediaAsset(value)) return cloneStructural(value);
453
+ if (looksLikeEntryDoc$1(value)) {
454
+ const nestedApiId = typeof value.schemaApiId === "string" ? value.schemaApiId : void 0;
455
+ return {
456
+ ...value,
457
+ data: encodeEntryDataStega(value.id, value.data, locale, nestedApiId)
458
+ };
459
+ }
460
+ if (looksLikeCatalogReference(value)) return cloneStructural(value);
461
+ if (looksLikeEntryReference(value)) return {
462
+ ...walk(value, ownerId, path),
463
+ id: value.id,
464
+ _type: value._type
465
+ };
466
+ if (looksLikePositionedEntryReference(value)) return cloneStructural(value);
467
+ return walk(value, ownerId, path);
468
+ };
469
+ const result = {};
470
+ for (const [key, v] of Object.entries(data)) result[key] = key === "layout" ? v : walkNode(v, entryId, key);
471
+ return result;
472
+ }
473
+ function looksLikeRichTextRoot(value) {
474
+ return looksLikeRichTextNode(value) && value.type === "doc";
475
+ }
476
+ function looksLikeRichTextNode(value) {
477
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.type === "string";
478
+ }
479
+ //#endregion
480
+ //#region src/clientTypes.ts
481
+ var EldraClientError = class extends Error {
482
+ status;
483
+ path;
484
+ constructor(status, statusText, path) {
485
+ super(`[eldra] gateway request failed: ${status} ${statusText} for ${path}`);
486
+ this.name = "EldraClientError";
487
+ this.status = status;
488
+ this.path = path;
489
+ }
490
+ };
491
+ //#endregion
492
+ //#region src/client.ts
493
+ /**
494
+ * Strips every trailing `/` from a URL (`https://x///` → `https://x`). A regex
495
+ * equivalent (`/\/+$/`) backtracks polynomially on a long run of slashes
496
+ * because the engine re-tries every split of the repeated group before
497
+ * failing to match past the string's end; this walks the string once from
498
+ * the end instead, which is linear regardless of how many slashes it finds.
499
+ */
500
+ function stripTrailingSlashes(value) {
501
+ let end = value.length;
502
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end--;
503
+ return value.slice(0, end);
504
+ }
505
+ function createEldraClient(opts) {
506
+ const gatewayUrl = stripTrailingSlashes(opts.gatewayUrl);
507
+ const doFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
508
+ const retryPolicy = resolveRetryPolicy(opts.retry);
509
+ const stegaEnabled = opts.stega === true;
510
+ const defaultLocale = opts.defaultLocale ?? null;
511
+ let previewToken = null;
512
+ const requestErrorListeners = /* @__PURE__ */ new Set();
513
+ function buildUrl(path, query, extra) {
514
+ const url = new URL(gatewayUrl + path);
515
+ if (query?.locale !== void 0) url.searchParams.set("locale", query.locale);
516
+ if (query?.depth !== void 0) url.searchParams.set("depth", String(query.depth));
517
+ if (query?.page !== void 0) url.searchParams.set("page", String(query.page));
518
+ if (query?.pageSize !== void 0) url.searchParams.set("pageSize", String(query.pageSize));
519
+ if (query?.sort?.length) url.searchParams.set("sort", query.sort.join(","));
520
+ if (query?.fields?.length) url.searchParams.set("fields", query.fields.join(","));
521
+ for (const f of query?.filter ?? []) url.searchParams.append("filter", f);
522
+ for (const [k, v] of Object.entries(extra ?? {})) url.searchParams.set(k, v);
523
+ return url;
524
+ }
525
+ async function request(url, init) {
526
+ const headers = new Headers(init?.headers);
527
+ headers.set("X-Org-Id", opts.orgId);
528
+ if (previewToken !== null) headers.set("X-Preview-Token", previewToken);
529
+ const merged = {
530
+ ...init,
531
+ headers
532
+ };
533
+ if (previewToken !== null) merged.cache = "no-store";
534
+ const tokenAtRequest = previewToken;
535
+ const res = await fetchWithRetry(doFetch, url.toString(), merged, retryPolicy);
536
+ if (!res.ok) {
537
+ const error = new EldraClientError(res.status, res.statusText, url.pathname);
538
+ if (previewToken === tokenAtRequest) notifyRequestError(error);
539
+ throw error;
540
+ }
541
+ return res;
542
+ }
543
+ function notifyRequestError(error) {
544
+ for (const listener of [...requestErrorListeners]) try {
545
+ listener(error);
546
+ } catch {}
547
+ }
548
+ function maybeStega(entry, locale) {
549
+ const apiId = typeof entry.schemaApiId === "string" ? entry.schemaApiId : void 0;
550
+ const projected = {
551
+ ...entry,
552
+ data: projectLocalizedLeaves(entry.data, locale, defaultLocale, apiId)
553
+ };
554
+ if (!stegaEnabled || previewToken === null) return projected;
555
+ return {
556
+ ...projected,
557
+ data: encodeEntryDataStega(entry.id, projected.data, locale, apiId)
558
+ };
559
+ }
560
+ return {
561
+ catalog: {
562
+ async getProduct(productIdOrSlug, query) {
563
+ return await (await request(buildUrl(`/catalog/v1/products/${encodeURIComponent(productIdOrSlug)}`, query))).json();
564
+ },
565
+ async listProducts(query) {
566
+ return toCatalogList(await (await request(buildUrl("/catalog/v1/products/list", query))).json());
567
+ },
568
+ async getCollection(slug, query) {
569
+ return await (await request(buildUrl(`/catalog/v1/collections/${encodeURIComponent(slug)}`, query))).json();
570
+ },
571
+ async listCollections(query) {
572
+ return toCatalogList(await (await request(buildUrl("/catalog/v1/collections", query))).json());
573
+ },
574
+ async listCategories(query) {
575
+ return toCatalogList(await (await request(buildUrl("/catalog/v1/categories", query))).json());
576
+ }
577
+ },
578
+ async getEntries(schemaIdentifier, query) {
579
+ const list = await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry`, query))).json();
580
+ if (list.data !== void 0 && list.data !== null && !Array.isArray(list.data)) throw new TypeError("[eldra] gateway entry list data must be an array");
581
+ return {
582
+ ...list,
583
+ data: (list.data ?? []).map((e) => maybeStega(e, query?.locale ?? null))
584
+ };
585
+ },
586
+ async getEntry(schemaIdentifier, entryId, query) {
587
+ return maybeStega(await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/${encodeURIComponent(entryId)}`, query))).json(), query?.locale ?? null);
588
+ },
589
+ async getEntryByUniqueField(schemaIdentifier, fieldId, value, query) {
590
+ return maybeStega(await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/unique/${encodeURIComponent(fieldId)}/${encodeURIComponent(value)}`, query))).json(), query?.locale ?? null);
591
+ },
592
+ async resolveEntryListField(entryId, fieldId, query) {
593
+ return await (await request(buildUrl(`/cms/v1/entry/${encodeURIComponent(entryId)}/list/${encodeURIComponent(fieldId)}`, query))).json();
594
+ },
595
+ async resolveEntryList(body, query) {
596
+ return await (await request(buildUrl("/cms/v1/entry-list/resolve", query), {
597
+ method: "POST",
598
+ headers: { "content-type": "application/json" },
599
+ body: JSON.stringify(body)
600
+ })).json();
601
+ },
602
+ async getTypeScriptDefinitions(tsOpts) {
603
+ const url = new URL(`${gatewayUrl}/cms/v1/typescript-definitions`);
604
+ if (tsOpts?.schemas?.length) url.searchParams.set("schemas", tsOpts.schemas.join(","));
605
+ if (tsOpts?.maxDepth !== void 0) url.searchParams.set("maxDepth", String(tsOpts.maxDepth));
606
+ if (tsOpts?.moduleName !== void 0) url.searchParams.set("moduleName", tsOpts.moduleName);
607
+ return await (await request(url)).text();
608
+ },
609
+ enablePreview(token) {
610
+ previewToken = token;
611
+ },
612
+ disablePreview() {
613
+ previewToken = null;
614
+ },
615
+ get previewEnabled() {
616
+ return previewToken !== null;
617
+ },
618
+ onRequestError(listener) {
619
+ requestErrorListeners.add(listener);
620
+ return () => {
621
+ requestErrorListeners.delete(listener);
622
+ };
623
+ },
624
+ encodeEntryDataStega
625
+ };
626
+ }
627
+ /**
628
+ * Normalise a catalog list response. The gateway serialises an empty page as
629
+ * `"data": null`, and a caller that pages through the list must not have to
630
+ * guess whether a missing `meta` means "one page" or "keep asking" — an absent
631
+ * meta is reported as a single, final page.
632
+ *
633
+ * **A bare array is a list too.** `GET /catalog/v1/categories` answers the whole
634
+ * tree as a top-level array rather than a `{data, meta}` page — the categories
635
+ * are a handful of rows and the endpoint takes no paging — and reading that as
636
+ * "an object with no `data`" made every category read answer *nothing*: no
637
+ * category target for a `link` field to resolve, and no category route for a
638
+ * build to generate, with no error anywhere to say so. The two paged endpoints
639
+ * are unaffected: they answer an object, and an object still has to carry an
640
+ * array under `data` or this throws.
641
+ */
642
+ function toCatalogList(value) {
643
+ if (Array.isArray(value)) return toCatalogList({ data: value });
644
+ const raw = value ?? {};
645
+ if (raw.data !== void 0 && raw.data !== null && !Array.isArray(raw.data)) throw new TypeError("[eldra] gateway catalog list data must be an array");
646
+ const data = raw.data ?? [];
647
+ return {
648
+ data,
649
+ meta: raw.meta ?? {
650
+ hasNext: false,
651
+ hasPrev: false,
652
+ page: 1,
653
+ pageSize: data.length,
654
+ rows: data.length,
655
+ total: data.length,
656
+ totalPages: 1
657
+ }
658
+ };
659
+ }
660
+ const localeKey = /^[a-z]{2}(?:-[A-Za-z0-9]{2,8})*$/;
661
+ /**
662
+ * A resolved `select` field's public-read shape: the CMS gateway replaces
663
+ * the stored plain string with `{ value, label }` so a schema-blind consumer
664
+ * can show a human label.
665
+ * Themes only ever declare `select` fields as their plain value union
666
+ * (`variant?: 'primary' | 'subtle' | 'split'`, generated from `block.json`),
667
+ * so every `Block.vue` compares `data.variant` against those literals
668
+ * directly — never against this wrapper. Left unprojected, every variant
669
+ * (and any other select-typed) field always fails that comparison and a
670
+ * block silently renders its default/no-variant markup forever, in preview
671
+ * and in production alike.
672
+ *
673
+ * This shape check alone is not enough to unwrap: a theme-authored composite
674
+ * field can legitimately declare two string sub-fields literally named
675
+ * `value`/`label` (a stat/metric field, a generic chip). Every call site
676
+ * must additionally confirm, via `isBlockFieldSelect`, that the *registered*
677
+ * field at this path really is `type: "select"` before unwrapping.
678
+ */
679
+ function looksLikeSelectValue(value) {
680
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
681
+ const record = value;
682
+ return Object.keys(record).length === 2 && typeof record.value === "string" && typeof record.label === "string";
683
+ }
684
+ /**
685
+ * Public CMS reads normally resolve localized fields server-side. Older content
686
+ * can still contain locale maps below list/composite fields because those
687
+ * leaves were persisted before recursive localization extraction existed.
688
+ * Project only objects whose every key is a locale tag, leaving ordinary
689
+ * records (including media and references) untouched.
690
+ *
691
+ * `apiId` (the entry's own `schemaApiId`, when known) and `path` (the
692
+ * dot-separated field path built as this walk descends, matching
693
+ * `stegaWalk.ts`'s path convention) gate the `{value,label}` select unwrap
694
+ * above on `isBlockFieldSelect`, so it only ever fires for a field the
695
+ * theme's manifest actually registered as `type: "select"` — including one
696
+ * nested inside a `list`'s composite item, e.g. `"items.0.variant"`. When
697
+ * `apiId` is undefined, or the schema has no registered block fields at all
698
+ * (a non-block entry, such as a page, never appears in the block-fields
699
+ * registry), `isBlockFieldSelect` returns false for every path and nothing
700
+ * is unwrapped — safe by construction, never a guess.
701
+ *
702
+ * Entering a nested resolved entry doc (`{id, data, schemaApiId, ...}` — the
703
+ * shape a page's embedded `blocks[]` array carries, or any other resolved
704
+ * reference field) re-derives `apiId` from that doc's own `schemaApiId` and
705
+ * resets `path`, mirroring `stegaWalk.ts`'s `encodeEntryDataStega`. Without
706
+ * this, every `getEntry`/`getEntries` call that embeds referenced entries
707
+ * (a page fetched with `depth` > 0, most visibly) threads the *outer*
708
+ * entry's `apiId` — a page's own schema is never a registered block — into
709
+ * every nested block, so none of their `select` fields ever unwrap: exactly
710
+ * the "non-block entry" case above, but for every block a page renders.
711
+ */
712
+ function looksLikeEntryDoc(v) {
713
+ return typeof v === "object" && v !== null && typeof v.id === "string" && typeof v.data === "object" && v.data !== null && !Array.isArray(v.data);
714
+ }
715
+ /**
716
+ * Whether a localized field's value counts as "translated", mirroring the
717
+ * gateway's own server-side rule for a localization row
718
+ * (`entry_read.go`'s `isTranslatedValue`): present and not null, not an empty
719
+ * string after trimming whitespace, not an empty array or object, and a
720
+ * rich-text document only when it carries actual text content. Every other
721
+ * value (including `0`/`false`) counts as translated.
722
+ *
723
+ * Exported so the per-field link fallback below (and a theme, if it ever
724
+ * needs the same call) has one definition of "untranslated" rather than a
725
+ * second copy that can drift from it.
726
+ */
727
+ function isTranslatedValue(value) {
728
+ if (value === null || value === void 0) return false;
729
+ if (typeof value === "string") return value.trim() !== "";
730
+ if (Array.isArray(value)) return value.length > 0;
731
+ if (typeof value === "object") {
732
+ const record = value;
733
+ if (Object.keys(record).length === 0) return false;
734
+ if (record.type === "doc") return richTextDocHasText(record);
735
+ return true;
736
+ }
737
+ return true;
738
+ }
739
+ /** Whether a TipTap-shaped rich-text node carries any non-whitespace text in
740
+ * one of its `text` leaves. Used only to decide whether a whole rich-text
741
+ * document counts as "translated" — never a renderer. */
742
+ function richTextDocHasText(node) {
743
+ if (node === null || typeof node !== "object") return false;
744
+ const { type, text, content } = node;
745
+ if (type === "text") return typeof text === "string" && text.trim() !== "";
746
+ if (!Array.isArray(content)) return false;
747
+ return content.some(richTextDocHasText);
748
+ }
749
+ function isPlainRecord(value) {
750
+ return value !== null && typeof value === "object" && !Array.isArray(value);
751
+ }
752
+ /**
753
+ * Per-field fallback for one locale's chosen node against the default
754
+ * locale's node, for the record-shaped sub-fields of a `link` field (and any
755
+ * other locale-keyed composite). Composite records (not a rich-text
756
+ * document) are merged **per field**: a key `chosen` leaves untranslated is
757
+ * copied from `defaultValue`, and every other key of `chosen` (including one
758
+ * `defaultValue` does not have) is kept. A leaf value — a string, an array,
759
+ * a rich-text document — is replaced only as a whole when `chosen` itself is
760
+ * untranslated.
761
+ *
762
+ * `children` needs no special case: an untranslated (missing/empty) array
763
+ * already falls back to the default's whole array under the same per-field
764
+ * rule, and a translated one is kept outright — never merged by index.
765
+ */
766
+ function mergeLocalizedFallback(chosen, defaultValue) {
767
+ const isComposite = (value) => isPlainRecord(value) && value.type !== "doc";
768
+ if (isComposite(chosen) && isComposite(defaultValue)) {
769
+ const merged = { ...chosen };
770
+ for (const key of Object.keys(defaultValue)) merged[key] = isTranslatedValue(merged[key]) ? mergeLocalizedFallback(merged[key], defaultValue[key]) : defaultValue[key];
771
+ return merged;
772
+ }
773
+ if (Array.isArray(chosen) && Array.isArray(defaultValue)) {
774
+ if (chosen.length === 0) return defaultValue;
775
+ if (chosen.length !== defaultValue.length) return chosen;
776
+ return chosen.map((item, i) => mergeLocalizedFallback(item, defaultValue[i]));
777
+ }
778
+ return isTranslatedValue(chosen) ? chosen : defaultValue;
779
+ }
780
+ function projectLocalizedValue(value, locale, defaultLocale, apiId, path) {
781
+ if (Array.isArray(value)) return value.map((item, i) => projectLocalizedValue(item, locale, defaultLocale, apiId, path === "" ? String(i) : `${path}.${i}`));
782
+ if (value === null || typeof value !== "object") return value;
783
+ if (looksLikeSelectValue(value) && isBlockFieldSelect(apiId, path)) return value.value;
784
+ if (looksLikeEntryDoc(value)) {
785
+ const nestedApiId = typeof value.schemaApiId === "string" ? value.schemaApiId : void 0;
786
+ return {
787
+ ...value,
788
+ data: projectLocalizedValue(value.data, locale, defaultLocale, nestedApiId, "")
789
+ };
790
+ }
791
+ const record = value;
792
+ const keys = Object.keys(record);
793
+ if (keys.length > 0 && keys.every((key) => localeKey.test(key))) {
794
+ const exactKey = locale && record[locale] !== void 0 ? locale : void 0;
795
+ const language = locale?.split("-")[0]?.toLowerCase();
796
+ const languageKey = language ? keys.find((key) => key.split("-")[0]?.toLowerCase() === language) : void 0;
797
+ const chosenKey = exactKey ?? languageKey ?? keys[0];
798
+ const chosen = record[chosenKey];
799
+ const defaultValue = defaultLocale != null && chosenKey !== defaultLocale ? record[defaultLocale] : void 0;
800
+ return projectLocalizedValue(defaultValue !== void 0 ? mergeLocalizedFallback(chosen, defaultValue) : chosen, locale, defaultLocale, apiId, path);
801
+ }
802
+ return Object.fromEntries(Object.entries(record).map(([key, item]) => [key, projectLocalizedValue(item, locale, defaultLocale, apiId, path === "" ? key : `${path}.${key}`)]));
803
+ }
804
+ function projectLocalizedLeaves(data, locale, defaultLocale, apiId) {
805
+ return projectLocalizedValue(data, locale, defaultLocale, apiId, "");
806
+ }
807
+ //#endregion
808
+ //#region src/richText.ts
809
+ /**
810
+ * Ordered ids of every rich-text toolbar control a `block.json` may request
811
+ * in `metadata.toolbar`. §18 v3: the theme no longer renders a toolbar —
812
+ * Studio's overlay editor does — but the list stays here as the single
813
+ * source of truth for the vite-plugin-theme scanner's build-time
814
+ * `metadata.toolbar` validation and theme-vue's block field lookup, so Theme
815
+ * Kit never carries two copies of it.
816
+ *
817
+ * Must stay in sync with the `metadata.toolbar` control ids Core's
818
+ * `richtext.go` validator accepts; a theme whose manifest names an id Core
819
+ * rejects fails ingest.
820
+ */
821
+ const RICH_TEXT_TOOLBAR_CONTROLS = [
822
+ "heading",
823
+ "bold",
824
+ "italic",
825
+ "strike",
826
+ "underline",
827
+ "link",
828
+ "bulletList",
829
+ "orderedList",
830
+ "blockquote",
831
+ "code",
832
+ "codeBlock",
833
+ "hardBreak",
834
+ "horizontalRule",
835
+ "image",
836
+ "embed",
837
+ "highlight",
838
+ "textColor",
839
+ "undo",
840
+ "redo",
841
+ "table"
842
+ ];
843
+ /**
844
+ * Allow ordinary site links while rejecting executable and opaque URL
845
+ * schemes. Framework-neutral so both the theme-vue rich-text renderer and
846
+ * hand-rolled theme code can share one link/asset-src allowlist. Values are
847
+ * stega-stripped before validation since a themed link target can carry the
848
+ * click-tracking payload from `encodeStega`.
849
+ */
850
+ function safeHref(value) {
851
+ if (typeof value !== "string") return null;
852
+ const href = stripStega(value).trim();
853
+ if (href.length === 0 || href.length > 2048 || href.includes("\\") || Array.from(href).some((character) => {
854
+ const codePoint = character.codePointAt(0) ?? 0;
855
+ return codePoint <= 31 || codePoint === 127;
856
+ })) return null;
857
+ if (href.startsWith("/")) return href.startsWith("//") ? null : href;
858
+ if (href.startsWith("#")) return href;
859
+ try {
860
+ const protocol = new URL(href).protocol;
861
+ return [
862
+ "https:",
863
+ "http:",
864
+ "mailto:",
865
+ "tel:"
866
+ ].includes(protocol) ? href : null;
867
+ } catch {
868
+ return null;
869
+ }
870
+ }
871
+ //#endregion
872
+ //#region src/richTextTree.ts
873
+ /**
874
+ * Framework-neutral read renderer for a §18 rich-text field's TipTap JSON
875
+ * document. Produces a plain element tree; each framework binding maps that
876
+ * tree onto its own vnode factory (`@eldrajs/theme-vue`'s `renderRichTextDoc`
877
+ * is ~20 lines of `h()`), so the node/mark rules, the URL gating and the
878
+ * attribute whitelist exist exactly once for every adapter.
879
+ *
880
+ * Read mode only — the theme renders rich text, Studio owns the document and
881
+ * the one headless editor that writes it.
882
+ *
883
+ * §18 v3: every **node** element carries `data-eldra-node="<type>"` and
884
+ * `data-eldra-pos="<open position>"` (see `richTextPositions.ts`), so the
885
+ * overlay can map a DOM selection to a ProseMirror document position without
886
+ * a schema. **Mark** elements (`strong`, `em`, `s`, `u`, `code`, `mark`,
887
+ * `span[style]`, `a`) carry no stamps, and neither do the wrappers that are
888
+ * not nodes: a `codeBlock` stamps its `pre`, not the `code` inside it, and a
889
+ * `table` stamps the `table`, not the `tbody`. The stamps are computed from
890
+ * the document, not from the tree, so a node the sanitiser drops (an unsafe
891
+ * image `src`) still consumes its position and everything after it stays
892
+ * numbered as the document numbers it.
893
+ */
894
+ const HEX_COLOR = /^#[0-9a-fA-F]{3,8}$/;
895
+ const NAMED_COLOR = /^[a-zA-Z]+$/;
896
+ /**
897
+ * Build a TipTap JSON document's content as a render tree. Non-doc input
898
+ * builds an empty tree.
899
+ *
900
+ * Every top-level child is an element: a well-formed document only holds
901
+ * block nodes there, and a malformed one (a text node, or an unknown node
902
+ * wrapping text, directly under `doc`) gets its bare text wrapped in a
903
+ * `span` rather than dropped — so the content survives and a mapper never
904
+ * has to place a text node next to the field root's element children.
905
+ */
906
+ function buildRichTextTree(doc, options) {
907
+ return buildChildren((isDocNode(doc) ? doc : {
908
+ type: "doc",
909
+ content: []
910
+ }).content, options, { pos: 0 }).map((child) => typeof child === "string" ? {
911
+ tag: "span",
912
+ attrs: {},
913
+ children: [child]
914
+ } : child);
915
+ }
916
+ function isDocNode(value) {
917
+ return typeof value === "object" && value !== null && !Array.isArray(value) && value.type === "doc";
918
+ }
919
+ function isNode(value) {
920
+ return typeof value === "object" && value !== null && !Array.isArray(value);
921
+ }
922
+ /** The concatenated, stega-stripped text of every direct text-leaf child of
923
+ * `content` — what `padEmptyBlocks` (see `buildNode`) treats as a
924
+ * textblock's "text". A non-text child (hardBreak, image, embed) contributes
925
+ * no characters. */
926
+ function textContentOf(content) {
927
+ if (!Array.isArray(content)) return "";
928
+ let text = "";
929
+ for (const child of content) if (isNode(child) && child.type === "text") text += richTextText(child);
930
+ return text;
931
+ }
932
+ function buildChildren(nodes, options, cursor) {
933
+ if (!Array.isArray(nodes)) return [];
934
+ const out = [];
935
+ for (const node of nodes) {
936
+ if (!isNode(node)) continue;
937
+ const pos = cursor.pos;
938
+ out.push(...buildNode(node, options, cursor, pos));
939
+ cursor.pos = pos + richTextNodeSize(node);
940
+ }
941
+ return out;
942
+ }
943
+ /** Returns 0..n children: a dropped node (unsafe src, textless text node)
944
+ * contributes nothing, and an unknown node splices its own children in. */
945
+ function buildNode(node, options, cursor, pos) {
946
+ if (node.type === "text") {
947
+ if (typeof node.text !== "string") return [];
948
+ return [applyMarks(richTextText(node), node.marks ?? [], options)];
949
+ }
950
+ cursor.pos = pos + 1;
951
+ const children = () => buildChildren(node.content, options, cursor);
952
+ const stamp = (attrs) => typeof node.type === "string" && node.type !== "" ? {
953
+ ...attrs,
954
+ "data-eldra-node": node.type,
955
+ "data-eldra-pos": String(pos)
956
+ } : attrs;
957
+ const element = (tag, attrs = {}) => [{
958
+ tag,
959
+ attrs: stamp(attrs),
960
+ children: children()
961
+ }];
962
+ const isBlank = /^\s*$/.test(textContentOf(node.content));
963
+ const endsWithHardBreak = (kids) => {
964
+ const last = kids[kids.length - 1];
965
+ return typeof last === "object" && last.tag === "br" && last.attrs["data-eldra-node"] === "hardBreak";
966
+ };
967
+ const padIfEmpty = (kids) => options.padEmptyBlocks === true && (isBlank || endsWithHardBreak(kids)) ? [...kids, {
968
+ tag: "br",
969
+ attrs: { [RICH_TEXT_PAD_ATTR]: "" },
970
+ children: []
971
+ }] : kids;
972
+ const textblockElement = (tag, attrs = {}) => [{
973
+ tag,
974
+ attrs: stamp(attrs),
975
+ children: padIfEmpty(children())
976
+ }];
977
+ switch (node.type) {
978
+ case "paragraph": return textblockElement("p");
979
+ case "heading": return textblockElement(`h${clampHeadingLevel(node.attrs?.level, options.minHeadingLevel)}`);
980
+ case "bulletList": return element("ul");
981
+ case "orderedList": return element("ol");
982
+ case "listItem": return element("li");
983
+ case "blockquote": return element("blockquote");
984
+ case "horizontalRule": return [{
985
+ tag: "hr",
986
+ attrs: stamp({}),
987
+ children: []
988
+ }];
989
+ case "hardBreak": return [{
990
+ tag: "br",
991
+ attrs: stamp({}),
992
+ children: []
993
+ }];
994
+ case "codeBlock": return buildCodeBlock(node, stamp({}), padIfEmpty(children()));
995
+ case "table": return [{
996
+ tag: "table",
997
+ attrs: stamp({}),
998
+ children: [{
999
+ tag: "tbody",
1000
+ attrs: {},
1001
+ children: children()
1002
+ }]
1003
+ }];
1004
+ case "tableRow": return element("tr");
1005
+ case "tableHeader": return element("th", tableCellAttrs(node));
1006
+ case "tableCell": return element("td", tableCellAttrs(node));
1007
+ case "image": return buildImage(node, options, stamp);
1008
+ case "embed": return buildEmbed(node, options, stamp);
1009
+ case "doc": return element("span");
1010
+ default: return element("span");
1011
+ }
1012
+ }
1013
+ function buildCodeBlock(node, attrs, children) {
1014
+ const language = typeof node.attrs?.language === "string" ? node.attrs.language : null;
1015
+ return [{
1016
+ tag: "pre",
1017
+ attrs,
1018
+ children: [{
1019
+ tag: "code",
1020
+ attrs: language !== null ? { class: `language-${language}` } : {},
1021
+ children
1022
+ }]
1023
+ }];
1024
+ }
1025
+ function tableCellAttrs(node) {
1026
+ const attrs = {};
1027
+ if (typeof node.attrs?.colspan === "number") attrs.colspan = String(node.attrs.colspan);
1028
+ if (typeof node.attrs?.rowspan === "number") attrs.rowspan = String(node.attrs.rowspan);
1029
+ return attrs;
1030
+ }
1031
+ function buildImage(node, options, stamp) {
1032
+ const src = options.safeHref(node.attrs?.src);
1033
+ if (src === null) return [];
1034
+ const attrs = { src };
1035
+ if (typeof node.attrs?.alt === "string") attrs.alt = node.attrs.alt;
1036
+ if (typeof node.attrs?.title === "string") attrs.title = node.attrs.title;
1037
+ if (typeof node.attrs?.assetId === "string") attrs["data-asset-id"] = node.attrs.assetId;
1038
+ return [{
1039
+ tag: "img",
1040
+ attrs: stamp(attrs),
1041
+ children: []
1042
+ }];
1043
+ }
1044
+ /** No iframe in read mode: an inert div carrying the safe source and provider/title metadata. */
1045
+ function buildEmbed(node, options, stamp) {
1046
+ const src = options.safeHref(node.attrs?.src);
1047
+ if (src === null) return [];
1048
+ const attrs = {
1049
+ class: "eldra-embed",
1050
+ "data-src": src
1051
+ };
1052
+ if (typeof node.attrs?.provider === "string") attrs["data-provider"] = node.attrs.provider;
1053
+ if (typeof node.attrs?.title === "string") attrs.title = node.attrs.title;
1054
+ return [{
1055
+ tag: "div",
1056
+ attrs: stamp(attrs),
1057
+ children: []
1058
+ }];
1059
+ }
1060
+ /**
1061
+ * A heading node's level as a real `h1`-`h6` number, with `minHeadingLevel`
1062
+ * (see `BuildRichTextTreeOptions`) applied as a floor.
1063
+ *
1064
+ * Both arguments are `unknown`-ish input: `value` comes from a document's own
1065
+ * `attrs`, and the floor from a caller's prop, so neither may be trusted to be
1066
+ * an integer in range. Each is normalised on its own before `Math.max` sees
1067
+ * them — a `minHeadingLevel` of `2.5`, `0`, `9` or `'3'` must never turn into
1068
+ * an `<h2.5>`/`<h0>`/`<h9>` — and the result is capped at 6 last, so a floor of
1069
+ * 6 against a level of 6 still reads `h6` rather than overflowing.
1070
+ */
1071
+ function clampHeadingLevel(value, minimum) {
1072
+ return Math.min(6, Math.max(1, typeof value === "number" && Number.isInteger(value) ? value : 1, typeof minimum === "number" && Number.isInteger(minimum) ? minimum : 1));
1073
+ }
1074
+ function colorStyle(property, value) {
1075
+ if (typeof value !== "string") return null;
1076
+ if (!HEX_COLOR.test(value) && !NAMED_COLOR.test(value)) return null;
1077
+ return `${property}: ${value}`;
1078
+ }
1079
+ function applyMarks(text, marks, options) {
1080
+ return marks.reduce((child, mark) => {
1081
+ const wrap = (tag, attrs = {}) => ({
1082
+ tag,
1083
+ attrs,
1084
+ children: [child]
1085
+ });
1086
+ switch (mark.type) {
1087
+ case "bold": return wrap("strong");
1088
+ case "italic": return wrap("em");
1089
+ case "strike": return wrap("s");
1090
+ case "underline": return wrap("u");
1091
+ case "code": return wrap("code");
1092
+ case "highlight": {
1093
+ const style = colorStyle("background-color", mark.attrs?.color);
1094
+ return wrap("mark", style !== null ? { style } : {});
1095
+ }
1096
+ case "textStyle": {
1097
+ const style = colorStyle("color", mark.attrs?.color);
1098
+ return wrap("span", style !== null ? { style } : {});
1099
+ }
1100
+ case "link": return buildLinkMark(mark, options, child);
1101
+ case "fileAttachment": return buildFileAttachmentMark(mark, options, child);
1102
+ default: return child;
1103
+ }
1104
+ }, text);
1105
+ }
1106
+ function buildLinkMark(mark, options, child) {
1107
+ const href = options.safeHref(mark.attrs?.href);
1108
+ if (href === null) return child;
1109
+ const attrs = { href };
1110
+ if (mark.attrs?.target === "_blank") {
1111
+ attrs.target = "_blank";
1112
+ attrs.rel = "noopener noreferrer";
1113
+ }
1114
+ return {
1115
+ tag: "a",
1116
+ attrs,
1117
+ children: [child]
1118
+ };
1119
+ }
1120
+ function buildFileAttachmentMark(mark, options, child) {
1121
+ const href = options.safeHref(mark.attrs?.href);
1122
+ if (href === null) return child;
1123
+ const attrs = {
1124
+ href,
1125
+ "data-file-attachment": ""
1126
+ };
1127
+ if (typeof mark.attrs?.assetId === "string") attrs["data-asset-id"] = mark.attrs.assetId;
1128
+ if (typeof mark.attrs?.filename === "string") attrs.download = mark.attrs.filename;
1129
+ return {
1130
+ tag: "a",
1131
+ attrs,
1132
+ children: [child]
1133
+ };
1134
+ }
1135
+ //#endregion
1136
+ export { DEFAULT_IMAGE_FRAMING, DEFAULT_LAYOUT_BREAKPOINTS, DesignTokenValidationError, EDIT_MODE_HIDDEN_OPACITY, EldraClientError, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, LAYOUT_BREAKPOINTS, LayoutValidationError, MAX_DYNAMIC_ROUTE_PATTERN_BYTES, PREVIEW_ROUTER_MESSAGE_TYPES, RICH_TEXT_LEAF_TYPES, RICH_TEXT_MARK_ELEMENTS, RICH_TEXT_PAD_ATTR, RICH_TEXT_TOOLBAR_CONTROLS, ReusableComponentSnapshotCache, activeLayoutBreakpoint, applyDesignTokenOverrides, buildDynamicRoutePath, buildRichTextTree, buildTemplateBlockRenames, catalogRouteTarget, clampFocal, clampImageFraming, classifyBeforeInput, computeRichTextPositions, createEldraClient, createLayoutRenderModel, createOverlayRuntime, createPreviewMessageRouter, createProjectionResolver, createReusableLayoutRenderModel, createTemplateLayoutRenderModel, decodeStega, describeSelectionContext, designTokenRevisionHash, domRangeToPositions, encodeEntryDataStega, encodeStega, focalBand, framingDrag, framingZoom, generateDesignTokenCss, generateLayoutCss, generateTailwindThemeCss, hiddenLayoutBreakpoints, imageFramingAttrs, imageFramingStyle, isBlockFieldLocalized, layoutIdentityOf, layoutNodeClass, layoutRenderNodeId, matchDynamicRoutePattern, normalizeColorSelection, normalizeImageFraming, normalizeLayoutDocument, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, parseDynamicRoutePattern, parseImageFramingValueAttr, projectEntryDataLocale, registerBlockFields, resolveColorSelection, resolveDesignTokenCatalog, resolveDomPoint, resolveDomPosition, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, responsiveValue, restampRichTextPositions, richTextMarkNameOf, richTextNodeSize, richTextText, safeHref, stripStega, unscaledFrameRect, validateLayoutDocument };