riverbankcms 0.31.0 → 0.31.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4646 +0,0 @@
1
- #!/usr/bin/env node
2
- import { Cn as ICON_PICKER_PRESETS, _r as linkSchema, a as classifySdkEventSchedule, i as sdkEventUpsertOptionalFieldSchemas, n as sdkCourseBookingSettingsSchema, o as classifySdkEventBookingOffer, or as createRichTextDoc, vr as normalizeLinkValue } from "./sdk-event-upsert-BC_MyWOx.mjs";
3
- import { m as EVENT_PRESET_VALUES } from "./src-CevC_tvx.mjs";
4
- import { z } from "zod";
5
-
6
- //#region ../content-model/src/title-resolution.ts
7
- /**
8
- * Content title resolution utilities.
9
- *
10
- * Provides a single source of truth for resolving display titles from content data.
11
- */
12
- /**
13
- * Default fields to check when titleField is not configured.
14
- * Order matters - first match wins.
15
- */
16
- const TITLE_FIELD_CANDIDATES = ["title", "name"];
17
- /**
18
- * Resolve title from content data using configured titleField with fallbacks.
19
- *
20
- * Resolution order:
21
- * 1. Explicit titleField (if configured)
22
- * 2. 'title' field
23
- * 3. 'name' field
24
- * 4. Fallback title
25
- *
26
- * @param content - Content data object
27
- * @param titleField - Configured title field ID (optional)
28
- * @param fallbackTitle - Fallback if no title found
29
- * @returns Resolved title string
30
- */
31
- function resolveContentTitle(content, titleField, fallbackTitle) {
32
- if (!content) return fallbackTitle;
33
- const candidates = [titleField?.trim(), ...TITLE_FIELD_CANDIDATES].filter((f) => Boolean(f?.trim()));
34
- for (const field of candidates) {
35
- const value = content[field];
36
- if (typeof value === "string") {
37
- const trimmed = value.trim();
38
- if (trimmed) return trimmed;
39
- }
40
- }
41
- return fallbackTitle;
42
- }
43
-
44
- //#endregion
45
- //#region ../content-model/src/metadataConfig.ts
46
- const ROUTE_METADATA_MANIFEST = {
47
- variantMeaning: { kind: "arrangement" },
48
- name: "content-entry-metadata",
49
- version: "1.0.0",
50
- title: "Details",
51
- description: "",
52
- component: "ContentEntryMetadata",
53
- fields: [
54
- {
55
- id: "draftTitle",
56
- type: "text",
57
- label: "Title",
58
- description: "The page's own name. It doesn't change any heading on the page.",
59
- required: true,
60
- multiline: false
61
- },
62
- {
63
- id: "draftMetaTitle",
64
- type: "text",
65
- label: "Search title",
66
- description: "Shown as the link in search results.",
67
- multiline: false,
68
- required: false,
69
- ui: { showCharCount: { max: 60 } }
70
- },
71
- {
72
- id: "draftMetaDescription",
73
- type: "text",
74
- label: "Search description",
75
- description: "The short summary under the link in search results.",
76
- required: false,
77
- multiline: true,
78
- ui: { showCharCount: { max: 160 } }
79
- },
80
- {
81
- id: "ogImageId",
82
- type: "text",
83
- label: "Social image",
84
- description: "Shown when someone shares a link to this page.",
85
- ui: { widget: "socialImage" },
86
- required: false,
87
- multiline: false
88
- }
89
- ],
90
- slots: []
91
- };
92
- const HOMEPAGE_PAGE_ROUTE_SLUG = { kind: "homepage" };
93
- function asNonEmptyPageRouteSlug(value) {
94
- return value;
95
- }
96
- function pageRouteSlugFromEditorValue(value) {
97
- const slug = sanitizeSlug(value ?? "");
98
- return slug.length > 0 ? {
99
- kind: "slug",
100
- value: asNonEmptyPageRouteSlug(slug)
101
- } : HOMEPAGE_PAGE_ROUTE_SLUG;
102
- }
103
- function pageRouteSlugToEditorValue(slug) {
104
- return slug.kind === "homepage" ? "" : slug.value;
105
- }
106
- function pageRouteSlugToStoredValue(slug) {
107
- return slug.kind === "homepage" ? null : slug.value;
108
- }
109
- function isHomepagePageRouteSlug(slug) {
110
- return slug.kind === "homepage";
111
- }
112
- function resolvePageRouteSlug(entry, currentSlug) {
113
- if (entry.kind !== "routable") return null;
114
- if (entry.draft.path === "/" || entry.published.path === "/") {
115
- return HOMEPAGE_PAGE_ROUTE_SLUG;
116
- }
117
- if (currentSlug !== undefined) {
118
- return pageRouteSlugFromEditorValue(currentSlug);
119
- }
120
- return pageRouteSlugFromEditorValue(entry.draft.slug);
121
- }
122
- const ROUTE_METADATA_MANAGED_FIELDS_BY_TYPE = {
123
- event: ["draftTitle", "draftSlug"],
124
- product: ["draftTitle", "draftSlug"],
125
- "product-category": ["draftTitle", "draftSlug"],
126
- "team-member": ["draftTitle", "draftSlug"]
127
- };
128
- const EMPTY_METADATA_FIELDS = [];
129
- function normalizeContentTypeKey(typeKey) {
130
- if (typeof typeKey !== "string") return null;
131
- const trimmed = typeKey.trim().toLowerCase();
132
- return trimmed.length > 0 ? trimmed : null;
133
- }
134
- function getManagedRouteMetadataFieldIdsForType(typeKey) {
135
- const normalizedTypeKey = normalizeContentTypeKey(typeKey);
136
- if (!normalizedTypeKey) return EMPTY_METADATA_FIELDS;
137
- return ROUTE_METADATA_MANAGED_FIELDS_BY_TYPE[normalizedTypeKey] ?? EMPTY_METADATA_FIELDS;
138
- }
139
- function isRouteMetadataFieldEditableForType(typeKey, fieldId) {
140
- const managedFields = getManagedRouteMetadataFieldIdsForType(typeKey);
141
- return !managedFields.includes(fieldId);
142
- }
143
- function getEditableRouteMetadataFieldIdsForType(typeKey) {
144
- return ROUTE_METADATA_MANIFEST.fields.map((field) => String(field.id)).filter((fieldId) => isRouteMetadataFieldEditableForType(typeKey, fieldId));
145
- }
146
- function getRouteMetadataManifestForType(typeKey) {
147
- return {
148
- ...ROUTE_METADATA_MANIFEST,
149
- fields: ROUTE_METADATA_MANIFEST.fields.filter((field) => isRouteMetadataFieldEditableForType(typeKey, String(field.id)))
150
- };
151
- }
152
- function getRouteMetadataManifestForContext(context) {
153
- if (context.kind === "content") {
154
- return getRouteMetadataManifestForType(context.typeKey);
155
- }
156
- return ROUTE_METADATA_MANIFEST;
157
- }
158
- function deriveRouteMetadataPresentation(context, options = {}) {
159
- const contextManifest = getRouteMetadataManifestForContext(context);
160
- const manifest = options.omitTitle ? omitRouteTitleFieldFromManifest(contextManifest) : contextManifest;
161
- if (context.kind === "content") {
162
- return {
163
- kind: "content",
164
- manifest,
165
- typeKey: normalizeContentTypeKey(context.typeKey)
166
- };
167
- }
168
- if (context.routeSlug.kind === "homepage") {
169
- return {
170
- kind: "page-homepage",
171
- manifest,
172
- routeSlug: context.routeSlug
173
- };
174
- }
175
- return {
176
- kind: "page-routable",
177
- manifest,
178
- routeSlug: context.routeSlug
179
- };
180
- }
181
- /**
182
- * Remove the legacy route title editor from a route metadata manifest.
183
- *
184
- * Entry titles are now derived from entry data (single source of truth) and the route title is a denormalized copy.
185
- * We still keep `draftTitle` in the underlying manifest for page creation flows, but we omit it from entry editors.
186
- */
187
- function omitRouteTitleFieldFromManifest(manifest) {
188
- const fields = manifest.fields.filter((field) => field.id !== "draftTitle");
189
- return {
190
- ...manifest,
191
- fields
192
- };
193
- }
194
- function sanitizeSlug(value) {
195
- if (!value) return "";
196
- return value.split("/").map((segment) => normalizeSlugSegment(segment)).filter(Boolean).join("/");
197
- }
198
- function normalizeSlugSegment(segment) {
199
- const normalized = segment.trim().normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
200
- return normalized;
201
- }
202
-
203
- //#endregion
204
- //#region ../content-model/src/content-types/sentinels.ts
205
- /** Leaf field types that receive a placeholder sentinel (containers recurse). */
206
- const SENTINEL_LEAF_TYPES = [
207
- "text",
208
- "textarea",
209
- "richText",
210
- "number",
211
- "date",
212
- "datetime",
213
- "url",
214
- "link",
215
- "media",
216
- "file",
217
- "boolean",
218
- "select",
219
- "reference"
220
- ];
221
- /** Matches the closed sentinel shape `"<REQUIRED: …>"`. */
222
- const SENTINEL_PATTERN = /^<REQUIRED:.*>$/;
223
- /**
224
- * True when a value is an unfilled placeholder sentinel. Shared by the emitter
225
- * (self-check) and the validator (rejection) so recognition can't drift.
226
- */
227
- function isPlaceholderSentinel(value) {
228
- return typeof value === "string" && SENTINEL_PATTERN.test(value);
229
- }
230
- function effectiveReferenceKind(field) {
231
- const kind = field.referenceKind;
232
- const legacy = field.reference?.type;
233
- return kind ?? legacy;
234
- }
235
- function selectOptionValues$1(field) {
236
- const options = field.options;
237
- return options ? options.map((o) => o.value) : [];
238
- }
239
- /**
240
- * The placeholder sentinel for a leaf field. Container types (group/button/
241
- * repeater) do not have a leaf sentinel — they expand structurally — and calling
242
- * this for them returns a generic marker only for completeness.
243
- */
244
- function buildSentinel(field) {
245
- switch (field.type) {
246
- case "text":
247
- case "textarea": return "<REQUIRED: text>";
248
- case "richText": return "<REQUIRED: rich-text>";
249
- case "number": return "<REQUIRED: number>";
250
- case "date": return "<REQUIRED: date (YYYY-MM-DD)>";
251
- case "datetime": return "<REQUIRED: datetime (ISO 8601)>";
252
- case "url": return "<REQUIRED: url>";
253
- case "link": return "<REQUIRED: link>";
254
- case "media": return "<REQUIRED: media-identifier>";
255
- case "file": return "<REQUIRED: file-identifier>";
256
- case "boolean": return "<REQUIRED: boolean>";
257
- case "select": {
258
- const values = selectOptionValues$1(field);
259
- return values.length > 0 ? `<REQUIRED: select (${values.join("|")})>` : "<REQUIRED: select>";
260
- }
261
- case "reference": {
262
- const kind = effectiveReferenceKind(field);
263
- return kind ? `<REQUIRED: reference-identifier (${kind})>` : "<REQUIRED: reference-identifier>";
264
- }
265
- case "group": return "<REQUIRED: group>";
266
- case "button": return "<REQUIRED: button>";
267
- case "repeater": return "<REQUIRED: repeater>";
268
- }
269
- }
270
- /**
271
- * Deep-scan arbitrary entry data for any unfilled placeholder sentinels. Needs no
272
- * schema, so it powers the CLI's pre-HTTP upsert pre-flight.
273
- */
274
- function findUnfilledSentinels(data, pathPrefix = "") {
275
- const found = [];
276
- const walk = (value, path) => {
277
- if (isPlaceholderSentinel(value)) {
278
- found.push({
279
- path: path || "(root)",
280
- value
281
- });
282
- return;
283
- }
284
- if (Array.isArray(value)) {
285
- value.forEach((item, index) => walk(item, `${path}[${index}]`));
286
- return;
287
- }
288
- if (value !== null && typeof value === "object") {
289
- for (const [key, child] of Object.entries(value)) {
290
- walk(child, path ? `${path}.${key}` : key);
291
- }
292
- }
293
- };
294
- walk(data, pathPrefix);
295
- return found;
296
- }
297
-
298
- //#endregion
299
- //#region ../content-model/src/content-types/entryValidation.ts
300
- /**
301
- * Entry-instance validator, compiled from the content-type field DSL.
302
- *
303
- * `ContentTypeSchemaZ` validates schema DOCUMENTS; this validates entry DATA
304
- * against a schema: required-field presence, rejection of unfilled placeholder
305
- * sentinels (shared vocabulary in `sentinels.ts`), and basic per-type shape
306
- * checks. It is intentionally lightweight — enough to power scaffold diagnostics
307
- * and a CLI pre-flight — not a replacement for server-side write validation.
308
- */
309
- function subfieldsOf$1(field) {
310
- const direct = field.fields;
311
- if (direct && direct.length > 0) return direct;
312
- const nested = field.schema?.fields;
313
- return nested ?? [];
314
- }
315
- function hasRepeaterVariants(field) {
316
- return field.itemTypes !== undefined;
317
- }
318
- function resolveRepeaterVariantFields(field, item) {
319
- if (!hasRepeaterVariants(field)) return subfieldsOf$1(field);
320
- const itemTypes = field.itemTypes;
321
- const typeId = item._type;
322
- if (typeof typeId !== "string") return null;
323
- return itemTypes[typeId]?.fields ?? null;
324
- }
325
- function selectOptionValues(field) {
326
- const options = field.options;
327
- return options ? options.map((o) => o.value) : [];
328
- }
329
- function isPlainObject(value) {
330
- return value !== null && typeof value === "object" && !Array.isArray(value);
331
- }
332
- function isAllowedIdentifierBearingMedia(field, value) {
333
- if (!isPlainObject(value) || typeof value.identifier !== "string" || value.identifier.trim().length === 0) {
334
- return false;
335
- }
336
- if (value.type === undefined) return true;
337
- const allowedKinds = field.type === "media" ? field.mediaKinds : field.fileKinds;
338
- if (typeof value.type !== "string") return false;
339
- const effectiveAllowedKinds = allowedKinds ?? (field.type === "media" ? ["image"] : ["document"]);
340
- return effectiveAllowedKinds.some((kind) => kind === value.type);
341
- }
342
- function assertNever$2(type) {
343
- throw new Error(`Unsupported entry field type: ${String(type)}`);
344
- }
345
- function scalarRule(type) {
346
- switch (type) {
347
- case "text":
348
- case "textarea":
349
- case "url":
350
- case "reference":
351
- case "date":
352
- case "datetime":
353
- case "select": return {
354
- accepts: (value) => typeof value === "string",
355
- expected: "a string"
356
- };
357
- case "link": return {
358
- accepts: (value) => linkSchema.safeParse(normalizeLinkValue(value)).success,
359
- expected: "a valid link"
360
- };
361
- case "number": return {
362
- accepts: (value) => typeof value === "number" && !Number.isNaN(value),
363
- expected: "a number"
364
- };
365
- case "boolean": return {
366
- accepts: (value) => typeof value === "boolean",
367
- expected: "a boolean"
368
- };
369
- case "richText": return {
370
- accepts: (value) => typeof value === "string" || isPlainObject(value),
371
- expected: "rich-text (string or document object)"
372
- };
373
- case "group":
374
- case "button":
375
- case "media":
376
- case "file": return {
377
- accepts: isPlainObject,
378
- expected: "an object"
379
- };
380
- case "repeater": return {
381
- accepts: Array.isArray,
382
- expected: "an array"
383
- };
384
- default: return assertNever$2(type);
385
- }
386
- }
387
- function leafTypeErrors(field, value, path) {
388
- if (field.type === "media" || field.type === "file") return mediaLeafErrors(field, value, path);
389
- if (field.type === "select") return selectLeafErrors(field, value, path);
390
- const rule = scalarRule(field.type);
391
- return rule.accepts(value) ? [] : [{
392
- path,
393
- fieldType: field.type,
394
- code: "wrong_type",
395
- message: `"${path}" must be ${rule.expected}.`
396
- }];
397
- }
398
- function mediaLeafErrors(field, value, path) {
399
- if (isPlainObject(value) && isPlaceholderSentinel(value.identifier)) {
400
- return [{
401
- path,
402
- fieldType: field.type,
403
- code: "unfilled_placeholder",
404
- message: `"${path}" still contains an unfilled placeholder (${value.identifier}).`
405
- }];
406
- }
407
- return isAllowedIdentifierBearingMedia(field, value) ? [] : [{
408
- path,
409
- fieldType: field.type,
410
- code: "wrong_type",
411
- message: `"${path}" must be a media object with an identifier.`
412
- }];
413
- }
414
- function selectLeafErrors(field, value, path) {
415
- if (typeof value !== "string") return [{
416
- path,
417
- fieldType: field.type,
418
- code: "wrong_type",
419
- message: `"${path}" must be a string.`
420
- }];
421
- const options = selectOptionValues(field);
422
- return options.length > 0 && !options.includes(value) ? [{
423
- path,
424
- fieldType: field.type,
425
- code: "invalid_option",
426
- message: `"${path}" must be one of: ${options.join(", ")}.`
427
- }] : [];
428
- }
429
- function validateField(field, value, path, allowIncomplete) {
430
- const missing = value === undefined || value === null || value === "";
431
- if (missing) return field.required === true && !allowIncomplete ? [{
432
- path,
433
- fieldType: field.type,
434
- code: "missing_required",
435
- message: `Required field "${path}" is missing.`
436
- }] : [];
437
- if (isPlaceholderSentinel(value)) return [{
438
- path,
439
- fieldType: field.type,
440
- code: "unfilled_placeholder",
441
- message: `"${path}" still contains an unfilled placeholder (${value}).`
442
- }];
443
- return validatePresentField(field, value, path, allowIncomplete);
444
- }
445
- function validatePresentField(field, value, path, allowIncomplete) {
446
- if (field.type === "group" || field.type === "button") {
447
- return isPlainObject(value) ? validateFields(subfieldsOf$1(field), value, path, allowIncomplete) : [{
448
- path,
449
- fieldType: field.type,
450
- code: "wrong_type",
451
- message: `"${path}" must be an object.`
452
- }];
453
- }
454
- if (field.type === "repeater") {
455
- return Array.isArray(value) ? value.flatMap((item, index) => validateRepeaterItem(field, item, `${path}[${index}]`, allowIncomplete)) : [{
456
- path,
457
- fieldType: field.type,
458
- code: "wrong_type",
459
- message: `"${path}" must be an array.`
460
- }];
461
- }
462
- return leafTypeErrors(field, value, path);
463
- }
464
- function validateRepeaterItem(field, item, path, allowIncomplete) {
465
- if (!isPlainObject(item)) return [{
466
- path,
467
- fieldType: "repeater",
468
- code: "wrong_type",
469
- message: `"${path}" must be an object.`
470
- }];
471
- const fields = resolveRepeaterVariantFields(field, item);
472
- return fields ? validateFields(fields, item, path, allowIncomplete) : [{
473
- path,
474
- fieldType: "repeater",
475
- code: "invalid_option",
476
- message: `"${path}" has an unknown or missing repeater item type.`
477
- }];
478
- }
479
- function validateFields(fields, data, pathPrefix, allowIncomplete) {
480
- return fields.flatMap((field) => validateField(field, data[field.id], pathPrefix ? `${pathPrefix}.${field.id}` : field.id, allowIncomplete));
481
- }
482
- /** Validate all entry fields, returning every error so callers can fix them in one pass. */
483
- function validateEntryInstance(input) {
484
- const errors = validateFields(input.schema.fields, input.data, "", input.allowIncomplete ?? false);
485
- return {
486
- valid: errors.length === 0,
487
- errors
488
- };
489
- }
490
-
491
- //#endregion
492
- //#region ../content-model/src/referenceFields.ts
493
- const BUILT_IN_REFERENCE_KINDS = [
494
- "post",
495
- "form",
496
- "bookingForm",
497
- "appointmentService",
498
- "appointmentResource",
499
- "page",
500
- "newsletterList",
501
- "mailchimpAudience"
502
- ];
503
- const builtInReferenceKindSet = new Set(BUILT_IN_REFERENCE_KINDS);
504
- function isBuiltInReferenceKind(referenceKind) {
505
- return builtInReferenceKindSet.has(referenceKind);
506
- }
507
- function isDynamicContentReferenceKind(referenceKind) {
508
- return parseReferenceKind(referenceKind).kind === "dynamicContent";
509
- }
510
- function isAdapterReferenceKind(referenceKind) {
511
- const parsed = parseReferenceKind(referenceKind);
512
- return parsed.kind === "builtIn" || parsed.kind === "dynamicContent";
513
- }
514
- function parseReferenceContentTypeKey(contentTypeKey) {
515
- const trimmed = contentTypeKey.trim();
516
- return trimmed.length > 0 ? trimmed : null;
517
- }
518
- function parseReferenceKind(referenceKind) {
519
- if (isBuiltInReferenceKind(referenceKind)) {
520
- return {
521
- kind: "builtIn",
522
- referenceKind
523
- };
524
- }
525
- if (referenceKind.startsWith("content:")) {
526
- const contentTypeKey = parseReferenceContentTypeKey(referenceKind.slice("content:".length));
527
- if (contentTypeKey) {
528
- return {
529
- kind: "dynamicContent",
530
- referenceKind: `content:${contentTypeKey}`,
531
- contentTypeKey
532
- };
533
- }
534
- }
535
- return {
536
- kind: "unsupported",
537
- referenceKind
538
- };
539
- }
540
-
541
- //#endregion
542
- //#region ../content-model/src/contentManifest.ts
543
- function assertNever$1(value) {
544
- throw new Error(`Unhandled content field mapping decision: ${JSON.stringify(value)}`);
545
- }
546
- function resolveContentReferenceKind(field) {
547
- return field.referenceKind ?? field.reference?.type ?? null;
548
- }
549
- function resolveReferenceFieldMapping(referenceKind, context = {}, valueFrom = "identifier") {
550
- if (referenceKind === null) {
551
- return { kind: "missingReferenceKind" };
552
- }
553
- if (isAdapterReferenceKind(referenceKind)) {
554
- return {
555
- kind: "adapterReference",
556
- referenceKind
557
- };
558
- }
559
- if (context.referenceContentTypeKeys && !context.referenceContentTypeKeys.includes(referenceKind)) {
560
- return {
561
- kind: "unresolvedReference",
562
- referenceKind
563
- };
564
- }
565
- return {
566
- kind: "contentEntryReference",
567
- contentType: referenceKind,
568
- valueFrom
569
- };
570
- }
571
- const DEFAULT_BUTTON_VARIANTS = [
572
- {
573
- value: "primary",
574
- label: "Primary"
575
- },
576
- {
577
- value: "secondary",
578
- label: "Secondary"
579
- },
580
- {
581
- value: "outline",
582
- label: "Outline"
583
- }
584
- ];
585
- const DISPLAY_MEDIA_KINDS$1 = [
586
- "image",
587
- "video",
588
- "audio"
589
- ];
590
- function mapContentFields(fields, context) {
591
- return fields.map((field) => toFieldDefinition(field, context)).filter((field) => field !== null);
592
- }
593
- function toFieldDefinition(field, context = {}) {
594
- const label = field.label ?? startCase(field.id);
595
- const base = {
596
- id: field.id,
597
- label,
598
- description: field.description ?? undefined,
599
- required: field.required ?? false,
600
- visibleRoles: undefined,
601
- defaultValue: field.defaultValue,
602
- ui: normalizeFieldUi(field.ui)
603
- };
604
- switch (field.type) {
605
- case "text": return {
606
- ...base,
607
- type: "text",
608
- multiline: Boolean(field.multiline),
609
- maxLength: field.maxLength
610
- };
611
- case "textarea": return {
612
- ...base,
613
- type: "text",
614
- multiline: true,
615
- maxLength: field.maxLength
616
- };
617
- case "number": return {
618
- ...base,
619
- type: "number",
620
- min: field.min,
621
- max: field.max,
622
- step: field.step
623
- };
624
- case "richText": return {
625
- ...base,
626
- type: "richText"
627
- };
628
- case "media": return {
629
- ...base,
630
- type: "media",
631
- mediaKinds: normalizeDisplayMediaKinds(field.mediaKinds)
632
- };
633
- case "file": return {
634
- ...base,
635
- type: "file",
636
- fileKinds: field.fileKinds && field.fileKinds.length ? field.fileKinds : [
637
- "document",
638
- "spreadsheet",
639
- "archive",
640
- "audio"
641
- ]
642
- };
643
- case "boolean": return {
644
- ...base,
645
- type: "boolean"
646
- };
647
- case "date": return {
648
- ...base,
649
- type: "date"
650
- };
651
- case "datetime": return {
652
- ...base,
653
- type: "datetime"
654
- };
655
- case "url": return {
656
- ...base,
657
- type: "url",
658
- allowRelative: field.allowRelative ?? false
659
- };
660
- case "select": {
661
- const options = field.options ?? [];
662
- if (!options.length) return null;
663
- return {
664
- ...base,
665
- type: "select",
666
- options: options.map((option) => ({
667
- value: option.value,
668
- label: option.label ?? option.value
669
- })),
670
- multiple: Boolean(field.multiple)
671
- };
672
- }
673
- case "reference": {
674
- const referenceKind = resolveContentReferenceKind(field);
675
- const mapping = resolveReferenceFieldMapping(referenceKind, context, field.valueFrom ?? "identifier");
676
- switch (mapping.kind) {
677
- case "adapterReference":
678
- case "unresolvedReference": return {
679
- ...base,
680
- type: "reference",
681
- referenceKind: mapping.referenceKind,
682
- allowManualEntry: false
683
- };
684
- case "missingReferenceKind": return null;
685
- case "contentEntryReference": return {
686
- ...base,
687
- type: "entryPicker",
688
- fixedContentType: mapping.contentType,
689
- valueFrom: mapping.valueFrom
690
- };
691
- default: return assertNever$1(mapping);
692
- }
693
- }
694
- case "link": return {
695
- ...base,
696
- type: "link"
697
- };
698
- case "button": {
699
- const buttonContext = { variants: context.buttonVariants };
700
- return expandButtonFieldGroup(field.id, label, buttonContext);
701
- }
702
- case "group": {
703
- const nestedFields$1 = (field.fields ?? field.schema?.fields ?? []).map((f) => toFieldDefinition(f, context)).filter((f) => f !== null);
704
- if (!nestedFields$1.length) return null;
705
- return {
706
- id: field.id,
707
- label,
708
- description: field.description ?? undefined,
709
- required: field.required ?? false,
710
- type: "group",
711
- ui: normalizeFieldUi(field.ui),
712
- schema: { fields: nestedFields$1 }
713
- };
714
- }
715
- case "repeater": {
716
- const repeater = {
717
- ...base,
718
- type: "repeater",
719
- itemLabel: field.itemLabel ?? "Item"
720
- };
721
- if (hasRepeaterVariants(field)) {
722
- return {
723
- ...repeater,
724
- polymorphic: true,
725
- itemTypes: Object.fromEntries(Object.entries(field.itemTypes).map(([typeId, variant]) => [typeId, {
726
- label: typeof variant.label === "string" ? variant.label : startCase(typeId),
727
- fields: mapContentFields(variant.fields ?? [], context)
728
- }]))
729
- };
730
- }
731
- const fields = mapContentFields(field.fields ?? field.schema?.fields ?? [], context);
732
- return fields.length ? {
733
- ...repeater,
734
- schema: { fields }
735
- } : null;
736
- }
737
- default: return null;
738
- }
739
- }
740
- function normalizeDisplayMediaKinds(mediaKinds) {
741
- const displayKinds = (mediaKinds ?? []).filter(isDisplayMediaKind$1);
742
- return displayKinds.length > 0 ? displayKinds : ["image"];
743
- }
744
- function isDisplayMediaKind$1(value) {
745
- return DISPLAY_MEDIA_KINDS$1.includes(value);
746
- }
747
- function startCase(value) {
748
- return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").replace(/\s+/g, " ").replace(/^./, (match) => match.toUpperCase());
749
- }
750
- /**
751
- * Maps a content type schema to form field definitions.
752
- *
753
- * @param schema - The content type schema
754
- * @param context - Optional context with theme variants for button fields
755
- * @returns Array of field definitions for form rendering
756
- */
757
- function mapContentSchemaToFormFields(schema, context = {}) {
758
- return mapContentFields(schema.fields ?? [], context);
759
- }
760
- function expandButtonFieldGroup(fieldId, fieldLabel, context = {}) {
761
- const variants = context.variants ?? [...DEFAULT_BUTTON_VARIANTS];
762
- const mainFields = [
763
- {
764
- id: "label",
765
- type: "text",
766
- label: "Label",
767
- required: true,
768
- multiline: false,
769
- ui: { row: "primary" }
770
- },
771
- {
772
- id: "variant",
773
- type: "select",
774
- label: "Style",
775
- options: variants.map((variant) => ({ ...variant })),
776
- required: false,
777
- multiple: false,
778
- ui: { row: "primary" }
779
- },
780
- {
781
- id: "link",
782
- type: "link",
783
- label: "Link",
784
- required: true,
785
- ui: { colSpan: 2 }
786
- }
787
- ];
788
- return {
789
- id: fieldId,
790
- type: "group",
791
- label: fieldLabel,
792
- required: false,
793
- ui: {
794
- layout: "grid",
795
- columns: 2
796
- },
797
- schema: { fields: [...mainFields, {
798
- id: "icons",
799
- type: "group",
800
- label: "Icons",
801
- required: false,
802
- ui: {
803
- preset: "disclosure",
804
- colSpan: 2
805
- },
806
- schema: { fields: [{
807
- id: "iconLeft",
808
- type: "text",
809
- label: "Left icon",
810
- required: false,
811
- multiline: false,
812
- ui: {
813
- widget: "iconPicker",
814
- iconPickerPreset: "cta"
815
- }
816
- }, {
817
- id: "iconRight",
818
- type: "text",
819
- label: "Right icon",
820
- required: false,
821
- multiline: false,
822
- ui: {
823
- widget: "iconPicker",
824
- iconPickerPreset: "cta"
825
- }
826
- }] }
827
- }] }
828
- };
829
- }
830
- function normalizeFieldUi(value) {
831
- if (!value || typeof value !== "object" || Array.isArray(value)) {
832
- return undefined;
833
- }
834
- return value;
835
- }
836
-
837
- //#endregion
838
- //#region ../content-model/src/routeTemplate.ts
839
- const ROUTE_TEMPLATE_SLUG_SEGMENT = "{slug}";
840
- var InvalidRouteTemplateError = class extends Error {
841
- constructor(error) {
842
- super(describeRouteTemplateParseError(error));
843
- this.name = "InvalidRouteTemplateError";
844
- this.error = error;
845
- }
846
- };
847
- function safeParseRouteTemplate(routePattern) {
848
- if (routePattern === null || routePattern === "") {
849
- return {
850
- success: true,
851
- routeTemplate: { kind: "fallback-slug" }
852
- };
853
- }
854
- const segments = splitRouteSegments(routePattern);
855
- const slugSegmentIndices = segments.flatMap((segment, index) => segment === ROUTE_TEMPLATE_SLUG_SEGMENT ? [index] : []);
856
- if (slugSegmentIndices.length > 1) {
857
- return {
858
- success: false,
859
- error: {
860
- code: "multiple-slug-segments",
861
- routePattern,
862
- segment: ROUTE_TEMPLATE_SLUG_SEGMENT
863
- }
864
- };
865
- }
866
- const invalidSegment = segments.find((segment) => segment !== ROUTE_TEMPLATE_SLUG_SEGMENT && isUnsupportedDynamicSegment(segment));
867
- if (invalidSegment) {
868
- return {
869
- success: false,
870
- error: {
871
- code: invalidSegment.startsWith(":") ? "legacy-dynamic-segment" : "unsupported-dynamic-segment",
872
- routePattern,
873
- segment: invalidSegment
874
- }
875
- };
876
- }
877
- if (slugSegmentIndices.length === 1) {
878
- const [prefix = "", suffix = ""] = routePattern.split(ROUTE_TEMPLATE_SLUG_SEGMENT);
879
- const slugIndex = slugSegmentIndices[0] ?? 0;
880
- return {
881
- success: true,
882
- routeTemplate: {
883
- kind: "slug-template",
884
- routePattern,
885
- prefix,
886
- suffix,
887
- prefixSegments: segments.slice(0, slugIndex),
888
- suffixSegments: segments.slice(slugIndex + 1)
889
- }
890
- };
891
- }
892
- return {
893
- success: true,
894
- routeTemplate: {
895
- kind: "fixed-path",
896
- routePattern,
897
- path: routePattern
898
- }
899
- };
900
- }
901
- function parseRouteTemplate(routePattern) {
902
- const result = safeParseRouteTemplate(routePattern);
903
- if (result.success) {
904
- return result.routeTemplate;
905
- }
906
- throw new InvalidRouteTemplateError(result.error);
907
- }
908
- function isSlugTemplate(routeTemplate) {
909
- return routeTemplate.kind === "slug-template";
910
- }
911
- function fixedPathOrNull(routeTemplate) {
912
- return routeTemplate.kind === "fixed-path" ? routeTemplate.path : null;
913
- }
914
- /** Returns the first path segment, or undefined when the template has no fixed prefix segment. */
915
- function getRouteTemplatePrefix(routeTemplate) {
916
- switch (routeTemplate.kind) {
917
- case "fallback-slug": return undefined;
918
- case "fixed-path": {
919
- const fixedSegments = routeTemplate.path.split("/").filter((segment) => segment.length > 0);
920
- return fixedSegments[0];
921
- }
922
- case "slug-template": return routeTemplate.prefixSegments[0];
923
- }
924
- }
925
- function expandSlug(routeTemplate, slug) {
926
- switch (routeTemplate.kind) {
927
- case "fallback-slug": return `/${slug}`;
928
- case "fixed-path": return routeTemplate.path;
929
- case "slug-template": return `${routeTemplate.prefix}${slug}${routeTemplate.suffix}`;
930
- }
931
- }
932
- function buildContentEntryRoutePath(input) {
933
- return expandSlug(parseRouteTemplate(input.routePattern), input.slug);
934
- }
935
- function describeRouteTemplateParseError(error) {
936
- switch (error.code) {
937
- case "legacy-dynamic-segment": return `Route pattern "${error.routePattern}" uses unsupported dynamic segment "${error.segment ?? ":slug"}". Use "${ROUTE_TEMPLATE_SLUG_SEGMENT}" as a full path segment.`;
938
- case "multiple-slug-segments": return `Route pattern "${error.routePattern}" must not contain "${ROUTE_TEMPLATE_SLUG_SEGMENT}" more than once.`;
939
- case "unsupported-dynamic-segment": return `Route pattern "${error.routePattern}" contains unsupported dynamic segment "${error.segment ?? ""}". Route patterns may only use "${ROUTE_TEMPLATE_SLUG_SEGMENT}" as a full path segment.`;
940
- }
941
- }
942
- function splitRouteSegments(routePattern) {
943
- return routePattern.split("/").filter((segment) => segment.length > 0);
944
- }
945
- function isUnsupportedDynamicSegment(segment) {
946
- return segment.startsWith(":") || segment.includes("{") || segment.includes("}");
947
- }
948
-
949
- //#endregion
950
- //#region ../content-model/src/definitions/canonicalizePageRouteMetadata.ts
951
- function normalizePathInput(value) {
952
- if (typeof value !== "string") return null;
953
- const trimmed = value.trim();
954
- return trimmed.length > 0 ? trimmed : null;
955
- }
956
- function canonicalizePageRoutePair(input, routing, options) {
957
- const normalizedPath = normalizePathInput(input.path);
958
- if (normalizedPath !== null) {
959
- const slug$1 = routing.toSlug(normalizedPath);
960
- return {
961
- path: routing.buildRoutePath(slug$1),
962
- slug: slug$1
963
- };
964
- }
965
- const trimmedInputSlug = typeof input.slug === "string" ? input.slug.trim() : "";
966
- const trimmedFallbackSlug = typeof options.fallbackSlug === "string" ? options.fallbackSlug.trim() : "";
967
- const rawSlug = trimmedInputSlug.length > 0 ? trimmedInputSlug : trimmedFallbackSlug;
968
- const slug = routing.sanitize(rawSlug);
969
- if (slug.length > 0) {
970
- return {
971
- path: routing.buildRoutePath(slug),
972
- slug
973
- };
974
- }
975
- if (options.allowMissing) {
976
- return {
977
- path: null,
978
- slug: null
979
- };
980
- }
981
- return {
982
- path: routing.buildRoutePath(""),
983
- slug: ""
984
- };
985
- }
986
- /**
987
- * Normalize routable page metadata into one editor/store-facing representation.
988
- *
989
- * Contract:
990
- * - Prefer explicit paths when present, deriving slugs from those paths so `/`, `''`, and persisted `NULL` homepage
991
- * variants collapse to the same draft/published shape.
992
- * - Preserve a missing published route as `{ path: null, slug: null }` so callers can distinguish "never published"
993
- * from "published homepage".
994
- * - Always return a concrete draft route for editor state, using `draftFallbackSlug` when both draft path and slug
995
- * are absent.
996
- *
997
- * This helper intentionally returns homepage slugs as empty strings for editor/store use. DB-facing callers that store
998
- * homepage slugs as `NULL` should map the output through `toStoredPageRouteSlug()`.
999
- */
1000
- function canonicalizePageRouteMetadata(input, routing, options = {}) {
1001
- const published = canonicalizePageRoutePair({
1002
- path: input.publishedPath,
1003
- slug: input.publishedSlug
1004
- }, routing, { allowMissing: true });
1005
- const draft = canonicalizePageRoutePair({
1006
- path: input.draftPath,
1007
- slug: input.draftSlug ?? published.slug
1008
- }, routing, {
1009
- allowMissing: false,
1010
- fallbackSlug: options.draftFallbackSlug
1011
- });
1012
- return {
1013
- draft: {
1014
- path: draft.path ?? routing.buildRoutePath(""),
1015
- slug: draft.slug ?? ""
1016
- },
1017
- published
1018
- };
1019
- }
1020
- /**
1021
- * Convert editor/store-facing page slugs back into the DB storage convention.
1022
- *
1023
- * Homepage slugs are stored as `NULL` in `site_routes`, while editor state uses empty strings to represent the
1024
- * homepage. This helper trims incidental whitespace and returns `null` for empty homepage-equivalent values.
1025
- */
1026
- function toStoredPageRouteSlug(slug) {
1027
- return pageRouteSlugToStoredValue(pageRouteSlugFromEditorValue(slug));
1028
- }
1029
-
1030
- //#endregion
1031
- //#region ../content-model/src/definitions/shared.ts
1032
- function createRoutingHelpers(schema, options = {}) {
1033
- const rawPrefix = schema.routing?.prefix ?? "/";
1034
- const slugPrefix = ensureSlugPrefix(rawPrefix);
1035
- const normalizedPrefix = normalizeRoutePrefix(slugPrefix);
1036
- const routePattern = schema.routing?.pattern ?? (schema.routing?.enabled ? "/{slug}" : undefined) ?? null;
1037
- const routeTemplate = parseRouteTemplate(routePattern);
1038
- const defaultSlug = options.slug ?? null;
1039
- const sanitize = (value) => sanitizeSlug(value ?? "");
1040
- const toSlug = (input) => {
1041
- if (!input) return "";
1042
- let normalized = input.trim();
1043
- if (!normalized) return "";
1044
- const sanitized = sanitize(normalized);
1045
- let result = sanitized;
1046
- if (result.startsWith(slugPrefix)) {
1047
- result = result.slice(slugPrefix.length);
1048
- }
1049
- const prefixed = normalizedPrefix !== "/" ? `${normalizedPrefix}/` : "/";
1050
- if (prefixed !== "/" && result.startsWith(prefixed)) {
1051
- result = result.slice(prefixed.length);
1052
- }
1053
- if (normalizedPrefix !== "/" && !result.startsWith("/")) {
1054
- const prefixWithoutLeadingSlash = normalizedPrefix.slice(1) + "/";
1055
- if (result.startsWith(prefixWithoutLeadingSlash)) {
1056
- result = result.slice(prefixWithoutLeadingSlash.length);
1057
- }
1058
- }
1059
- if (prefixed === "/" && result.startsWith("/")) {
1060
- result = result.slice(1);
1061
- }
1062
- return result;
1063
- };
1064
- const toPath = (slug) => {
1065
- const cleaned = sanitize(slug);
1066
- if (!cleaned) {
1067
- return normalizedPrefix === "/" ? "/" : normalizedPrefix;
1068
- }
1069
- if (normalizedPrefix === "/") {
1070
- return `/${cleaned}`;
1071
- }
1072
- return `${normalizedPrefix}/${cleaned}`;
1073
- };
1074
- const buildRoutePath = (slug) => {
1075
- const cleaned = sanitize(slug);
1076
- const effectiveSlug = cleaned || defaultSlug || "";
1077
- if (routePattern) {
1078
- return expandSlug(routeTemplate, effectiveSlug);
1079
- }
1080
- return toPath(effectiveSlug);
1081
- };
1082
- return {
1083
- slugPrefix,
1084
- normalizedPrefix,
1085
- routePattern,
1086
- defaultSlug,
1087
- toSlug,
1088
- toPath,
1089
- buildRoutePath,
1090
- sanitize
1091
- };
1092
- }
1093
- function ensureSlugPrefix(prefix) {
1094
- const base = prefix?.trim();
1095
- if (!base) {
1096
- return "/";
1097
- }
1098
- const withLeading = base.startsWith("/") ? base : `/${base}`;
1099
- return withLeading.endsWith("/") ? withLeading : `${withLeading}/`;
1100
- }
1101
- function normalizeRoutePrefix(prefix) {
1102
- if (prefix === "/") return "/";
1103
- return prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
1104
- }
1105
- /** Both route-owning and subject-owning snapshots carry the same SEO facts. */
1106
- function snapshotSeoMetadata(route) {
1107
- return {
1108
- draftMetaTitle: route.draftMetaTitle ?? null,
1109
- draftMetaDescription: route.draftMetaDescription ?? null,
1110
- publishedMetaTitle: route.publishedMetaTitle ?? null,
1111
- publishedMetaDescription: route.publishedMetaDescription ?? null,
1112
- ogImageId: route.ogImageId ?? null
1113
- };
1114
- }
1115
- /**
1116
- * Build snapshot for routable content (content with an associated route)
1117
- */
1118
- function buildRoutableSnapshot(entry, route, routing, defaults) {
1119
- const fallbackSlug = defaults.slug ?? routing.defaultSlug ?? "";
1120
- const rawDraftTitle = route.draftTitle ?? route.publishedTitle ?? null;
1121
- if (!rawDraftTitle || rawDraftTitle.trim().length === 0) {
1122
- throw new Error(`Missing draft title in route for entry ${entry.id}. Route data: ${JSON.stringify(route)}`);
1123
- }
1124
- const draftTitle = rawDraftTitle.trim();
1125
- const rawDraftSlug = route.draftSlug ?? fallbackSlug;
1126
- const draftSlug = routing.sanitize(rawDraftSlug);
1127
- const draftPath = route.draftPath ?? routing.toPath(draftSlug);
1128
- const draftStatus = route.draftStatus ?? "draft";
1129
- const publishAt = route.scheduledPublishAt ?? null;
1130
- const rawPublishedTitle = route.publishedTitle ?? route.draftTitle;
1131
- const publishedTitle = rawPublishedTitle ? rawPublishedTitle.trim() : null;
1132
- const publishedPath = route.publishedPath ?? null;
1133
- const publishedStatus = route.status ?? null;
1134
- const lastPublishedAt = route.lastPublishedAt ?? null;
1135
- const currentStatus = route.status ?? route.draftStatus ?? "draft";
1136
- return {
1137
- kind: "routable",
1138
- id: entry.id,
1139
- draft: {
1140
- title: draftTitle,
1141
- slug: draftSlug,
1142
- status: draftStatus,
1143
- publishAt,
1144
- path: draftPath
1145
- },
1146
- published: {
1147
- title: publishedTitle,
1148
- path: publishedPath,
1149
- status: publishedStatus ?? null,
1150
- publishAt: lastPublishedAt
1151
- },
1152
- status: currentStatus ?? "draft",
1153
- route: snapshotSeoMetadata(route)
1154
- };
1155
- }
1156
- /**
1157
- * Build snapshot for non-routable content (content without a route, like testimonials)
1158
- */
1159
- function buildNonRoutableSnapshot(entry, title) {
1160
- const safeTitle = title.trim() || "Untitled Entry";
1161
- const hasBeenPublished = !!entry.publishedVersionId;
1162
- const hasDraftVersionChanges = !!entry.publishedVersionId && !!entry.draftVersionId;
1163
- const lifecycleStatus = hasBeenPublished ? "published" : "draft";
1164
- return {
1165
- kind: "non-routable",
1166
- id: entry.id,
1167
- draft: {
1168
- title: safeTitle,
1169
- status: lifecycleStatus,
1170
- publishAt: null
1171
- },
1172
- published: {
1173
- title: hasBeenPublished ? safeTitle : null,
1174
- status: hasBeenPublished ? lifecycleStatus : null,
1175
- publishAt: null
1176
- },
1177
- status: lifecycleStatus,
1178
- hasDraftVersionChanges
1179
- };
1180
- }
1181
- function buildSnapshot(entry, route, routing, defaults) {
1182
- if (route !== null && route !== undefined) {
1183
- return buildRoutableSnapshot(entry, route, routing, defaults);
1184
- }
1185
- const title = defaults.title || "Untitled Entry";
1186
- return buildNonRoutableSnapshot(entry, title);
1187
- }
1188
- function createSnapshotFromContentEntry(data, routing, defaults, titleField) {
1189
- let resolvedDefaults = defaults;
1190
- if (!data.route && data.draftContent) {
1191
- const extractedTitle = resolveContentTitle(data.draftContent, titleField, "");
1192
- if (extractedTitle) {
1193
- resolvedDefaults = {
1194
- ...defaults,
1195
- title: extractedTitle
1196
- };
1197
- }
1198
- }
1199
- return buildSnapshot(data.entry, data.route ?? null, routing, resolvedDefaults);
1200
- }
1201
- function createSnapshotFromRoutableContent(owner, route, routing, defaults) {
1202
- return buildSnapshot(owner, route, routing, defaults);
1203
- }
1204
- /** Surface names are resolved by the subject, never copied into the route snapshot. */
1205
- function createPageSurfaceContentSnapshot(owner, route) {
1206
- return {
1207
- kind: "routable",
1208
- titleOwner: "subject",
1209
- id: owner.id,
1210
- draft: {
1211
- title: null,
1212
- slug: route.draftSlug,
1213
- path: route.draftPath,
1214
- status: route.draftStatus,
1215
- publishAt: route.scheduledPublishAt ?? null
1216
- },
1217
- published: {
1218
- title: null,
1219
- path: route.publishedPath ?? null,
1220
- status: route.status ?? null,
1221
- publishAt: route.lastPublishedAt ?? null
1222
- },
1223
- status: route.status ?? route.draftStatus,
1224
- route: snapshotSeoMetadata(route)
1225
- };
1226
- }
1227
- function createSnapshotFromPageRecord(record, routing, defaults) {
1228
- const canonicalRoute = canonicalizePageRouteMetadata({
1229
- draftPath: record.draftPath ?? null,
1230
- publishedPath: record.path ?? null
1231
- }, routing, { draftFallbackSlug: defaults.slug ?? null });
1232
- const routeLike = {
1233
- draftTitle: record.draftTitle ?? record.title ?? null,
1234
- draftPath: canonicalRoute.draft.path,
1235
- draftSlug: canonicalRoute.draft.slug,
1236
- draftStatus: record.draftStatus ?? null,
1237
- publishedTitle: record.title ?? null,
1238
- publishedPath: canonicalRoute.published.path,
1239
- publishedSlug: canonicalRoute.published.slug,
1240
- status: record.status ?? null,
1241
- publishedAt: record.publishedAt ?? null,
1242
- lastPublishedAt: record.lastPublishedAt,
1243
- scheduledPublishAt: record.scheduledPublishAt ?? null,
1244
- draftMetaTitle: record.draftMetaTitle ?? null,
1245
- draftMetaDescription: record.draftMetaDescription ?? null,
1246
- publishedMetaTitle: record.publishedMetaTitle ?? null,
1247
- publishedMetaDescription: record.publishedMetaDescription ?? null,
1248
- ogImageId: record.ogImageId ?? null
1249
- };
1250
- return buildSnapshot({ id: record.id }, routeLike, routing, defaults);
1251
- }
1252
- /** The metadata a page surface may author, shared by reads and committed receipts. */
1253
- function routeSeoMetadataValues(route) {
1254
- return {
1255
- draftMetaTitle: route.draftMetaTitle ?? null,
1256
- draftMetaDescription: route.draftMetaDescription ?? null,
1257
- ogImageId: route.ogImageId ?? null
1258
- };
1259
- }
1260
- function createMetadataStateFromSnapshot(snapshot) {
1261
- if (snapshot.kind === "non-routable") {
1262
- const empty = {};
1263
- return {
1264
- values: empty,
1265
- baseline: empty
1266
- };
1267
- }
1268
- const seo = routeSeoMetadataValues(snapshot.route);
1269
- const values = snapshot.titleOwner === "subject" ? seo : {
1270
- draftTitle: snapshot.draft.title,
1271
- ...seo
1272
- };
1273
- return {
1274
- values,
1275
- baseline: { ...values }
1276
- };
1277
- }
1278
- function routeLifecycleContext(snapshot) {
1279
- if (snapshot.kind === "non-routable") return null;
1280
- return {
1281
- draftStatus: snapshot.draft.status,
1282
- scheduledPublishAt: snapshot.draft.publishAt
1283
- };
1284
- }
1285
- /**
1286
- * Extract published metadata values from a snapshot.
1287
- * Used to set the publishedBaseline for unpublished changes detection.
1288
- *
1289
- * Returns null if the entry has never been published.
1290
- */
1291
- function getPublishedMetadataFromSnapshot(snapshot, _routing) {
1292
- if (snapshot.kind === "non-routable") {
1293
- return null;
1294
- }
1295
- const seo = routeSeoMetadataValues({
1296
- draftMetaTitle: snapshot.route.publishedMetaTitle,
1297
- draftMetaDescription: snapshot.route.publishedMetaDescription,
1298
- ogImageId: snapshot.route.ogImageId
1299
- });
1300
- const hasPublishedSignal = snapshot.published.status === "published" || Boolean(snapshot.published.publishAt);
1301
- if (snapshot.titleOwner === "subject") return hasPublishedSignal ? seo : null;
1302
- if (!snapshot.published.title && !hasPublishedSignal) {
1303
- return null;
1304
- }
1305
- const publishedTitle = snapshot.published.title ?? snapshot.draft.title;
1306
- if (!publishedTitle) return null;
1307
- return {
1308
- draftTitle: publishedTitle,
1309
- ...seo
1310
- };
1311
- }
1312
- function buildToolbarState(snapshot, context, options) {
1313
- const publishedMessage = formatPublishMessage(snapshot, options.formatPublicationDate);
1314
- const publishLabel = routeLifecycleContext(snapshot)?.draftStatus === "scheduled" ? "Publish now" : `Publish ${options.entityLabel.toLowerCase()}`;
1315
- return {
1316
- currentStatus: snapshot.status,
1317
- publishLabel,
1318
- publishedMessage,
1319
- disablePublish: false,
1320
- disableDiscard: false,
1321
- values: context.values
1322
- };
1323
- }
1324
- /** Sentence adapter only; date admission and typography belong to the shared formatter. */
1325
- function formatPublishMessage(snapshot, formatDate) {
1326
- if (snapshot.status === "published") {
1327
- const date = snapshot.published.publishAt ? formatDate(snapshot.published.publishAt) : null;
1328
- return date ? `Published ${date}` : "Published";
1329
- }
1330
- const scheduled = snapshot.status === "scheduled" && snapshot.draft.publishAt ? formatDate(snapshot.draft.publishAt) : null;
1331
- return scheduled ? `Scheduled for ${scheduled}` : "Not yet published";
1332
- }
1333
-
1334
- //#endregion
1335
- //#region ../content-model/src/content-types/schema.ts
1336
- /**
1337
- * Content field types supported in custom content types.
1338
- *
1339
- * - text, textarea, richText: Text-based fields
1340
- * - number: Numeric input
1341
- * - date, datetime: Date/time pickers
1342
- * - media: Image/video uploads
1343
- * - file: Public file uploads/downloads
1344
- * - boolean: Toggle/checkbox
1345
- * - select: Dropdown with options
1346
- * - reference: Link to another content type
1347
- * - link: URL/page link picker
1348
- * - url: Plain URL input
1349
- * - button: Expands to a group with label, variant, link, and icons
1350
- * - group: Nested field container (for advanced use cases)
1351
- */
1352
- const contentFieldTypes = [
1353
- "text",
1354
- "textarea",
1355
- "richText",
1356
- "number",
1357
- "date",
1358
- "url",
1359
- "media",
1360
- "file",
1361
- "boolean",
1362
- "select",
1363
- "reference",
1364
- "link",
1365
- "button",
1366
- "group",
1367
- "repeater",
1368
- "datetime"
1369
- ];
1370
- const DISPLAY_MEDIA_KINDS = [
1371
- "image",
1372
- "video",
1373
- "audio"
1374
- ];
1375
- const FILE_FIELD_KINDS = [
1376
- "document",
1377
- "spreadsheet",
1378
- "archive",
1379
- "audio"
1380
- ];
1381
- const LEGACY_MEDIA_KINDS = [
1382
- "image",
1383
- "video",
1384
- "audio",
1385
- "document",
1386
- "spreadsheet",
1387
- "archive"
1388
- ];
1389
- /**
1390
- * Base content field schema (non-recursive properties)
1391
- */
1392
- const BaseContentFieldSchema = z.object({
1393
- id: z.string(),
1394
- type: z.enum(contentFieldTypes),
1395
- label: z.string().optional(),
1396
- description: z.string().optional(),
1397
- required: z.boolean().optional(),
1398
- defaultValue: z.unknown().optional(),
1399
- multiline: z.boolean().optional(),
1400
- rows: z.number().int().positive().optional(),
1401
- maxLength: z.number().int().positive().optional(),
1402
- min: z.number().optional(),
1403
- max: z.number().optional(),
1404
- step: z.number().positive().optional(),
1405
- mediaKinds: z.array(z.enum(LEGACY_MEDIA_KINDS)).optional(),
1406
- fileKinds: z.array(z.enum(FILE_FIELD_KINDS)).optional(),
1407
- allowRelative: z.boolean().optional(),
1408
- options: z.array(z.object({
1409
- value: z.string(),
1410
- label: z.string().optional()
1411
- })).optional(),
1412
- multiple: z.boolean().optional(),
1413
- referenceKind: z.string().trim().optional(),
1414
- reference: z.object({ type: z.string().trim() }).optional(),
1415
- valueFrom: z.enum([
1416
- "id",
1417
- "identifier",
1418
- "slug"
1419
- ]).optional(),
1420
- ui: z.record(z.string(), z.unknown()).optional(),
1421
- itemLabel: z.string().optional()
1422
- }).superRefine((field, ctx) => {
1423
- if ((field.type === "media" || field.type === "file") && field.defaultValue !== undefined && field.defaultValue !== null && (typeof field.defaultValue !== "object" || Array.isArray(field.defaultValue) || typeof field.defaultValue.identifier !== "string" || !field.defaultValue.identifier.trim())) {
1424
- ctx.addIssue({
1425
- code: z.ZodIssueCode.custom,
1426
- path: ["defaultValue"],
1427
- message: `${field.type} defaultValue must be null or an object with a non-empty identifier`
1428
- });
1429
- }
1430
- if (field.multiple !== undefined && field.type !== "select") {
1431
- ctx.addIssue({
1432
- code: z.ZodIssueCode.custom,
1433
- path: ["multiple"],
1434
- message: "multiple is only valid for select fields"
1435
- });
1436
- }
1437
- if (field.type !== "reference") {
1438
- return;
1439
- }
1440
- const referenceKind = field.referenceKind;
1441
- const legacyReferenceType = field.reference?.type;
1442
- const effectiveReferenceKind$1 = referenceKind ?? legacyReferenceType;
1443
- if (field.referenceKind !== undefined && !referenceKind) {
1444
- ctx.addIssue({
1445
- code: z.ZodIssueCode.custom,
1446
- path: ["referenceKind"],
1447
- message: "referenceKind must not be empty"
1448
- });
1449
- }
1450
- if (field.reference?.type !== undefined && !legacyReferenceType) {
1451
- ctx.addIssue({
1452
- code: z.ZodIssueCode.custom,
1453
- path: ["reference", "type"],
1454
- message: "reference.type must not be empty"
1455
- });
1456
- }
1457
- if (referenceKind && legacyReferenceType && referenceKind !== legacyReferenceType) {
1458
- ctx.addIssue({
1459
- code: z.ZodIssueCode.custom,
1460
- path: ["referenceKind"],
1461
- message: "referenceKind must match reference.type when both are provided"
1462
- });
1463
- }
1464
- if (field.valueFrom !== undefined && effectiveReferenceKind$1 && isAdapterReferenceKind(effectiveReferenceKind$1)) {
1465
- ctx.addIssue({
1466
- code: z.ZodIssueCode.custom,
1467
- path: ["valueFrom"],
1468
- message: "valueFrom is only valid for content entry reference fields"
1469
- });
1470
- }
1471
- }).passthrough();
1472
- const ContentFieldSchema = BaseContentFieldSchema.extend({
1473
- itemTypes: z.lazy(() => z.record(z.string(), z.object({
1474
- label: z.string().optional(),
1475
- fields: z.array(ContentFieldSchema).optional()
1476
- }).passthrough())).optional(),
1477
- fields: z.lazy(() => z.array(ContentFieldSchema)).optional(),
1478
- schema: z.lazy(() => z.object({ fields: z.array(ContentFieldSchema).optional() }).passthrough()).optional()
1479
- });
1480
- const RoutingSchema = z.object({
1481
- enabled: z.boolean().default(false),
1482
- pattern: z.string().optional(),
1483
- slugField: z.string().optional(),
1484
- pathField: z.string().optional(),
1485
- prefix: z.string().optional(),
1486
- subroutes: z.array(z.object({
1487
- kind: z.string().min(1),
1488
- segmentType: z.enum([
1489
- "uuid",
1490
- "iso-date",
1491
- "uuid-or-date",
1492
- "slug"
1493
- ]),
1494
- precedence: z.enum(["subroute-first", "content-first"]).optional()
1495
- })).optional()
1496
- }).superRefine((routing, ctx) => {
1497
- if (!routing.pattern) {
1498
- return;
1499
- }
1500
- const parseResult = safeParseRouteTemplate(routing.pattern);
1501
- if (parseResult.success) {
1502
- return;
1503
- }
1504
- ctx.addIssue({
1505
- code: z.ZodIssueCode.custom,
1506
- path: ["pattern"],
1507
- message: describeRouteTemplateParseError(parseResult.error)
1508
- });
1509
- });
1510
- const LabelsSchema = z.object({
1511
- singular: z.string(),
1512
- plural: z.string()
1513
- });
1514
- const OrderingSchema = z.object({ mode: z.enum(["default", "manual"]).default("default") }).default({ mode: "default" });
1515
- const ContentTypeSchemaZ = z.object({
1516
- version: z.number().default(1),
1517
- fields: z.array(ContentFieldSchema).default([]),
1518
- routing: RoutingSchema.optional(),
1519
- titleField: z.string().optional(),
1520
- widgets: z.record(z.string(), z.unknown()).optional(),
1521
- labels: LabelsSchema.default({
1522
- singular: "Entry",
1523
- plural: "Entries"
1524
- }),
1525
- ordering: OrderingSchema.optional()
1526
- }).refine((data) => {
1527
- if (data.titleField) {
1528
- const fieldExists = data.fields.some((f) => f.id === data.titleField);
1529
- return fieldExists;
1530
- }
1531
- return true;
1532
- }, {
1533
- message: "titleField must reference an existing field ID in the fields array",
1534
- path: ["titleField"]
1535
- });
1536
- function parseContentTypeSchema(input) {
1537
- if (!input || typeof input !== "object") {
1538
- throw new Error("[content-types] Missing or invalid schema payload");
1539
- }
1540
- const result = ContentTypeSchemaZ.safeParse(input);
1541
- if (!result.success) {
1542
- const message = result.error?.message ?? "Invalid content type schema";
1543
- throw new Error(`[content-types] ${message}`);
1544
- }
1545
- return {
1546
- ...result.data,
1547
- fields: normalizeContentFields(result.data.fields ?? [])
1548
- };
1549
- }
1550
- function isManualEntryOrderingEnabled(schema) {
1551
- return schema?.ordering?.mode === "manual";
1552
- }
1553
- /** Default list order shared by management lists and public entry loaders. */
1554
- function resolveContentEntryOrder(schema, explicitOrder) {
1555
- return explicitOrder ?? (isManualEntryOrderingEnabled(schema) ? "manual.asc" : undefined);
1556
- }
1557
- function normalizeContentFields(fields) {
1558
- return fields.map((field) => {
1559
- const schemaFields = field.schema?.fields ?? undefined;
1560
- const nextFields = field.fields ?? schemaFields;
1561
- const normalizedFields = nextFields ? normalizeContentFields(nextFields) : undefined;
1562
- const next = normalizeLegacyFileMediaField({
1563
- ...field,
1564
- ...normalizedFields ? { fields: normalizedFields } : {}
1565
- });
1566
- return next;
1567
- });
1568
- }
1569
- function normalizeLegacyFileMediaField(field) {
1570
- if (field.type !== "media") return field;
1571
- const mediaKinds = field.mediaKinds ?? [];
1572
- const displayKinds = mediaKinds.filter(isDisplayMediaKind);
1573
- const fileKinds = mediaKinds.filter(isFileFieldKind);
1574
- if (fileKinds.length === 0 || displayKinds.length > 0) {
1575
- return {
1576
- ...field,
1577
- mediaKinds: displayKinds.length > 0 ? displayKinds : field.mediaKinds
1578
- };
1579
- }
1580
- const { mediaKinds: _legacyMediaKinds, ...rest } = field;
1581
- return {
1582
- ...rest,
1583
- type: "file",
1584
- fileKinds
1585
- };
1586
- }
1587
- function isDisplayMediaKind(value) {
1588
- return DISPLAY_MEDIA_KINDS.includes(value);
1589
- }
1590
- function isFileFieldKind(value) {
1591
- return FILE_FIELD_KINDS.includes(value);
1592
- }
1593
-
1594
- //#endregion
1595
- //#region ../content-model/src/content-types/scaffold.ts
1596
- /** Nested subfields for group/repeater/button-style fields (both DSL shapes). */
1597
- function subfieldsOf(field) {
1598
- const direct = field.fields;
1599
- if (direct && direct.length > 0) return direct;
1600
- const nested = field.schema?.fields;
1601
- return nested ?? [];
1602
- }
1603
- function resourceKindForFieldType(fieldType) {
1604
- if (fieldType === "media") return "media";
1605
- if (fieldType === "file") return "file";
1606
- if (fieldType === "reference") return "reference";
1607
- return undefined;
1608
- }
1609
- const CONTAINER_TYPES = new Set([
1610
- "group",
1611
- "button",
1612
- "repeater"
1613
- ]);
1614
- /**
1615
- * Build the placeholder value for a required field. Group/button fields recurse
1616
- * into their required subfields; repeaters emit a single seed item so agents see
1617
- * the item shape.
1618
- */
1619
- function buildFieldValue(field) {
1620
- if (field.type === "repeater") {
1621
- return [buildObjectFromFields(subfieldsOf(field))];
1622
- }
1623
- if (CONTAINER_TYPES.has(field.type)) {
1624
- const subfields = subfieldsOf(field);
1625
- if (subfields.length > 0) {
1626
- return buildObjectFromFields(subfields);
1627
- }
1628
- if (field.type === "button") {
1629
- return {
1630
- label: "<REQUIRED: text>",
1631
- link: "<REQUIRED: link>"
1632
- };
1633
- }
1634
- return {};
1635
- }
1636
- if (field.type === "media" || field.type === "file") {
1637
- return { identifier: buildSentinel(field) };
1638
- }
1639
- return buildSentinel(field);
1640
- }
1641
- /**
1642
- * Build a template object from a list of fields, stubbing required fields and
1643
- * omitting optional ones.
1644
- */
1645
- function buildObjectFromFields(fields) {
1646
- const template = {};
1647
- for (const field of fields) {
1648
- if (field.required !== true) continue;
1649
- template[field.id] = buildFieldValue(field);
1650
- }
1651
- return template;
1652
- }
1653
- function diagnosticFromValidationError(error) {
1654
- const needsResource = resourceKindForFieldType(error.fieldType);
1655
- const message = needsResource === "media" ? `Provide an existing media identifier for "${error.path}".` : needsResource === "file" ? `Provide an existing file identifier for "${error.path}".` : needsResource === "reference" ? `Provide an existing entry identifier for "${error.path}".` : error.message;
1656
- return {
1657
- path: error.path,
1658
- fieldType: error.fieldType,
1659
- ...needsResource ? { needsResource } : {},
1660
- message
1661
- };
1662
- }
1663
- /**
1664
- * Emit a placeholder template + diagnostics for a content type from its field DSL.
1665
- * Diagnostics come from the entry-instance validator run against the template,
1666
- * merged with a sentinel sweep so no emitted placeholder goes unreported.
1667
- */
1668
- function buildEntryScaffold(input) {
1669
- const template = buildObjectFromFields(input.schema.fields);
1670
- const { errors } = validateEntryInstance({
1671
- schema: input.schema,
1672
- data: template
1673
- });
1674
- const diagnostics = errors.map(diagnosticFromValidationError);
1675
- const seen = new Set(diagnostics.map((d) => d.path));
1676
- for (const sentinel of findUnfilledSentinels(template)) {
1677
- if (!seen.has(sentinel.path)) {
1678
- seen.add(sentinel.path);
1679
- diagnostics.push({
1680
- path: sentinel.path,
1681
- fieldType: "unknown",
1682
- message: `Replace the placeholder at "${sentinel.path}" (${sentinel.value}).`
1683
- });
1684
- }
1685
- }
1686
- return {
1687
- contentType: input.key,
1688
- template,
1689
- diagnostics,
1690
- ready: diagnostics.length === 0
1691
- };
1692
- }
1693
-
1694
- //#endregion
1695
- //#region ../content-model/src/content-types/defaults.ts
1696
- function applyContentTypeDefaults(schema) {
1697
- return {
1698
- version: schema.version ?? 1,
1699
- fields: cloneFieldCollection(schema.fields ?? []),
1700
- ordering: schema.ordering ? { ...schema.ordering } : undefined,
1701
- routing: schema.routing ? { ...schema.routing } : undefined,
1702
- widgets: schema.widgets ? { ...schema.widgets } : undefined,
1703
- labels: schema.labels ? { ...schema.labels } : {
1704
- singular: "Entry",
1705
- plural: "Entries"
1706
- }
1707
- };
1708
- }
1709
- function getWorkflowFieldIds(schema) {
1710
- if (!schema.routing?.enabled) {
1711
- return [
1712
- null,
1713
- null,
1714
- null,
1715
- null
1716
- ];
1717
- }
1718
- return [
1719
- "title",
1720
- "slug",
1721
- "status",
1722
- "publishAt"
1723
- ];
1724
- }
1725
- function serializeContentTypeSchema(schema) {
1726
- return JSON.parse(JSON.stringify(applyContentTypeDefaults(schema)));
1727
- }
1728
- function cloneFieldCollection(collection) {
1729
- return JSON.parse(JSON.stringify(collection));
1730
- }
1731
-
1732
- //#endregion
1733
- //#region ../content-model/src/content-types/builtin-schemas.ts
1734
- const POST_CONTENT_TYPE_SCHEMA = {
1735
- version: 1,
1736
- fields: [
1737
- {
1738
- id: "image",
1739
- type: "media",
1740
- label: "Featured image",
1741
- description: "Shown in the post hero and previews."
1742
- },
1743
- {
1744
- id: "excerpt",
1745
- type: "textarea",
1746
- label: "Excerpt",
1747
- description: "Short summary shown in listings.",
1748
- rows: 3
1749
- },
1750
- {
1751
- id: "body",
1752
- type: "richText",
1753
- label: "Body",
1754
- description: "Write the full post content. Paragraphs are separated automatically.",
1755
- required: true,
1756
- ui: { richTextVariant: "media" }
1757
- }
1758
- ],
1759
- routing: {
1760
- enabled: true,
1761
- pattern: "/blog/{slug}",
1762
- slugField: "slug",
1763
- prefix: "/blog/"
1764
- },
1765
- labels: {
1766
- singular: "Blog post",
1767
- plural: "Blog posts"
1768
- }
1769
- };
1770
- const EVENT_CONTENT_TYPE_SCHEMA = {
1771
- version: 1,
1772
- fields: [
1773
- {
1774
- id: "summary",
1775
- type: "textarea",
1776
- label: "Short introduction",
1777
- description: "Shown in your listings and search results, and at the top of its page.",
1778
- rows: 3
1779
- },
1780
- {
1781
- id: "image",
1782
- type: "media",
1783
- label: "Event image",
1784
- description: "At the top of its page and beside it in your listings."
1785
- },
1786
- {
1787
- id: "body",
1788
- type: "richText",
1789
- label: "Full description",
1790
- description: "The main text on its page, under the introduction."
1791
- }
1792
- ],
1793
- routing: {
1794
- enabled: true,
1795
- pattern: "/events/{slug}",
1796
- slugField: "slug",
1797
- prefix: "/events/",
1798
- subroutes: [{
1799
- kind: "event-occurrence",
1800
- segmentType: "uuid-or-date",
1801
- precedence: "subroute-first"
1802
- }, {
1803
- kind: "event-run",
1804
- segmentType: "slug",
1805
- precedence: "content-first"
1806
- }]
1807
- },
1808
- labels: {
1809
- singular: "Event",
1810
- plural: "Events"
1811
- }
1812
- };
1813
- const TEAM_MEMBER_CONTENT_TYPE_SCHEMA = {
1814
- version: 1,
1815
- fields: [
1816
- {
1817
- id: "intro",
1818
- type: "textarea",
1819
- label: "Profile intro",
1820
- description: "A short opening paragraph for the profile page.",
1821
- rows: 3,
1822
- maxLength: 360
1823
- },
1824
- {
1825
- id: "bio",
1826
- type: "richText",
1827
- label: "Profile body",
1828
- description: "Longer profile story, approach, experience, and background."
1829
- },
1830
- {
1831
- id: "credentials",
1832
- type: "textarea",
1833
- label: "Credentials and training",
1834
- description: "Qualifications, training, or experience to highlight on the page.",
1835
- rows: 4
1836
- },
1837
- {
1838
- id: "specialties",
1839
- type: "textarea",
1840
- label: "Specialties and focus areas",
1841
- description: "Areas this team member works with most often.",
1842
- rows: 4
1843
- },
1844
- {
1845
- id: "pullQuote",
1846
- type: "textarea",
1847
- label: "Pull quote",
1848
- description: "Optional quote or short statement to feature on the page.",
1849
- rows: 2,
1850
- maxLength: 240
1851
- },
1852
- {
1853
- id: "ctaLabel",
1854
- type: "text",
1855
- label: "Call-to-action label",
1856
- description: "Optional button label for the profile page.",
1857
- maxLength: 80
1858
- },
1859
- {
1860
- id: "ctaHref",
1861
- type: "url",
1862
- label: "Call-to-action link",
1863
- description: "Optional internal or external link for the profile page button.",
1864
- allowRelative: true
1865
- }
1866
- ],
1867
- routing: {
1868
- enabled: true,
1869
- pattern: "/team/{slug}",
1870
- slugField: "slug",
1871
- prefix: "/team/"
1872
- },
1873
- labels: {
1874
- singular: "Team member",
1875
- plural: "Team members"
1876
- }
1877
- };
1878
- const PRODUCT_CONTENT_TYPE_SCHEMA = {
1879
- version: 1,
1880
- fields: [
1881
- {
1882
- id: "summary",
1883
- type: "textarea",
1884
- label: "Summary",
1885
- description: "Short teaser shown in listings.",
1886
- rows: 3
1887
- },
1888
- {
1889
- id: "gallery",
1890
- type: "media",
1891
- label: "Listing image",
1892
- description: "Optional image used for product cards and previews."
1893
- },
1894
- {
1895
- id: "body",
1896
- type: "richText",
1897
- label: "Details",
1898
- description: "Full product details and buying notes."
1899
- }
1900
- ],
1901
- routing: {
1902
- enabled: true,
1903
- pattern: "/products/{slug}",
1904
- slugField: "slug",
1905
- prefix: "/products/"
1906
- },
1907
- labels: {
1908
- singular: "Product",
1909
- plural: "Products"
1910
- }
1911
- };
1912
- const TESTIMONIAL_CONTENT_TYPE_SCHEMA = {
1913
- version: 1,
1914
- ordering: { mode: "manual" },
1915
- fields: [
1916
- {
1917
- id: "name",
1918
- type: "text",
1919
- label: "Name",
1920
- description: "Who provided this testimonial?",
1921
- required: true,
1922
- maxLength: 120
1923
- },
1924
- {
1925
- id: "jobTitle",
1926
- type: "text",
1927
- label: "Job title",
1928
- description: "Optional title or role for the person.",
1929
- maxLength: 120
1930
- },
1931
- {
1932
- id: "company",
1933
- type: "text",
1934
- label: "Company",
1935
- description: "Optional company or organisation.",
1936
- maxLength: 120
1937
- },
1938
- {
1939
- id: "headshot",
1940
- type: "media",
1941
- label: "Headshot",
1942
- description: "Optional portrait or logo for this testimonial.",
1943
- mediaKinds: ["image"]
1944
- },
1945
- {
1946
- id: "body",
1947
- type: "richText",
1948
- label: "Testimonial",
1949
- description: "Full testimonial text.",
1950
- required: true,
1951
- ui: { richTextVariant: "limited" }
1952
- }
1953
- ],
1954
- routing: { enabled: false },
1955
- titleField: "name",
1956
- labels: {
1957
- singular: "Testimonial",
1958
- plural: "Testimonials"
1959
- }
1960
- };
1961
- const PAGE_CONTENT_TYPE_SCHEMA = {
1962
- version: 1,
1963
- fields: [],
1964
- routing: {
1965
- enabled: true,
1966
- pattern: "/{slug}",
1967
- slugField: "slug",
1968
- prefix: "/"
1969
- },
1970
- labels: {
1971
- singular: "Page",
1972
- plural: "Pages"
1973
- }
1974
- };
1975
- const PRODUCT_CATEGORY_CONTENT_TYPE_SCHEMA = {
1976
- version: 1,
1977
- fields: [
1978
- {
1979
- id: "summary",
1980
- type: "textarea",
1981
- label: "Summary",
1982
- description: "Short teaser shown above category product lists.",
1983
- rows: 3
1984
- },
1985
- {
1986
- id: "heroImage",
1987
- type: "media",
1988
- label: "Hero image",
1989
- description: "Optional category landing page image."
1990
- },
1991
- {
1992
- id: "body",
1993
- type: "richText",
1994
- label: "Body",
1995
- description: "Long-form category landing page content."
1996
- }
1997
- ],
1998
- routing: {
1999
- enabled: true,
2000
- pattern: "/shop/{slug}",
2001
- slugField: "slug",
2002
- prefix: "/shop/"
2003
- },
2004
- labels: {
2005
- singular: "Product category",
2006
- plural: "Product categories"
2007
- }
2008
- };
2009
-
2010
- //#endregion
2011
- //#region ../content-model/src/content-types/builtins.ts
2012
- /**
2013
- * Built-in `ContentTypeSchema` registry. Keyed exhaustively on
2014
- * `BuiltinContentTypeKey` via `satisfies` — adding a new builtin key
2015
- * fails the compile here until a schema is provided. The `as const`
2016
- * import preserves field literals so `BUILTIN_CONTENT_TYPE_FIELD_IDS`
2017
- * below can derive an accurate per-builtin field set.
2018
- */
2019
- const BUILTIN_CONTENT_TYPE_SCHEMAS = {
2020
- post: POST_CONTENT_TYPE_SCHEMA,
2021
- event: EVENT_CONTENT_TYPE_SCHEMA,
2022
- "team-member": TEAM_MEMBER_CONTENT_TYPE_SCHEMA,
2023
- product: PRODUCT_CONTENT_TYPE_SCHEMA,
2024
- testimonial: TESTIMONIAL_CONTENT_TYPE_SCHEMA,
2025
- page: PAGE_CONTENT_TYPE_SCHEMA,
2026
- "product-category": PRODUCT_CATEGORY_CONTENT_TYPE_SCHEMA
2027
- };
2028
- function deriveFieldIdSet(schema) {
2029
- return new Set(schema.fields.map((f) => f.id));
2030
- }
2031
- /**
2032
- * Field-id sets for every built-in content type — DERIVED from
2033
- * `BUILTIN_CONTENT_TYPE_SCHEMAS`, so adding a field to a schema flows
2034
- * through automatically. The previous hand-maintained registry left
2035
- * drift to a snapshot test; now drift is impossible.
2036
- *
2037
- * Kept exported with the same shape consumers were used to.
2038
- */
2039
- const BUILTIN_CONTENT_TYPE_FIELD_IDS = {
2040
- post: deriveFieldIdSet(BUILTIN_CONTENT_TYPE_SCHEMAS.post),
2041
- event: deriveFieldIdSet(BUILTIN_CONTENT_TYPE_SCHEMAS.event),
2042
- "team-member": deriveFieldIdSet(BUILTIN_CONTENT_TYPE_SCHEMAS["team-member"]),
2043
- product: deriveFieldIdSet(BUILTIN_CONTENT_TYPE_SCHEMAS.product),
2044
- testimonial: deriveFieldIdSet(BUILTIN_CONTENT_TYPE_SCHEMAS.testimonial),
2045
- page: deriveFieldIdSet(BUILTIN_CONTENT_TYPE_SCHEMAS.page),
2046
- "product-category": deriveFieldIdSet(BUILTIN_CONTENT_TYPE_SCHEMAS["product-category"])
2047
- };
2048
- const DOMAIN_BACKED_LINKED_ENTRY_REASON = "Domain-backed entries need a dedicated editor workflow.";
2049
- /**
2050
- * Preview editing support for built-in content entries when they appear as
2051
- * linked data inside a block. Generic editorial content can use the shared
2052
- * content-entry form; domain-backed content stays closed until its workflow
2053
- * can preserve domain invariants such as occurrences, booking, or commerce.
2054
- */
2055
- const BUILTIN_PREVIEW_LINKED_ENTRY_EDITING = {
2056
- post: { kind: "generic" },
2057
- event: {
2058
- kind: "unsupported-domain-backed",
2059
- reason: DOMAIN_BACKED_LINKED_ENTRY_REASON
2060
- },
2061
- "team-member": { kind: "generic" },
2062
- product: {
2063
- kind: "unsupported-domain-backed",
2064
- reason: DOMAIN_BACKED_LINKED_ENTRY_REASON
2065
- },
2066
- testimonial: { kind: "generic" },
2067
- page: { kind: "generic" },
2068
- "product-category": {
2069
- kind: "unsupported-domain-backed",
2070
- reason: DOMAIN_BACKED_LINKED_ENTRY_REASON
2071
- }
2072
- };
2073
- function getBuiltinPreviewLinkedEntryEditing(key) {
2074
- return BUILTIN_PREVIEW_LINKED_ENTRY_EDITING[key] ?? null;
2075
- }
2076
-
2077
- //#endregion
2078
- //#region ../content-model/src/content-types/labels.ts
2079
- function getContentTypeLabelsFromSchema(schema, _fallbackName) {
2080
- return {
2081
- singular: schema.labels.singular,
2082
- plural: schema.labels.plural
2083
- };
2084
- }
2085
-
2086
- //#endregion
2087
- //#region ../field-primitives/src/bindings/index.ts
2088
- const BINDING_TRANSFORMS = {
2089
- RICHTEXT_FIRST_PARAGRAPH: "richtext.firstParagraph",
2090
- DATE_FORMAT_SHORT: "date.formatShort",
2091
- DATE_FORMAT_LONG: "date.formatLong",
2092
- TEXT_INLINE_TEXT: "text.inlineText"
2093
- };
2094
- const BINDING_TRANSFORM_VALUES = Object.values(BINDING_TRANSFORMS);
2095
-
2096
- //#endregion
2097
- //#region ../content-model/src/templates/types.ts
2098
- const TEMPLATE_BINDING_TRANSFORMS = BINDING_TRANSFORMS;
2099
- function isUnknownArray(value) {
2100
- return Array.isArray(value);
2101
- }
2102
- function readTemplateFallbackOptions(binding) {
2103
- if (typeof binding !== "object" || binding === null) return undefined;
2104
- if ("options" in binding && isUnknownArray(binding.options)) return binding.options;
2105
- return "sources" in binding && isUnknownArray(binding.sources) ? binding.sources : undefined;
2106
- }
2107
- function normalizeStoredBindingDescriptor(value) {
2108
- return typeof value === "object" && value !== null && "source" in value && value.source === "fallback" ? {
2109
- ...value,
2110
- options: readTemplateFallbackOptions(value)
2111
- } : value;
2112
- }
2113
- /** Parse stored binding values without treating malformed descriptors as nested records. */
2114
- const bindingDescriptorSchema = z.lazy(() => z.preprocess(normalizeStoredBindingDescriptor, bindingDescriptorVariants));
2115
- const bindingValueSchema = z.lazy(() => z.union([
2116
- z.string(),
2117
- bindingDescriptorSchema,
2118
- z.record(z.string(), bindingValueSchema).refine((record) => typeof record.source !== "string" || !descriptorSources.has(record.source), "Malformed binding descriptor")
2119
- ]));
2120
- const bindingDescriptorVariants = z.discriminatedUnion("source", [
2121
- z.object({
2122
- source: z.literal("field"),
2123
- path: z.string()
2124
- }),
2125
- z.object({
2126
- source: z.literal("meta"),
2127
- path: z.string()
2128
- }),
2129
- z.object({
2130
- source: z.literal("literal"),
2131
- value: z.unknown()
2132
- }),
2133
- z.object({
2134
- source: z.literal("transform"),
2135
- transform: z.enum(BINDING_TRANSFORM_VALUES),
2136
- path: z.string().optional(),
2137
- input: z.union([bindingDescriptorSchema, z.string()]).optional()
2138
- }),
2139
- z.object({
2140
- source: z.literal("fallback"),
2141
- options: z.array(bindingValueSchema)
2142
- })
2143
- ]);
2144
- const descriptorSources = new Set(bindingDescriptorVariants.options.map((variant) => variant.shape.source.value));
2145
- const TemplateBindingRecordSchema = z.record(z.string(), bindingValueSchema);
2146
-
2147
- //#endregion
2148
- //#region ../content-model/src/templates/bindingBuilders.ts
2149
- function fieldBinding(path) {
2150
- return {
2151
- source: "field",
2152
- path
2153
- };
2154
- }
2155
- function metaBinding(path) {
2156
- return {
2157
- source: "meta",
2158
- path
2159
- };
2160
- }
2161
- function literalBinding(value) {
2162
- return {
2163
- source: "literal",
2164
- value
2165
- };
2166
- }
2167
- function transformBinding(transform, options = {}) {
2168
- return {
2169
- source: "transform",
2170
- transform,
2171
- ...options.input === undefined ? {} : { input: options.input },
2172
- ...options.path === undefined ? {} : { path: options.path }
2173
- };
2174
- }
2175
- function fallbackBinding(...options) {
2176
- return {
2177
- source: "fallback",
2178
- options: [...options]
2179
- };
2180
- }
2181
-
2182
- //#endregion
2183
- //#region ../content-model/src/entry-slots/types.ts
2184
- function ok(value) {
2185
- return {
2186
- ok: true,
2187
- value
2188
- };
2189
- }
2190
- function err(error) {
2191
- return {
2192
- ok: false,
2193
- error
2194
- };
2195
- }
2196
- const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2197
- const SLOT_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/;
2198
- function unsafeAsSlotKey(value) {
2199
- return value;
2200
- }
2201
- function unsafeAsEntryBlockSlotId(value) {
2202
- return value;
2203
- }
2204
- function unsafeAsEntrySlotContentEntryId(value) {
2205
- return value;
2206
- }
2207
- function unsafeAsEntrySlotPageSurfaceId(value) {
2208
- return value;
2209
- }
2210
- function unsafeAsPageSurfaceSlotId(value) {
2211
- return value;
2212
- }
2213
- function unsafeAsEntrySlotPageId(value) {
2214
- return value;
2215
- }
2216
- function unsafeAsEntrySlotBlockId(value) {
2217
- return value;
2218
- }
2219
- function unsafeAsEntrySlotContentVersionId(value) {
2220
- return value;
2221
- }
2222
- function unsafeAsEntrySlotBlockOrderIndex(value) {
2223
- return value;
2224
- }
2225
- function parseSlotKey(value) {
2226
- if (typeof value !== "string") return err({ kind: "not-string" });
2227
- const normalized = value.trim();
2228
- if (!normalized) return err({ kind: "empty" });
2229
- if (!SLOT_KEY_PATTERN.test(normalized)) {
2230
- return err({
2231
- kind: "invalid-format",
2232
- value: normalized
2233
- });
2234
- }
2235
- return ok(unsafeAsSlotKey(normalized));
2236
- }
2237
- function parseEntryBlockSlotId(value) {
2238
- return parseUuidBrand(value, unsafeAsEntryBlockSlotId);
2239
- }
2240
- function parseEntrySlotPageSurfaceId(value) {
2241
- return parseUuidBrand(value, unsafeAsEntrySlotPageSurfaceId);
2242
- }
2243
- function parsePageSurfaceSlotId(value) {
2244
- return parseUuidBrand(value, unsafeAsPageSurfaceSlotId);
2245
- }
2246
- function parseUuidBrand(value, brand) {
2247
- if (typeof value !== "string") return err({ kind: "not-string" });
2248
- const normalized = value.trim().toLowerCase();
2249
- if (!normalized) return err({ kind: "empty" });
2250
- if (!UUID_PATTERN.test(normalized)) {
2251
- return err({
2252
- kind: "invalid-uuid",
2253
- value: normalized
2254
- });
2255
- }
2256
- return ok(brand(normalized));
2257
- }
2258
- function parseNonEmptyStringBrand(value, brand) {
2259
- if (typeof value !== "string") return err({ kind: "not-string" });
2260
- const normalized = value.trim();
2261
- if (!normalized) return err({ kind: "empty" });
2262
- return ok(brand(normalized));
2263
- }
2264
- const SYSTEM_ENTRY_SLOT_BLOCK_KIND = "system.entry-slot";
2265
- const DEFAULT_ENTRY_SLOT_ALLOWED_BLOCKS = [
2266
- "block.body-text",
2267
- "block.rich-text",
2268
- "block.image-gallery",
2269
- "block.cta-full"
2270
- ];
2271
- const TEMPLATE_ONLY_BLOCK_KINDS = [
2272
- SYSTEM_ENTRY_SLOT_BLOCK_KIND,
2273
- "block.event-details",
2274
- "block.event-registration"
2275
- ];
2276
- function parseEntrySlotDefinitions(template) {
2277
- const definitions = [];
2278
- const seen = new Map();
2279
- for (const [blockIndex, block] of template.blocks.entries()) {
2280
- if (!isEntrySlotTemplateBlock(block)) continue;
2281
- const parsed = parseEntrySlotDefinition(block, blockIndex);
2282
- if (!parsed.ok) return parsed;
2283
- const firstBlockIndex = seen.get(parsed.value.slotKey);
2284
- if (firstBlockIndex !== undefined) {
2285
- return err({
2286
- kind: "duplicate-slot-key",
2287
- slotKey: parsed.value.slotKey,
2288
- firstBlockIndex,
2289
- blockIndex
2290
- });
2291
- }
2292
- seen.set(parsed.value.slotKey, blockIndex);
2293
- definitions.push(parsed.value);
2294
- }
2295
- return ok(definitions);
2296
- }
2297
- function isEntrySlotTemplateBlock(block) {
2298
- return block.blockKind === SYSTEM_ENTRY_SLOT_BLOCK_KIND;
2299
- }
2300
- function parseEntrySlotDefinition(block, blockIndex) {
2301
- if (block.scope !== "template") {
2302
- return err({
2303
- kind: "invalid-slot-scope",
2304
- blockIndex,
2305
- scope: block.scope
2306
- });
2307
- }
2308
- if (!isRecord$2(block.content)) {
2309
- return err({
2310
- kind: "invalid-slot-content",
2311
- blockIndex
2312
- });
2313
- }
2314
- const slotKeyResult = parseSlotKey(block.content.slotKey);
2315
- if (!slotKeyResult.ok) {
2316
- return err({
2317
- kind: "invalid-slot-key",
2318
- blockIndex,
2319
- error: slotKeyResult.error
2320
- });
2321
- }
2322
- const label = typeof block.content.label === "string" ? block.content.label.trim() : "";
2323
- if (!label) {
2324
- return err({
2325
- kind: "missing-label",
2326
- blockIndex,
2327
- slotKey: slotKeyResult.value
2328
- });
2329
- }
2330
- const allowedBlocks = parseAllowedBlocks(block.content.allowedBlocks, slotKeyResult.value, blockIndex);
2331
- if (!allowedBlocks.ok) return allowedBlocks;
2332
- return ok({
2333
- slotKey: slotKeyResult.value,
2334
- label,
2335
- allowedBlocks: allowedBlocks.value
2336
- });
2337
- }
2338
- function parseAllowedBlocks(value, slotKey, blockIndex) {
2339
- if (value === undefined) {
2340
- return ok({
2341
- kind: "default",
2342
- blockKinds: DEFAULT_ENTRY_SLOT_ALLOWED_BLOCKS
2343
- });
2344
- }
2345
- if (!Array.isArray(value)) {
2346
- return err({
2347
- kind: "invalid-allowed-blocks",
2348
- blockIndex,
2349
- slotKey
2350
- });
2351
- }
2352
- const allowedBlockValues = value;
2353
- if (allowedBlockValues.length === 0) {
2354
- return ok({
2355
- kind: "none",
2356
- blockKinds: []
2357
- });
2358
- }
2359
- const blockKinds = [];
2360
- const seen = new Set();
2361
- for (const blockKind of allowedBlockValues) {
2362
- if (typeof blockKind !== "string" || !blockKind.trim()) {
2363
- return err({
2364
- kind: "invalid-allowed-block-kind",
2365
- blockIndex,
2366
- slotKey,
2367
- value: blockKind
2368
- });
2369
- }
2370
- const normalized = blockKind.trim();
2371
- if (isTemplateOnlyBlockKind(normalized)) {
2372
- return err({
2373
- kind: "template-only-block-kind",
2374
- blockIndex,
2375
- slotKey,
2376
- blockKind: normalized
2377
- });
2378
- }
2379
- if (seen.has(normalized)) {
2380
- return err({
2381
- kind: "duplicate-allowed-block-kind",
2382
- blockIndex,
2383
- slotKey,
2384
- blockKind: normalized
2385
- });
2386
- }
2387
- seen.add(normalized);
2388
- blockKinds.push(normalized);
2389
- }
2390
- return ok({
2391
- kind: "restricted",
2392
- blockKinds
2393
- });
2394
- }
2395
- function validateBlockKindForEntrySlot(definition, blockKind) {
2396
- const normalized = blockKind.trim();
2397
- if (isTemplateOnlyBlockKind(normalized)) {
2398
- return err({
2399
- kind: "template-only-block-kind",
2400
- blockKind: normalized
2401
- });
2402
- }
2403
- if (definition.allowedBlocks.kind === "none") {
2404
- return err({
2405
- kind: "block-kind-not-allowed",
2406
- blockKind: normalized,
2407
- slotKey: definition.slotKey
2408
- });
2409
- }
2410
- if (!definition.allowedBlocks.blockKinds.includes(normalized)) {
2411
- return err({
2412
- kind: "block-kind-not-allowed",
2413
- blockKind: normalized,
2414
- slotKey: definition.slotKey
2415
- });
2416
- }
2417
- return ok(normalized);
2418
- }
2419
- /**
2420
- * Kinds that read the entry a template is rendering (its event, its slots),
2421
- * so they have nothing to show anywhere but a content type's template.
2422
- */
2423
- function isTemplateOnlyBlockKind(blockKind) {
2424
- return blockKind.startsWith("system.") || TEMPLATE_ONLY_BLOCK_KINDS.includes(blockKind);
2425
- }
2426
- function resolveEntrySlotVisibility(input) {
2427
- const storedByKey = new Map();
2428
- for (const slot of input.storedSlots) {
2429
- storedByKey.set(slot.slotKey, slot);
2430
- }
2431
- const visible = input.definitions.map((definition) => ({
2432
- kind: "defined",
2433
- definition,
2434
- entrySlot: storedByKey.get(definition.slotKey) ?? null
2435
- }));
2436
- const definedKeys = new Set(input.definitions.map((definition) => definition.slotKey));
2437
- for (const slot of input.storedSlots) {
2438
- if (!definedKeys.has(slot.slotKey)) {
2439
- visible.push({
2440
- kind: "orphaned",
2441
- slotKey: slot.slotKey,
2442
- entrySlot: slot
2443
- });
2444
- }
2445
- }
2446
- return visible;
2447
- }
2448
- function resolveEntryPageCompositionState(slot) {
2449
- if (slot.kind === "orphaned") {
2450
- return {
2451
- kind: "invalid",
2452
- reason: "orphaned-slot"
2453
- };
2454
- }
2455
- if (!slot.entrySlot) return { kind: "absent" };
2456
- const { draftCompositionVersionId, publishedCompositionVersionId } = slot.entrySlot;
2457
- if (draftCompositionVersionId && publishedCompositionVersionId) {
2458
- return {
2459
- kind: "draft-and-published",
2460
- draftCompositionVersionId,
2461
- publishedCompositionVersionId
2462
- };
2463
- }
2464
- if (draftCompositionVersionId) return {
2465
- kind: "draft-only",
2466
- draftCompositionVersionId
2467
- };
2468
- if (publishedCompositionVersionId) return {
2469
- kind: "published-only",
2470
- publishedCompositionVersionId
2471
- };
2472
- return { kind: "absent" };
2473
- }
2474
- function selectBlocksForDeclaredEntrySlot(input) {
2475
- return input.entrySlots.find((slot) => slot.slotKey === input.declaredSlotKey)?.blocks ?? [];
2476
- }
2477
- function buildDraftEntrySlotCompositionVersionData(input) {
2478
- return {
2479
- schemaVersion: 1,
2480
- stage: "draft",
2481
- ...input
2482
- };
2483
- }
2484
- function entrySlotCompositionOwnerFromV1(versionData) {
2485
- return {
2486
- kind: "entrySlot",
2487
- entrySlotId: versionData.entrySlotId,
2488
- contentEntryId: versionData.contentEntryId
2489
- };
2490
- }
2491
- function buildDraftSlotCompositionVersionData(input) {
2492
- return {
2493
- schemaVersion: 2,
2494
- stage: "draft",
2495
- ...input
2496
- };
2497
- }
2498
- function buildPublishedEntrySlotCompositionVersionData(input) {
2499
- const published = filterPublishedSlotBlocks(input.blockSequence);
2500
- if (!published.ok) return published;
2501
- return ok({
2502
- schemaVersion: 1,
2503
- stage: "published",
2504
- entrySlotId: input.entrySlotId,
2505
- contentEntryId: input.contentEntryId,
2506
- slotKey: input.slotKey,
2507
- blockSequence: published.value
2508
- });
2509
- }
2510
- function buildPublishedSlotCompositionVersionData(input) {
2511
- const published = filterPublishedSlotBlocks(input.blockSequence);
2512
- if (!published.ok) return published;
2513
- return ok({
2514
- schemaVersion: 2,
2515
- stage: "published",
2516
- owner: input.owner,
2517
- slotKey: input.slotKey,
2518
- blockSequence: published.value
2519
- });
2520
- }
2521
- function filterPublishedSlotBlocks(blockSequence) {
2522
- for (const block of blockSequence) {
2523
- if (block.kind !== "published-block-content") {
2524
- return err({
2525
- kind: "published-composition-contains-unpublished-block",
2526
- blockId: block.blockId,
2527
- snapshotKind: block.kind
2528
- });
2529
- }
2530
- }
2531
- return ok(blockSequence.filter((block) => block.kind === "published-block-content"));
2532
- }
2533
- function parseEntrySlotCompositionVersionData(input) {
2534
- if (!isRecord$2(input)) return err({ kind: "not-object" });
2535
- if (input.schemaVersion !== 1) {
2536
- return err({
2537
- kind: "unsupported-schema-version",
2538
- schemaVersion: input.schemaVersion
2539
- });
2540
- }
2541
- const stage = parseSlotCompositionStage(input.stage);
2542
- if (!stage.ok) {
2543
- return err({
2544
- kind: "invalid-stage",
2545
- stage: input.stage
2546
- });
2547
- }
2548
- const entrySlotId = parseEntryBlockSlotId(input.entrySlotId);
2549
- if (!entrySlotId.ok) return err({
2550
- kind: "invalid-entry-slot-id",
2551
- error: entrySlotId.error
2552
- });
2553
- const contentEntryId = parseNonEmptyStringBrand(input.contentEntryId, unsafeAsEntrySlotContentEntryId);
2554
- if (!contentEntryId.ok) return err({
2555
- kind: "invalid-content-entry-id",
2556
- error: contentEntryId.error
2557
- });
2558
- const slotKey = parseSlotKey(input.slotKey);
2559
- if (!slotKey.ok) return err({
2560
- kind: "invalid-slot-key",
2561
- error: slotKey.error
2562
- });
2563
- const parsedBlockSequence = parseSlotCompositionBlockSequence(stage.value, input.blockSequence);
2564
- if (!parsedBlockSequence.ok) return parsedBlockSequence;
2565
- if (parsedBlockSequence.value.stage === "draft") {
2566
- return ok(buildDraftEntrySlotCompositionVersionData({
2567
- entrySlotId: entrySlotId.value,
2568
- contentEntryId: contentEntryId.value,
2569
- slotKey: slotKey.value,
2570
- blockSequence: parsedBlockSequence.value.blockSequence
2571
- }));
2572
- }
2573
- return ok({
2574
- schemaVersion: 1,
2575
- stage: "published",
2576
- entrySlotId: entrySlotId.value,
2577
- contentEntryId: contentEntryId.value,
2578
- slotKey: slotKey.value,
2579
- blockSequence: parsedBlockSequence.value.blockSequence
2580
- });
2581
- }
2582
- function parseSlotCompositionVersionData(input) {
2583
- if (!isRecord$2(input)) return err({ kind: "not-object" });
2584
- if (input.schemaVersion === 1) {
2585
- return parseEntrySlotCompositionVersionData(input);
2586
- }
2587
- if (input.schemaVersion !== 2) {
2588
- return err({
2589
- kind: "unsupported-schema-version",
2590
- schemaVersion: input.schemaVersion
2591
- });
2592
- }
2593
- const stage = parseSlotCompositionStage(input.stage);
2594
- if (!stage.ok) {
2595
- return err({
2596
- kind: "invalid-stage",
2597
- stage: input.stage
2598
- });
2599
- }
2600
- const owner = parseSlotCompositionOwner(input.owner);
2601
- if (!owner.ok) return err({
2602
- kind: "invalid-owner",
2603
- error: owner.error
2604
- });
2605
- const slotKey = parseSlotKey(input.slotKey);
2606
- if (!slotKey.ok) return err({
2607
- kind: "invalid-slot-key",
2608
- error: slotKey.error
2609
- });
2610
- const parsedBlockSequence = parseSlotCompositionBlockSequence(stage.value, input.blockSequence);
2611
- if (!parsedBlockSequence.ok) return parsedBlockSequence;
2612
- if (parsedBlockSequence.value.stage === "draft") {
2613
- return ok(buildDraftSlotCompositionVersionData({
2614
- owner: owner.value,
2615
- slotKey: slotKey.value,
2616
- blockSequence: parsedBlockSequence.value.blockSequence
2617
- }));
2618
- }
2619
- return ok({
2620
- schemaVersion: 2,
2621
- stage: "published",
2622
- owner: owner.value,
2623
- slotKey: slotKey.value,
2624
- blockSequence: parsedBlockSequence.value.blockSequence
2625
- });
2626
- }
2627
- function parseSlotCompositionStage(value) {
2628
- return value === "draft" || value === "published" ? ok(value) : err("invalid");
2629
- }
2630
- function parseSlotCompositionBlockSequence(stage, value) {
2631
- if (!Array.isArray(value)) return err({ kind: "invalid-block-sequence" });
2632
- const blockSequence = [];
2633
- const publishedBlockSequence = [];
2634
- for (const [index, snapshot] of value.entries()) {
2635
- const parsed = parseEntrySlotBlockSnapshot(snapshot);
2636
- if (!parsed.ok) return err({
2637
- kind: "invalid-block-snapshot",
2638
- index
2639
- });
2640
- if (stage === "published" && parsed.value.kind !== "published-block-content") {
2641
- return err({
2642
- kind: "published-composition-contains-unpublished-block",
2643
- index
2644
- });
2645
- }
2646
- if (parsed.value.kind === "published-block-content") {
2647
- publishedBlockSequence.push(parsed.value);
2648
- }
2649
- blockSequence.push(parsed.value);
2650
- }
2651
- return stage === "draft" ? ok({
2652
- stage,
2653
- blockSequence
2654
- }) : ok({
2655
- stage,
2656
- blockSequence: publishedBlockSequence
2657
- });
2658
- }
2659
- function parseSlotCompositionOwner(input) {
2660
- if (!isRecord$2(input)) return err({ kind: "not-object" });
2661
- if (input.kind === "entrySlot") {
2662
- const entrySlotId = parseEntryBlockSlotId(input.entrySlotId);
2663
- if (!entrySlotId.ok) return err({
2664
- kind: "invalid-entry-slot-id",
2665
- error: entrySlotId.error
2666
- });
2667
- const contentEntryId = parseNonEmptyStringBrand(input.contentEntryId, unsafeAsEntrySlotContentEntryId);
2668
- if (!contentEntryId.ok) return err({
2669
- kind: "invalid-content-entry-id",
2670
- error: contentEntryId.error
2671
- });
2672
- return ok({
2673
- kind: "entrySlot",
2674
- entrySlotId: entrySlotId.value,
2675
- contentEntryId: contentEntryId.value
2676
- });
2677
- }
2678
- if (input.kind === "surfaceSlot") {
2679
- const surfaceSlotId = parsePageSurfaceSlotId(input.surfaceSlotId);
2680
- if (!surfaceSlotId.ok) return err({
2681
- kind: "invalid-surface-slot-id",
2682
- error: surfaceSlotId.error
2683
- });
2684
- const pageSurfaceId = parseEntrySlotPageSurfaceId(input.pageSurfaceId);
2685
- if (!pageSurfaceId.ok) return err({
2686
- kind: "invalid-page-surface-id",
2687
- error: pageSurfaceId.error
2688
- });
2689
- return ok({
2690
- kind: "surfaceSlot",
2691
- surfaceSlotId: surfaceSlotId.value,
2692
- pageSurfaceId: pageSurfaceId.value
2693
- });
2694
- }
2695
- return err({
2696
- kind: "unsupported-owner-kind",
2697
- ownerKind: input.kind
2698
- });
2699
- }
2700
- function parseEntrySlotBlockSnapshot(input) {
2701
- if (!isRecord$2(input)) return err("invalid");
2702
- const blockId = parseNonEmptyStringBrand(input.blockId, unsafeAsEntrySlotBlockId);
2703
- const orderIndex = parseBlockOrderIndex(input.orderIndex);
2704
- const blockKind = typeof input.blockKind === "string" && input.blockKind.trim() ? input.blockKind.trim() : null;
2705
- const purpose = input.purpose === undefined ? "content" : typeof input.purpose === "string" && input.purpose.trim() ? input.purpose.trim() : null;
2706
- const identifier = input.identifier === null || input.identifier === undefined ? null : typeof input.identifier === "string" ? input.identifier : undefined;
2707
- if (!blockId.ok || !orderIndex.ok || !blockKind || !purpose || identifier === undefined) return err("invalid");
2708
- if (input.kind === "published-block-content") {
2709
- const contentVersionId = parseNonEmptyStringBrand(input.contentVersionId, unsafeAsEntrySlotContentVersionId);
2710
- if (!contentVersionId.ok) return err("invalid");
2711
- return ok({
2712
- kind: "published-block-content",
2713
- blockId: blockId.value,
2714
- contentVersionId: contentVersionId.value,
2715
- identifier,
2716
- blockKind,
2717
- purpose,
2718
- orderIndex: orderIndex.value
2719
- });
2720
- }
2721
- if (input.kind === "draft-block-content") {
2722
- const contentVersionId = input.contentVersionId === null ? ok(null) : parseNonEmptyStringBrand(input.contentVersionId, unsafeAsEntrySlotContentVersionId);
2723
- if (!contentVersionId.ok) return err("invalid");
2724
- return ok({
2725
- kind: "draft-block-content",
2726
- blockId: blockId.value,
2727
- contentVersionId: contentVersionId.value,
2728
- identifier,
2729
- blockKind,
2730
- purpose,
2731
- orderIndex: orderIndex.value
2732
- });
2733
- }
2734
- if (input.kind === "missing-block-content" && (input.reason === "new-block" || input.reason === "deleted-content-version" || input.reason === "unpublished-block")) {
2735
- return ok({
2736
- kind: "missing-block-content",
2737
- blockId: blockId.value,
2738
- identifier,
2739
- blockKind,
2740
- purpose,
2741
- orderIndex: orderIndex.value,
2742
- reason: input.reason
2743
- });
2744
- }
2745
- return err("invalid");
2746
- }
2747
- function parseBlockOrderIndex(value) {
2748
- if (!Number.isInteger(value) || typeof value !== "number" || value < 0) return err("invalid");
2749
- return ok(unsafeAsEntrySlotBlockOrderIndex(value));
2750
- }
2751
- function blockContentVersionIdsForEntrySlotCompositionVersionData(versionData) {
2752
- return blockContentVersionIdsForSlotCompositionVersionData(versionData);
2753
- }
2754
- function blockContentVersionIdsForSlotCompositionVersionData(versionData) {
2755
- return versionData.blockSequence.flatMap((block) => block.kind === "missing-block-content" || block.contentVersionId === null ? [] : [block.contentVersionId]);
2756
- }
2757
- function planEntrySlotPublish(input) {
2758
- if (input.slot.kind === "orphaned") {
2759
- return {
2760
- kind: "warning-only",
2761
- slotKey: input.slot.slotKey,
2762
- warning: "orphaned-slot-hidden"
2763
- };
2764
- }
2765
- const missingBlocks = input.draftBlockSequence.filter((block) => block.kind === "missing-block-content").map((block) => block.blockId);
2766
- if (missingBlocks.length > 0) {
2767
- return {
2768
- kind: "blocked",
2769
- slotKey: input.slot.definition.slotKey,
2770
- reason: "missing-block-content",
2771
- blockIds: missingBlocks
2772
- };
2773
- }
2774
- return {
2775
- kind: "publishable",
2776
- slotKey: input.slot.definition.slotKey,
2777
- needsBlockContentPublish: input.draftBlockSequence.some((block) => block.kind === "draft-block-content")
2778
- };
2779
- }
2780
- function planEntrySlotDiscard(slot) {
2781
- return slot.kind === "orphaned" ? {
2782
- kind: "skip-hidden-orphan",
2783
- slotKey: slot.slotKey
2784
- } : {
2785
- kind: "discardable",
2786
- slotKey: slot.definition.slotKey
2787
- };
2788
- }
2789
- function parseSdkEntryBlocksPatch(blocks) {
2790
- if (blocks === undefined) return ok({ kind: "leave-unchanged" });
2791
- if (!isRecord$2(blocks)) return err({ kind: "invalid-blocks-object" });
2792
- const slots = [];
2793
- for (const [rawSlotKey, rawBlocks] of Object.entries(blocks)) {
2794
- const slotKey = parseSlotKey(rawSlotKey);
2795
- if (!slotKey.ok) return err({
2796
- kind: "invalid-slot-key",
2797
- key: rawSlotKey,
2798
- error: slotKey.error
2799
- });
2800
- if (!Array.isArray(rawBlocks)) return err({
2801
- kind: "invalid-slot-blocks",
2802
- slotKey: slotKey.value
2803
- });
2804
- if (rawBlocks.length === 0) {
2805
- slots.push({
2806
- kind: "clear-slot",
2807
- slotKey: slotKey.value
2808
- });
2809
- continue;
2810
- }
2811
- const parsedBlocks = [];
2812
- const blockIndexByIdentifier = new Map();
2813
- for (const [blockIndex, rawBlock] of rawBlocks.entries()) {
2814
- const parsed = parseSdkEntrySlotBlockInput(rawBlock, slotKey.value, blockIndex);
2815
- if (!parsed.ok) return parsed;
2816
- if (parsed.value.identifier) {
2817
- const firstBlockIndex = blockIndexByIdentifier.get(parsed.value.identifier);
2818
- if (firstBlockIndex !== undefined) {
2819
- return err({
2820
- kind: "duplicate-block-identifier",
2821
- slotKey: slotKey.value,
2822
- identifier: parsed.value.identifier,
2823
- firstBlockIndex,
2824
- blockIndex
2825
- });
2826
- }
2827
- blockIndexByIdentifier.set(parsed.value.identifier, blockIndex);
2828
- }
2829
- parsedBlocks.push(parsed.value);
2830
- }
2831
- slots.push({
2832
- kind: "replace-slot",
2833
- slotKey: slotKey.value,
2834
- blocks: parsedBlocks
2835
- });
2836
- }
2837
- return ok({
2838
- kind: "patch-slots",
2839
- slots
2840
- });
2841
- }
2842
- function parseSdkEntrySlotBlockInput(input, slotKey, blockIndex) {
2843
- if (!isRecord$2(input)) return err({
2844
- kind: "invalid-block",
2845
- slotKey,
2846
- blockIndex
2847
- });
2848
- const blockKind = typeof input.kind === "string" ? input.kind.trim() : "";
2849
- if (!blockKind || !isRecord$2(input.content)) return err({
2850
- kind: "invalid-block",
2851
- slotKey,
2852
- blockIndex
2853
- });
2854
- if (isTemplateOnlyBlockKind(blockKind)) {
2855
- return err({
2856
- kind: "template-only-block-kind",
2857
- slotKey,
2858
- blockIndex,
2859
- blockKind
2860
- });
2861
- }
2862
- const identifier = input.identifier === undefined || input.identifier === null ? null : typeof input.identifier === "string" ? input.identifier.trim() : undefined;
2863
- if (identifier === undefined || identifier === "") return err({
2864
- kind: "invalid-block",
2865
- slotKey,
2866
- blockIndex
2867
- });
2868
- return ok({
2869
- identifier,
2870
- kind: blockKind,
2871
- content: input.content
2872
- });
2873
- }
2874
- function describeSdkEntryBlocksPatchParseError(error) {
2875
- switch (error.kind) {
2876
- case "invalid-blocks-object": return "Entry slot blocks payload must be an object";
2877
- case "invalid-slot-key": return `Entry slot key is invalid: ${error.key}`;
2878
- case "invalid-slot-blocks": return `Entry slot "${error.slotKey}" blocks must be an array`;
2879
- case "invalid-block": return `Entry slot "${error.slotKey}" block at index ${error.blockIndex} is invalid`;
2880
- case "duplicate-block-identifier": return `Entry slot "${error.slotKey}" has duplicate block identifier "${error.identifier}" at index ${error.blockIndex}; first used at index ${error.firstBlockIndex}`;
2881
- case "template-only-block-kind": return `Entry slot "${error.slotKey}" block at index ${error.blockIndex} uses template-only block type: ${error.blockKind}`;
2882
- }
2883
- const exhaustive = error;
2884
- return exhaustive;
2885
- }
2886
- function parseSlotContainerOwner(input) {
2887
- if (!isRecord$2(input)) return err({ kind: "not-object" });
2888
- if (input.kind === "contentEntry") {
2889
- const contentEntryId = parseNonEmptyStringBrand(input.contentEntryId, unsafeAsEntrySlotContentEntryId);
2890
- if (!contentEntryId.ok) {
2891
- return err({
2892
- kind: "invalid-content-entry-id",
2893
- error: contentEntryId.error
2894
- });
2895
- }
2896
- return ok({
2897
- kind: "contentEntry",
2898
- contentEntryId: contentEntryId.value
2899
- });
2900
- }
2901
- if (input.kind === "pageSurface") {
2902
- const pageSurfaceId = parseEntrySlotPageSurfaceId(input.pageSurfaceId);
2903
- if (!pageSurfaceId.ok) {
2904
- return err({
2905
- kind: "invalid-page-surface-id",
2906
- error: pageSurfaceId.error
2907
- });
2908
- }
2909
- return ok({
2910
- kind: "pageSurface",
2911
- pageSurfaceId: pageSurfaceId.value
2912
- });
2913
- }
2914
- return err({
2915
- kind: "unsupported-owner-kind",
2916
- ownerKind: input.kind
2917
- });
2918
- }
2919
- function slotContainerOwnerToContentVersionOwner(owner) {
2920
- return {
2921
- kind: "entry",
2922
- contentEntryId: owner.contentEntryId
2923
- };
2924
- }
2925
- function slotContainerOwnerToEntrySlotLookup(owner) {
2926
- return { contentEntryId: owner.contentEntryId };
2927
- }
2928
- function planSlotCompositionMutation(input) {
2929
- switch (input.mutation.kind) {
2930
- case "leaveUnchanged": return {
2931
- kind: "noChange",
2932
- owner: input.owner,
2933
- slotKey: input.slotKey
2934
- };
2935
- case "replaceDraftComposition": return {
2936
- kind: "replaceDraftComposition",
2937
- owner: input.owner,
2938
- slotKey: input.slotKey,
2939
- blocks: input.mutation.blocks
2940
- };
2941
- case "publishDraftComposition": return {
2942
- kind: "publishDraftComposition",
2943
- owner: input.owner,
2944
- slotKey: input.slotKey,
2945
- draftVersionId: input.mutation.draftVersionId
2946
- };
2947
- default: return assertNever(input.mutation);
2948
- }
2949
- }
2950
- function planSlotCompositionTransfer(input) {
2951
- if (sameSlotCompositionOwner(input.from, input.to)) {
2952
- return {
2953
- kind: "noChange",
2954
- owner: input.to,
2955
- slotKey: input.slotKey
2956
- };
2957
- }
2958
- if (input.to.kind !== "surfaceSlot") {
2959
- return {
2960
- kind: "manualReviewRequired",
2961
- reason: {
2962
- kind: "target-is-not-surface-slot",
2963
- targetKind: input.to.kind
2964
- }
2965
- };
2966
- }
2967
- switch (input.from.kind) {
2968
- case "entrySlot": return {
2969
- kind: "copyEntrySlotToSurfaceSlot",
2970
- from: input.from,
2971
- to: input.to,
2972
- slotKey: input.slotKey
2973
- };
2974
- case "surfaceSlot": return {
2975
- kind: "forkSurfaceSlotComposition",
2976
- from: input.from,
2977
- to: input.to,
2978
- slotKey: input.slotKey
2979
- };
2980
- default: return assertNever(input.from);
2981
- }
2982
- }
2983
- function sameSlotCompositionOwner(left, right) {
2984
- switch (left.kind) {
2985
- case "entrySlot": return right.kind === "entrySlot" && right.entrySlotId === left.entrySlotId && right.contentEntryId === left.contentEntryId;
2986
- case "surfaceSlot": return right.kind === "surfaceSlot" && right.surfaceSlotId === left.surfaceSlotId && right.pageSurfaceId === left.pageSurfaceId;
2987
- default: return assertNever(left);
2988
- }
2989
- }
2990
- const ENTRY_SLOT_TEMPLATE_LIFECYCLE_DECISION = {
2991
- publicTemplateDefinitions: "effective-current",
2992
- previewTemplateDefinitions: "draft-current",
2993
- removedSlotData: "retained-hidden-until-slot-reintroduced"
2994
- };
2995
- function isRecord$2(value) {
2996
- return typeof value === "object" && value !== null && !Array.isArray(value);
2997
- }
2998
- function assertNever(value) {
2999
- throw new Error(`Unhandled entry-slot variant: ${JSON.stringify(value)}`);
3000
- }
3001
-
3002
- //#endregion
3003
- //#region ../content-model/src/templates/defaults.ts
3004
- const POST_EXCERPT_FALLBACK = fallbackBinding(fieldBinding("excerpt"), transformBinding(TEMPLATE_BINDING_TRANSFORMS.RICHTEXT_FIRST_PARAGRAPH, { input: fieldBinding("body") }));
3005
- const EVENT_SUBHEADLINE_FALLBACK = fallbackBinding(fieldBinding("summary"), transformBinding(TEMPLATE_BINDING_TRANSFORMS.RICHTEXT_FIRST_PARAGRAPH, { input: fieldBinding("body") }));
3006
- const ENTRY_TITLE_INLINE_TEXT = transformBinding(TEMPLATE_BINDING_TRANSFORMS.TEXT_INLINE_TEXT, { input: metaBinding("title") });
3007
- const POST_BODY_TEXT_BINDINGS = {
3008
- body: fieldBinding("body"),
3009
- alignment: literalBinding("left")
3010
- };
3011
- const EVENT_BODY_TEXT_BINDINGS = {
3012
- body: fieldBinding("body"),
3013
- alignment: literalBinding("left")
3014
- };
3015
- const TEAM_MEMBER_BODY_TEXT_BINDINGS = {
3016
- body: fieldBinding("bio"),
3017
- alignment: literalBinding("left")
3018
- };
3019
- const TESTIMONIAL_BODY_TEXT_BINDINGS = {
3020
- body: fieldBinding("body"),
3021
- alignment: literalBinding("center")
3022
- };
3023
- /**
3024
- * Built-in content type keys that intentionally ship without a default
3025
- * template — they use the block editor directly rather than a templated
3026
- * render. Single source of truth for the carve-out so callers and tests
3027
- * don't drift on which keys are "missing on purpose".
3028
- */
3029
- const CONTENT_TYPES_WITHOUT_DEFAULT_TEMPLATE = ["page", "product-category"];
3030
- const DEFAULT_TEMPLATE_DEFINITIONS = {
3031
- post: {
3032
- templateKey: "default",
3033
- name: "Blog post detail",
3034
- description: "Default article layout for blog posts.",
3035
- metadata: {},
3036
- blocks: [
3037
- {
3038
- blockKind: "block.hero",
3039
- scope: "entry",
3040
- content: { _sectionStyles: { background: { type: "image" } } },
3041
- bindings: {
3042
- eyebrow: literalBinding("Article"),
3043
- headline: metaBinding("title"),
3044
- headlineInline: ENTRY_TITLE_INLINE_TEXT,
3045
- subheadline: POST_EXCERPT_FALLBACK,
3046
- "_sectionStyles.background.image": fieldBinding("image")
3047
- }
3048
- },
3049
- {
3050
- blockKind: "block.body-text",
3051
- scope: "entry",
3052
- bindings: POST_BODY_TEXT_BINDINGS
3053
- },
3054
- {
3055
- blockKind: "block.cta-full",
3056
- scope: "template",
3057
- content: {
3058
- eyebrow: "Stay in the loop",
3059
- title: "Get the latest updates",
3060
- content: createRichTextDoc(["Subscribe to our newsletter to receive new articles and resources right in your inbox."]),
3061
- ctas: [{
3062
- label: "Subscribe now",
3063
- link: {
3064
- kind: "url",
3065
- href: "/contact"
3066
- }
3067
- }, {
3068
- label: "View all posts",
3069
- link: {
3070
- kind: "url",
3071
- href: "/blog"
3072
- }
3073
- }]
3074
- }
3075
- }
3076
- ]
3077
- },
3078
- event: {
3079
- templateKey: "default",
3080
- name: "Event detail",
3081
- description: "Standard detail page for events.",
3082
- metadata: {},
3083
- blocks: [
3084
- {
3085
- blockKind: "block.hero",
3086
- scope: "entry",
3087
- content: { _sectionStyles: { background: { type: "image" } } },
3088
- bindings: {
3089
- eyebrow: literalBinding("Event"),
3090
- headline: metaBinding("title"),
3091
- headlineInline: ENTRY_TITLE_INLINE_TEXT,
3092
- subheadline: EVENT_SUBHEADLINE_FALLBACK,
3093
- "_sectionStyles.background.image": fieldBinding("image")
3094
- }
3095
- },
3096
- {
3097
- blockKind: "block.event-details",
3098
- scope: "entry",
3099
- content: {
3100
- heading: "Event details",
3101
- showVenue: true,
3102
- showMap: true,
3103
- showOtherDates: true,
3104
- otherDatesLimit: "5",
3105
- showCapacity: true
3106
- }
3107
- },
3108
- {
3109
- blockKind: "block.body-text",
3110
- scope: "entry",
3111
- content: { body: createRichTextDoc([""]) },
3112
- bindings: EVENT_BODY_TEXT_BINDINGS
3113
- },
3114
- {
3115
- blockKind: SYSTEM_ENTRY_SLOT_BLOCK_KIND,
3116
- scope: "template",
3117
- content: {
3118
- slotKey: "main",
3119
- label: "Page content"
3120
- }
3121
- },
3122
- {
3123
- blockKind: "block.event-registration",
3124
- scope: "entry",
3125
- content: {
3126
- heading: "",
3127
- maxTickets: "5",
3128
- showVenue: true,
3129
- showCapacity: true,
3130
- buttonText: "Book your place",
3131
- buttonVariant: "primary"
3132
- },
3133
- bindings: {
3134
- occurrenceContext: { $bind: { from: "$root.occurrenceContext" } },
3135
- contentEntry: { $bind: { from: "$root.contentEntry" } }
3136
- }
3137
- }
3138
- ]
3139
- },
3140
- "team-member": {
3141
- templateKey: "default",
3142
- name: "Team member profile",
3143
- description: "Default layout for team member profile pages.",
3144
- metadata: {},
3145
- blocks: [{
3146
- blockKind: "block.hero",
3147
- scope: "entry",
3148
- bindings: {
3149
- eyebrow: literalBinding("About"),
3150
- headline: metaBinding("title"),
3151
- headlineInline: ENTRY_TITLE_INLINE_TEXT,
3152
- subheadline: fieldBinding("intro")
3153
- }
3154
- }, {
3155
- blockKind: "block.body-text",
3156
- scope: "entry",
3157
- content: { body: createRichTextDoc([""]) },
3158
- bindings: TEAM_MEMBER_BODY_TEXT_BINDINGS
3159
- }]
3160
- },
3161
- product: {
3162
- templateKey: "default",
3163
- name: "Product detail",
3164
- description: "Standard landing page for shop products.",
3165
- metadata: {},
3166
- blocks: [{
3167
- blockKind: "block.product-detail",
3168
- scope: "entry",
3169
- content: {
3170
- heading: "",
3171
- showSummary: true,
3172
- showBody: true,
3173
- addButtonText: "Add to cart",
3174
- emptyStateText: "Product unavailable."
3175
- }
3176
- }]
3177
- },
3178
- testimonial: {
3179
- templateKey: "default",
3180
- name: "Testimonial detail",
3181
- description: "Rich layout for individual testimonials.",
3182
- metadata: {},
3183
- blocks: [{
3184
- blockKind: "block.hero",
3185
- scope: "entry",
3186
- bindings: {
3187
- eyebrow: literalBinding("Customer story"),
3188
- headline: metaBinding("title"),
3189
- headlineInline: ENTRY_TITLE_INLINE_TEXT,
3190
- subheadline: fallbackBinding(fieldBinding("jobTitle"), fieldBinding("company"))
3191
- }
3192
- }, {
3193
- blockKind: "block.body-text",
3194
- scope: "entry",
3195
- bindings: TESTIMONIAL_BODY_TEXT_BINDINGS
3196
- }]
3197
- }
3198
- };
3199
- /** The legacy definition stays untouched; this alternative is selected only at creation. */
3200
- const EVENT_HEADER_TEMPLATE_DEFINITION = {
3201
- ...DEFAULT_TEMPLATE_DEFINITIONS.event,
3202
- blocks: [{
3203
- blockKind: "block.event-details",
3204
- scope: "entry",
3205
- content: {
3206
- heading: "",
3207
- showVenue: true,
3208
- showMap: true,
3209
- showOtherDates: true,
3210
- otherDatesLimit: "5",
3211
- showCapacity: true
3212
- }
3213
- }, ...DEFAULT_TEMPLATE_DEFINITIONS.event.blocks.slice(2)]
3214
- };
3215
- function getDefaultTemplateDefinition(contentTypeKey, defaults) {
3216
- if (contentTypeKey === "event" && defaults?.event === "event-header") return EVENT_HEADER_TEMPLATE_DEFINITION;
3217
- return DEFAULT_TEMPLATE_DEFINITIONS[contentTypeKey] ?? null;
3218
- }
3219
- const DEFAULT_TEMPLATE_KEYS = Object.freeze(Object.keys(DEFAULT_TEMPLATE_DEFINITIONS));
3220
-
3221
- //#endregion
3222
- //#region ../content-model/src/templates/bindingTypeCompatibility.ts
3223
- const SCALAR_BLOCK_FIELD_TYPES = [
3224
- "text",
3225
- "inlineText",
3226
- "number",
3227
- "slug",
3228
- "url",
3229
- "richText",
3230
- "media",
3231
- "file",
3232
- "boolean",
3233
- "select",
3234
- "reference",
3235
- "link",
3236
- "date",
3237
- "datetime"
3238
- ];
3239
- function isScalarBlockFieldType(type) {
3240
- return SCALAR_BLOCK_FIELD_TYPES.includes(type);
3241
- }
3242
- /**
3243
- * Compatibility matrix: content field type → compatible block field types
3244
- */
3245
- const CONTENT_TO_BLOCK_COMPATIBILITY = {
3246
- text: [
3247
- "text",
3248
- "inlineText",
3249
- "slug",
3250
- "url"
3251
- ],
3252
- textarea: ["text", "inlineText"],
3253
- number: [
3254
- "number",
3255
- "text",
3256
- "inlineText"
3257
- ],
3258
- date: [
3259
- "date",
3260
- "datetime",
3261
- "text",
3262
- "inlineText"
3263
- ],
3264
- url: [
3265
- "url",
3266
- "text",
3267
- "inlineText"
3268
- ],
3269
- richText: ["richText"],
3270
- media: ["media"],
3271
- file: ["file"],
3272
- boolean: ["boolean"],
3273
- select: [
3274
- "text",
3275
- "inlineText",
3276
- "select"
3277
- ],
3278
- reference: ["reference", "link"],
3279
- link: ["link", "reference"],
3280
- button: ["link"],
3281
- group: [],
3282
- repeater: ["repeater"],
3283
- datetime: [
3284
- "datetime",
3285
- "date",
3286
- "text",
3287
- "inlineText"
3288
- ]
3289
- };
3290
- /**
3291
- * Canonical meta-field registry.
3292
- *
3293
- * Single source of truth for "what entry meta fields exist and what content-field
3294
- * type they resolve to". Other modules derive their meta-related tables from
3295
- * this one to prevent the three-source-of-truth drift that previously existed
3296
- * across `META_FIELD_COMPATIBILITY` (this file), `getAvailableFieldPaths`
3297
- * (fieldPaths.ts), and `resolveMetaPathType` (bindingValidation.ts).
3298
- */
3299
- const META_FIELDS = {
3300
- title: "text",
3301
- slug: "text",
3302
- status: "text",
3303
- publishedAt: "date",
3304
- createdAt: "date",
3305
- updatedAt: "date"
3306
- };
3307
- /** Set of all known meta-field keys, derived from {@link META_FIELDS}. */
3308
- const META_FIELD_IDS = new Set(Object.keys(META_FIELDS));
3309
- /**
3310
- * Resolve a meta path to its content-field type. Returns `null` for unknown paths.
3311
- *
3312
- * Use this when validating bindings; the returned type participates in the
3313
- * standard `isCompatibleBinding` matrix. For target-aware compatibility
3314
- * (which adds aliases like `title → slug → url`), use
3315
- * {@link isCompatibleMetaBinding}.
3316
- */
3317
- function resolveMetaFieldType(path) {
3318
- return isMetaFieldPath(path) ? META_FIELDS[path] : null;
3319
- }
3320
- /** Type guard narrowing `string` to the union of declared meta-field paths. */
3321
- function isMetaFieldPath(path) {
3322
- return path in META_FIELDS;
3323
- }
3324
- /**
3325
- * Meta field → compatible block targets.
3326
- *
3327
- * Includes target-specific aliases that the generic field-type matrix
3328
- * doesn't (e.g. `title` is text but is also a valid `slug`/`url` source).
3329
- * Indexed by the same keys as {@link META_FIELDS} — adding a new meta field
3330
- * means updating both maps.
3331
- */
3332
- const META_FIELD_COMPATIBILITY = {
3333
- title: [
3334
- "text",
3335
- "inlineText",
3336
- "slug",
3337
- "url"
3338
- ],
3339
- slug: [
3340
- "text",
3341
- "inlineText",
3342
- "slug",
3343
- "url"
3344
- ],
3345
- status: [
3346
- "text",
3347
- "inlineText",
3348
- "select"
3349
- ],
3350
- publishedAt: [
3351
- "text",
3352
- "inlineText",
3353
- "date",
3354
- "datetime"
3355
- ],
3356
- createdAt: [
3357
- "text",
3358
- "inlineText",
3359
- "date",
3360
- "datetime"
3361
- ],
3362
- updatedAt: [
3363
- "text",
3364
- "inlineText",
3365
- "date",
3366
- "datetime"
3367
- ]
3368
- };
3369
- /**
3370
- * Nested path suffixes and their compatible types (for example media.url).
3371
- */
3372
- const NESTED_PATH_COMPATIBILITY = {
3373
- "media.url": [
3374
- "text",
3375
- "inlineText",
3376
- "url"
3377
- ],
3378
- "media.alt": ["text", "inlineText"],
3379
- "file.url": [
3380
- "text",
3381
- "inlineText",
3382
- "url"
3383
- ],
3384
- "file.filename": ["text", "inlineText"]
3385
- };
3386
- /**
3387
- * Check if a content field type is compatible with a block field type
3388
- */
3389
- function isCompatibleBinding(sourceType, targetType) {
3390
- if (targetType === "repeater") {
3391
- return sourceType === "repeater";
3392
- }
3393
- const compatibleTypes = CONTENT_TO_BLOCK_COMPATIBILITY[sourceType];
3394
- if (compatibleTypes) {
3395
- return compatibleTypes.includes(targetType);
3396
- }
3397
- return false;
3398
- }
3399
- /**
3400
- * Check if a meta field is compatible with a block field type
3401
- */
3402
- function isCompatibleMetaBinding(metaFieldName, targetType) {
3403
- if (targetType === "repeater") return false;
3404
- if (!isMetaFieldPath(metaFieldName)) return false;
3405
- const compatibleTypes = META_FIELD_COMPATIBILITY[metaFieldName];
3406
- return compatibleTypes.includes(targetType);
3407
- }
3408
- /**
3409
- * Check if a nested path is compatible with a block field type
3410
- */
3411
- function isCompatibleNestedPath(parentType, nestedSuffix, targetType) {
3412
- if (targetType === "repeater") return false;
3413
- const pathKey = `${parentType}.${nestedSuffix}`;
3414
- const compatibleTypes = NESTED_PATH_COMPATIBILITY[pathKey];
3415
- if (compatibleTypes) {
3416
- return compatibleTypes.includes(targetType);
3417
- }
3418
- return false;
3419
- }
3420
- /**
3421
- * Get compatible block field types for a given content field type
3422
- */
3423
- function getCompatibleBlockTypes(sourceType) {
3424
- return CONTENT_TO_BLOCK_COMPATIBILITY[sourceType] || [];
3425
- }
3426
- /**
3427
- * Get all compatible content field types for a given block field type (reverse lookup)
3428
- */
3429
- function getCompatibleContentTypes(targetType) {
3430
- const compatible = [];
3431
- for (const [contentType, blockTypes] of Object.entries(CONTENT_TO_BLOCK_COMPATIBILITY)) {
3432
- if (blockTypes.includes(targetType)) {
3433
- compatible.push(contentType);
3434
- }
3435
- }
3436
- return compatible;
3437
- }
3438
-
3439
- //#endregion
3440
- //#region ../content-model/src/templates/fieldPaths.ts
3441
- const META_FIELD_LABELS = {
3442
- title: "Title",
3443
- slug: "Slug",
3444
- status: "Status",
3445
- publishedAt: "Published Date",
3446
- createdAt: "Created Date",
3447
- updatedAt: "Updated Date"
3448
- };
3449
- /**
3450
- * Extract all available field paths from a content type schema
3451
- * for use in binding editor autocomplete.
3452
- */
3453
- function getAvailableFieldPaths(schema) {
3454
- const paths = [];
3455
- for (const [path, type] of Object.entries(META_FIELDS)) {
3456
- paths.push({
3457
- path,
3458
- label: META_FIELD_LABELS[path],
3459
- type,
3460
- category: "meta"
3461
- });
3462
- }
3463
- paths.push(...contentFieldPaths(schema.fields ?? []));
3464
- return paths;
3465
- }
3466
- function contentFieldPaths(fields, parentPath = "", parentLabel = "") {
3467
- const paths = [];
3468
- for (const field of fields) {
3469
- const basePath = parentPath ? `${parentPath}.${field.id}` : field.id;
3470
- const fieldLabel = field.label ?? field.id;
3471
- const baseLabel = parentLabel ? `${parentLabel} / ${fieldLabel}` : fieldLabel;
3472
- if (field.type === "group") {
3473
- paths.push(...contentFieldPaths(nestedFields(field), basePath, baseLabel));
3474
- continue;
3475
- }
3476
- if (field.type === "repeater") {
3477
- continue;
3478
- }
3479
- if (field.type === "richText") {
3480
- paths.push({
3481
- path: basePath,
3482
- label: baseLabel,
3483
- type: "richText",
3484
- category: "content"
3485
- });
3486
- continue;
3487
- }
3488
- if (field.type === "media") {
3489
- paths.push({
3490
- path: basePath,
3491
- label: baseLabel,
3492
- type: "media",
3493
- category: "content"
3494
- }, {
3495
- path: `${basePath}.url`,
3496
- label: `${baseLabel} (URL)`,
3497
- type: "media.url",
3498
- category: "content"
3499
- }, {
3500
- path: `${basePath}.alt`,
3501
- label: `${baseLabel} (Alt Text)`,
3502
- type: "media.alt",
3503
- category: "content"
3504
- });
3505
- continue;
3506
- }
3507
- if (field.type === "file") {
3508
- paths.push({
3509
- path: basePath,
3510
- label: baseLabel,
3511
- type: "file",
3512
- category: "content"
3513
- }, {
3514
- path: `${basePath}.url`,
3515
- label: `${baseLabel} (URL)`,
3516
- type: "file.url",
3517
- category: "content"
3518
- }, {
3519
- path: `${basePath}.filename`,
3520
- label: `${baseLabel} (Filename)`,
3521
- type: "file.filename",
3522
- category: "content"
3523
- });
3524
- continue;
3525
- }
3526
- paths.push({
3527
- path: basePath,
3528
- label: baseLabel,
3529
- type: field.type,
3530
- category: "content"
3531
- });
3532
- }
3533
- return paths;
3534
- }
3535
- function nestedFields(field) {
3536
- const record = field;
3537
- return record.fields ?? record.schema?.fields ?? [];
3538
- }
3539
- /**
3540
- * Get field type from path for validation
3541
- */
3542
- function getFieldTypeFromPath(schema, path) {
3543
- const descriptor = getFieldDescriptorFromPath(schema, path);
3544
- return descriptor?.kind === "scalar" ? descriptor.type : descriptor?.kind ?? null;
3545
- }
3546
- function getFieldDescriptorFromPath(schema, path) {
3547
- const paths = getAvailableFieldPaths(schema);
3548
- const match = paths.find((p) => p.path === path);
3549
- if (match) return {
3550
- kind: "scalar",
3551
- type: match.type
3552
- };
3553
- const field = findContentFieldByPath(schema.fields ?? [], path.split("."));
3554
- if (!field || field.type !== "repeater") return null;
3555
- return {
3556
- kind: "repeater",
3557
- shape: buildRepeaterFieldShape(field)
3558
- };
3559
- }
3560
- function findContentFieldByPath(fields, segments) {
3561
- if (segments.length === 0) return null;
3562
- const [head, ...tail] = segments;
3563
- const field = fields.find((candidate) => candidate.id === head);
3564
- if (!field) return null;
3565
- if (tail.length === 0) return field;
3566
- if (field.type !== "group") return null;
3567
- return findContentFieldByPath(nestedFields(field), tail);
3568
- }
3569
- function buildRepeaterFieldShape(field) {
3570
- const record = field;
3571
- if (record.polymorphic || record.itemTypes) {
3572
- return {
3573
- kind: "unsupported",
3574
- reason: "polymorphic_unsupported"
3575
- };
3576
- }
3577
- const fields = nestedFields(field);
3578
- if (fields.length === 0) {
3579
- return {
3580
- kind: "unsupported",
3581
- reason: "missing_item_schema"
3582
- };
3583
- }
3584
- const itemFields = [];
3585
- for (const child of fields) {
3586
- if (child.type === "repeater") {
3587
- return {
3588
- kind: "unsupported",
3589
- reason: "nested_repeater_unsupported"
3590
- };
3591
- }
3592
- if (!isRepeaterItemScalarType(child.type)) {
3593
- return {
3594
- kind: "unsupported",
3595
- reason: "unsupported_item_field"
3596
- };
3597
- }
3598
- itemFields.push({
3599
- id: child.id,
3600
- type: child.type,
3601
- required: Boolean(child.required)
3602
- });
3603
- }
3604
- return {
3605
- kind: "supported",
3606
- itemFields
3607
- };
3608
- }
3609
- function isRepeaterItemScalarType(type) {
3610
- switch (type) {
3611
- case "text":
3612
- case "textarea":
3613
- case "richText":
3614
- case "number":
3615
- case "date":
3616
- case "url":
3617
- case "media":
3618
- case "file":
3619
- case "boolean":
3620
- case "select":
3621
- case "reference":
3622
- case "link":
3623
- case "button":
3624
- case "datetime": return true;
3625
- case "group":
3626
- case "repeater": return false;
3627
- default: {
3628
- const _exhaustive = type;
3629
- return _exhaustive;
3630
- }
3631
- }
3632
- }
3633
- /**
3634
- * Validate if a path exists in the schema
3635
- */
3636
- function isValidFieldPath(schema, path) {
3637
- const paths = getAvailableFieldPaths(schema);
3638
- return paths.some((fieldPath) => fieldPath.path === path);
3639
- }
3640
- /**
3641
- * Get field paths compatible with a specific block field type
3642
- *
3643
- * Filters available paths to only show those that can be safely bound
3644
- * to the target field type without requiring transforms.
3645
- */
3646
- function getCompatibleFieldPaths(schema, targetFieldType) {
3647
- const allPaths = getAvailableFieldPaths(schema);
3648
- return allPaths.filter((fieldPath) => {
3649
- if (fieldPath.category === "meta") {
3650
- return isCompatibleMetaBinding(fieldPath.path, targetFieldType);
3651
- }
3652
- if (fieldPath.type.includes(".")) {
3653
- const parts = fieldPath.type.split(".");
3654
- const parentType = parts[0];
3655
- const nestedSuffix = parts[1];
3656
- if (parentType && nestedSuffix) {
3657
- return isCompatibleNestedPath(parentType, nestedSuffix, targetFieldType);
3658
- }
3659
- return false;
3660
- }
3661
- return isCompatibleBinding(fieldPath.type, targetFieldType);
3662
- });
3663
- }
3664
-
3665
- //#endregion
3666
- //#region ../content-model/src/templates/bindingValidation.ts
3667
- /**
3668
- * What each transform accepts and produces. The `satisfies` clause forces
3669
- * every `TemplateBindingTransformName` to have an entry — adding a new
3670
- * transform name without an IO declaration is a compile error rather than
3671
- * a runtime "unknown transform" error.
3672
- *
3673
- * Source-of-truth status:
3674
- * - The names live in three places (`TRANSFORMS` in blocks, `BINDING_TRANSFORMS`
3675
- * in sdk, `TEMPLATE_BINDING_TRANSFORMS` here) for package-boundary
3676
- * reasons — blocks doesn't depend on content-model. A cross-package
3677
- * equivalence test (`bindingValidation.test.ts`) pins the three sets
3678
- * so drift fails CI rather than going unnoticed.
3679
- * - The IO declaration lives only here; the runtime implementations in
3680
- * `blocks/bindings/index.ts:applyTransform` are checked against this
3681
- * table by the same cross-package test.
3682
- */
3683
- const TRANSFORM_IO = {
3684
- [TEMPLATE_BINDING_TRANSFORMS.RICHTEXT_FIRST_PARAGRAPH]: {
3685
- acceptsInputTypes: ["richText"],
3686
- outputType: "text"
3687
- },
3688
- [TEMPLATE_BINDING_TRANSFORMS.DATE_FORMAT_SHORT]: {
3689
- acceptsInputTypes: ["date", "datetime"],
3690
- outputType: "text"
3691
- },
3692
- [TEMPLATE_BINDING_TRANSFORMS.DATE_FORMAT_LONG]: {
3693
- acceptsInputTypes: ["date", "datetime"],
3694
- outputType: "text"
3695
- },
3696
- [TEMPLATE_BINDING_TRANSFORMS.TEXT_INLINE_TEXT]: {
3697
- acceptsInputTypes: [
3698
- "text",
3699
- "textarea",
3700
- "select"
3701
- ],
3702
- outputType: "text"
3703
- }
3704
- };
3705
- function getTransformIO(name) {
3706
- return name in TRANSFORM_IO ? TRANSFORM_IO[name] : undefined;
3707
- }
3708
- /**
3709
- * Resolve a meta path to its content-field type. Returns `null` for unknown
3710
- * meta paths. Delegates entirely to the canonical {@link resolveMetaFieldType}
3711
- * registry, which {@link getAvailableFieldPaths} also reads.
3712
- */
3713
- function resolveMetaPathType(path) {
3714
- return resolveMetaFieldType(path);
3715
- }
3716
- function isRecord$1(value) {
3717
- return typeof value === "object" && value !== null && !Array.isArray(value);
3718
- }
3719
- function isBindingDescriptor(value) {
3720
- if (!isRecord$1(value)) return false;
3721
- const source = value.source;
3722
- return source === "field" || source === "meta" || source === "literal" || source === "transform" || source === "fallback";
3723
- }
3724
- /**
3725
- * Detect a root-context (`{$bind: {from: '$root.X'}}`) binding.
3726
- *
3727
- * These are block-internal data-wiring bindings, not user-authored entry-field
3728
- * bindings. They appear on blocks like `block.event-registration` to plumb
3729
- * ambient context (occurrence, content entry root, portal token) from the
3730
- * renderer's data context into the block. The validator should NOT flag them
3731
- * as `invalidBindingKey` — they're never expected to live on the manifest's
3732
- * additionalFields list. Phase 9 will migrate this stored shape away.
3733
- *
3734
- * Matches:
3735
- * - `{ $bind: { from: '$root.foo' } }`
3736
- * - `{ $bind: { from: '$root.foo.bar' } }`
3737
- *
3738
- * Does NOT match field/meta-source bindings whose path happens to start with
3739
- * `$root` — those use a `source` discriminator, not the `$bind` envelope.
3740
- */
3741
- function isRootContextBinding(value) {
3742
- if (!isRecord$1(value)) return false;
3743
- const bind = value.$bind;
3744
- if (!isRecord$1(bind)) return false;
3745
- return typeof bind.from === "string" && bind.from.startsWith("$root.");
3746
- }
3747
- /**
3748
- * Check compatibility between a resolved source type (for example `'text'`,
3749
- * `'richText'`, or `'media.url'`) and a target block field type.
3750
- *
3751
- * Handles three shapes of source type:
3752
- * - plain content-field type (e.g. `'text'`)
3753
- * - dotted nested suffix (e.g. `'media.url'`)
3754
- * - meta-typed value (treated as plain content type, since meta types
3755
- * already map cleanly into the matrix)
3756
- */
3757
- function isSourceCompatibleWithTarget(sourceType, targetType) {
3758
- if (sourceType.includes(".")) {
3759
- const [parent, suffix] = sourceType.split(".", 2);
3760
- if (!parent || !suffix) return false;
3761
- return isCompatibleNestedPath(parent, suffix, targetType);
3762
- }
3763
- return isCompatibleBinding(sourceType, targetType);
3764
- }
3765
- function resolveFieldSource(path, context) {
3766
- const descriptor = getFieldDescriptorFromPath(context.schema, path);
3767
- if (descriptor === null) {
3768
- return {
3769
- kind: "invalidPath",
3770
- error: {
3771
- kind: "invalidFieldPath",
3772
- blockIdentifier: context.blockIdentifier,
3773
- fieldKey: context.fieldKey,
3774
- path
3775
- }
3776
- };
3777
- }
3778
- if (descriptor.kind === "repeater") {
3779
- return {
3780
- kind: "ok",
3781
- type: "repeater",
3782
- path,
3783
- shape: descriptor.shape
3784
- };
3785
- }
3786
- return {
3787
- kind: "ok",
3788
- type: descriptor.type,
3789
- path
3790
- };
3791
- }
3792
- function resolveMetaSource(path, context) {
3793
- const type = resolveMetaPathType(path);
3794
- if (type === null) {
3795
- return {
3796
- kind: "invalidPath",
3797
- error: {
3798
- kind: "invalidMetaPath",
3799
- blockIdentifier: context.blockIdentifier,
3800
- fieldKey: context.fieldKey,
3801
- path
3802
- }
3803
- };
3804
- }
3805
- return {
3806
- kind: "ok",
3807
- type,
3808
- path
3809
- };
3810
- }
3811
- /**
3812
- * Check a resolved source type against the target. Meta paths get the
3813
- * target-aware aliases (e.g. `title` → `slug`/`url`); plain field paths use
3814
- * the generic compatibility matrix.
3815
- */
3816
- function checkDirectCompatibility(resolved, context, isMetaSource) {
3817
- if (isMetaSource) {
3818
- if (isCompatibleMetaBinding(resolved.path, context.target.type)) return null;
3819
- return {
3820
- kind: "typeIncompatible",
3821
- blockIdentifier: context.blockIdentifier,
3822
- fieldKey: context.fieldKey,
3823
- sourceType: `meta.${resolved.path}`,
3824
- sourcePath: resolved.path,
3825
- targetType: context.target.type,
3826
- via: "direct"
3827
- };
3828
- }
3829
- if (context.target.type === "repeater") {
3830
- const mismatch = checkRepeaterCompatibility(resolved, context);
3831
- return mismatch;
3832
- }
3833
- if (resolved.type === "repeater") {
3834
- return {
3835
- kind: "typeIncompatible",
3836
- blockIdentifier: context.blockIdentifier,
3837
- fieldKey: context.fieldKey,
3838
- sourceType: describeResolvedSourceType(resolved),
3839
- sourcePath: resolved.path,
3840
- targetType: context.target.type,
3841
- via: "direct"
3842
- };
3843
- }
3844
- if (isSourceCompatibleWithTarget(resolved.type, context.target.type)) return null;
3845
- return {
3846
- kind: "typeIncompatible",
3847
- blockIdentifier: context.blockIdentifier,
3848
- fieldKey: context.fieldKey,
3849
- sourceType: resolved.type,
3850
- sourcePath: resolved.path,
3851
- targetType: context.target.type,
3852
- via: "direct"
3853
- };
3854
- }
3855
- function describeResolvedSourceType(resolved) {
3856
- if (resolved.type !== "repeater") return resolved.type;
3857
- return resolved.shape?.kind === "unsupported" ? `repeater(${resolved.shape.reason})` : "repeater";
3858
- }
3859
- function describeTargetType(target) {
3860
- return target.type;
3861
- }
3862
- function checkRepeaterCompatibility(resolved, context) {
3863
- if (context.target.type !== "repeater") return null;
3864
- const incompatible = (sourceType) => ({
3865
- kind: "typeIncompatible",
3866
- blockIdentifier: context.blockIdentifier,
3867
- fieldKey: context.fieldKey,
3868
- sourceType,
3869
- sourcePath: resolved.path,
3870
- targetType: describeTargetType(context.target),
3871
- via: "direct"
3872
- });
3873
- if (resolved.type !== "repeater" || !resolved.shape) {
3874
- return incompatible(describeResolvedSourceType(resolved));
3875
- }
3876
- const sourceShape = resolved.shape;
3877
- const targetShape = context.target.shape;
3878
- if (sourceShape.kind === "unsupported") {
3879
- return incompatible(`repeater(${sourceShape.reason})`);
3880
- }
3881
- if (targetShape.kind === "unsupported") {
3882
- return incompatible(`target-repeater(${targetShape.reason})`);
3883
- }
3884
- const sourceById = new Map(sourceShape.itemFields.map((field) => [field.id, field]));
3885
- for (const targetField of targetShape.itemFields) {
3886
- const sourceField = sourceById.get(targetField.id);
3887
- if (!sourceField) {
3888
- if (targetField.required) return incompatible("repeater(missing_required_target_field)");
3889
- continue;
3890
- }
3891
- if (targetField.required && !sourceField.required) {
3892
- return incompatible("repeater(requiredness_mismatch)");
3893
- }
3894
- if (!isScalarBlockFieldType(targetField.type) || !isSourceCompatibleWithTarget(sourceField.type, targetField.type)) {
3895
- return incompatible(`repeater(type_mismatch:${sourceField.id})`);
3896
- }
3897
- }
3898
- return null;
3899
- }
3900
- /**
3901
- * Validate one binding value against one target field.
3902
- *
3903
- * Handles every shape `TemplateBindingValue` can take:
3904
- * - descriptor (`field`/`meta`/`literal`/`transform`/`fallback`)
3905
- * - string shorthand (treated as a `field` path)
3906
- * - nested object (each key maps to a nested manifest target at
3907
- * `${parentKey}.${childKey}`; missing nested targets are reported as
3908
- * `invalidBindingKey` rather than silently inheriting the parent's type)
3909
- */
3910
- function validateBinding(binding, context) {
3911
- if (typeof binding === "string") {
3912
- const resolved = resolveFieldSource(binding, context);
3913
- if (resolved.kind === "invalidPath") return [resolved.error];
3914
- const mismatch = checkDirectCompatibility(resolved, context, false);
3915
- return mismatch ? [mismatch] : [];
3916
- }
3917
- if (!isRecord$1(binding)) {
3918
- return [{
3919
- kind: "typeIncompatible",
3920
- blockIdentifier: context.blockIdentifier,
3921
- fieldKey: context.fieldKey,
3922
- sourceType: typeof binding,
3923
- targetType: context.target.type,
3924
- via: "direct"
3925
- }];
3926
- }
3927
- if (isBindingDescriptor(binding)) {
3928
- return validateDescriptor(binding, context);
3929
- }
3930
- const errors = [];
3931
- for (const [childKey, child] of Object.entries(binding)) {
3932
- if (child === null || child === undefined) continue;
3933
- const nestedKey = `${context.fieldKey}.${childKey}`;
3934
- const nestedTarget = context.targetByKey.get(nestedKey);
3935
- if (!nestedTarget) {
3936
- errors.push({
3937
- kind: "invalidBindingKey",
3938
- blockIdentifier: context.blockIdentifier,
3939
- blockKind: context.blockKind,
3940
- fieldKey: nestedKey
3941
- });
3942
- continue;
3943
- }
3944
- errors.push(...validateBinding(child, {
3945
- ...context,
3946
- fieldKey: nestedKey,
3947
- target: nestedTarget
3948
- }));
3949
- }
3950
- return errors;
3951
- }
3952
- function validateDescriptor(binding, context) {
3953
- switch (binding.source) {
3954
- case "field": {
3955
- const resolved = resolveFieldSource(binding.path, context);
3956
- if (resolved.kind === "invalidPath") return [resolved.error];
3957
- const mismatch = checkDirectCompatibility(resolved, context, false);
3958
- return mismatch ? [mismatch] : [];
3959
- }
3960
- case "meta": {
3961
- const resolved = resolveMetaSource(binding.path, context);
3962
- if (resolved.kind === "invalidPath") return [resolved.error];
3963
- const mismatch = checkDirectCompatibility(resolved, context, true);
3964
- return mismatch ? [mismatch] : [];
3965
- }
3966
- case "literal": return [];
3967
- case "transform": return validateTransform(binding, context);
3968
- case "fallback": return (readTemplateFallbackOptions(binding) ?? []).flatMap((option) => validateBinding(option, { ...context }).map((err$1) => err$1.kind === "typeIncompatible" && err$1.via === "direct" ? {
3969
- ...err$1,
3970
- via: "fallbackOption"
3971
- } : err$1));
3972
- default: {
3973
- const _exhaustive = binding;
3974
- return _exhaustive;
3975
- }
3976
- }
3977
- }
3978
- function validateTransform(binding, context) {
3979
- const io = getTransformIO(binding.transform);
3980
- if (!io) {
3981
- return [{
3982
- kind: "unknownTransform",
3983
- blockIdentifier: context.blockIdentifier,
3984
- fieldKey: context.fieldKey,
3985
- transform: binding.transform
3986
- }];
3987
- }
3988
- const inputDescriptor = resolveTransformInput(binding);
3989
- if (inputDescriptor === null) {
3990
- return [{
3991
- kind: "typeIncompatible",
3992
- blockIdentifier: context.blockIdentifier,
3993
- fieldKey: context.fieldKey,
3994
- sourceType: "transform(no input)",
3995
- targetType: context.target.type,
3996
- via: "transformOutput"
3997
- }];
3998
- }
3999
- const resolved = inputDescriptor.source === "field" ? resolveFieldSource(inputDescriptor.path, context) : inputDescriptor.source === "meta" ? resolveMetaSource(inputDescriptor.path, context) : null;
4000
- if (resolved && resolved.kind === "invalidPath") {
4001
- return [resolved.error];
4002
- }
4003
- const errors = [];
4004
- if (resolved && resolved.kind === "ok") {
4005
- const inputType = resolved.type;
4006
- if (!io.acceptsInputTypes.includes(inputType)) {
4007
- errors.push({
4008
- kind: "transformInputIncompatible",
4009
- blockIdentifier: context.blockIdentifier,
4010
- fieldKey: context.fieldKey,
4011
- transform: binding.transform,
4012
- inputType,
4013
- acceptedTypes: io.acceptsInputTypes
4014
- });
4015
- }
4016
- }
4017
- if (!isCompatibleBinding(io.outputType, context.target.type)) {
4018
- errors.push({
4019
- kind: "typeIncompatible",
4020
- blockIdentifier: context.blockIdentifier,
4021
- fieldKey: context.fieldKey,
4022
- sourceType: io.outputType,
4023
- targetType: context.target.type,
4024
- via: "transformOutput"
4025
- });
4026
- }
4027
- return errors;
4028
- }
4029
- function resolveTransformInput(binding) {
4030
- if (binding.input !== undefined) {
4031
- if (typeof binding.input === "string") {
4032
- return {
4033
- source: "field",
4034
- path: binding.input
4035
- };
4036
- }
4037
- return binding.input;
4038
- }
4039
- if (typeof binding.path === "string") {
4040
- return {
4041
- source: "field",
4042
- path: binding.path
4043
- };
4044
- }
4045
- return null;
4046
- }
4047
- /**
4048
- * Validate every binding on one block and assert that every required manifest
4049
- * field has a binding present.
4050
- */
4051
- function validateBlockBindings(block, schema, manifest) {
4052
- const blockIdentifier = block.identifier ?? block.blockKind;
4053
- if (block.scope === "template") return [];
4054
- const errors = [];
4055
- const bindings = block.bindings ?? {};
4056
- const targetByKey = new Map(manifest.fields.map((target) => [target.id, target]));
4057
- for (const [fieldKey, binding] of Object.entries(bindings)) {
4058
- if (binding === null || binding === undefined) continue;
4059
- if (isRootContextBinding(binding)) continue;
4060
- const target = targetByKey.get(fieldKey);
4061
- if (!target) {
4062
- errors.push({
4063
- kind: "invalidBindingKey",
4064
- blockIdentifier,
4065
- blockKind: block.blockKind,
4066
- fieldKey
4067
- });
4068
- continue;
4069
- }
4070
- errors.push(...validateBinding(binding, {
4071
- blockIdentifier,
4072
- fieldKey,
4073
- target,
4074
- schema,
4075
- targetByKey,
4076
- blockKind: block.blockKind
4077
- }));
4078
- }
4079
- for (const target of manifest.fields) {
4080
- if (!target.required) continue;
4081
- const value = bindings[target.id];
4082
- if (value === undefined || value === null) {
4083
- errors.push({
4084
- kind: "requiredBindingMissing",
4085
- blockIdentifier,
4086
- blockKind: block.blockKind,
4087
- fieldKey: target.id
4088
- });
4089
- }
4090
- }
4091
- return errors;
4092
- }
4093
- /**
4094
- * Validate every block in a template definition.
4095
- *
4096
- * Unknown block kinds are surfaced as `unknownBlockKind` errors and that
4097
- * block is skipped for further checks (the rest of the template is still
4098
- * validated, so callers see all problems at once).
4099
- */
4100
- function validateTemplateBindings(template, schema, getManifest) {
4101
- const errors = [];
4102
- for (const [index, block] of template.blocks.entries()) {
4103
- const blockIdentifier = block.identifier ?? `${block.blockKind}#${index}`;
4104
- if (block.scope === "template") continue;
4105
- const manifest = getManifest(block.blockKind);
4106
- if (!manifest) {
4107
- errors.push({
4108
- kind: "unknownBlockKind",
4109
- blockIdentifier,
4110
- blockKind: block.blockKind
4111
- });
4112
- continue;
4113
- }
4114
- errors.push(...validateBlockBindings({
4115
- ...block,
4116
- identifier: blockIdentifier
4117
- }, schema, manifest));
4118
- }
4119
- return errors;
4120
- }
4121
- function matchBindingError(error, handlers) {
4122
- const handler = handlers[error.kind];
4123
- return handler(error);
4124
- }
4125
- /**
4126
- * Human-readable rendering of a validation error. Suitable for editor
4127
- * inline-error display and audit reports. Server-side error mappers should
4128
- * use the error's `kind` discriminator (via `matchBindingError`) instead
4129
- * of string-matching the message.
4130
- */
4131
- function bindingValidationErrorMessage(error) {
4132
- return matchBindingError(error, {
4133
- unknownBlockKind: (e) => `Unknown block kind "${e.blockKind}"`,
4134
- invalidBindingKey: (e) => `Binding key "${e.fieldKey}" is not a field of block "${e.blockKind}"`,
4135
- invalidFieldPath: (e) => `Field path "${e.path}" does not exist in the content type`,
4136
- invalidMetaPath: (e) => `Meta path "${e.path}" is not a known entry meta field`,
4137
- typeIncompatible: (e) => {
4138
- const ctx = e.via === "transformOutput" ? " (transform output)" : e.via === "fallbackOption" ? " (fallback option)" : "";
4139
- const pathSuffix = e.sourcePath ? ` (path "${e.sourcePath}")` : "";
4140
- return `Source type "${e.sourceType}" is not compatible with target field type "${e.targetType}"${pathSuffix}${ctx}`;
4141
- },
4142
- unknownTransform: (e) => `Unknown transform "${e.transform}"`,
4143
- transformInputIncompatible: (e) => `Transform "${e.transform}" does not accept input type "${e.inputType}" (accepts: ${e.acceptedTypes.join(", ")})`,
4144
- requiredBindingMissing: (e) => `Required field "${e.fieldKey}" of block "${e.blockKind}" has no binding`
4145
- });
4146
- }
4147
-
4148
- //#endregion
4149
- //#region ../content-model/src/templates/manifestAdapter.ts
4150
- const FIELD_TYPE_CLASSIFICATION = {
4151
- text: "leaf",
4152
- inlineText: "leaf",
4153
- number: "leaf",
4154
- slug: "leaf",
4155
- url: "leaf",
4156
- richText: "leaf",
4157
- media: "leaf",
4158
- file: "leaf",
4159
- boolean: "leaf",
4160
- select: "leaf",
4161
- reference: "leaf",
4162
- link: "leaf",
4163
- date: "leaf",
4164
- datetime: "leaf",
4165
- group: "composite",
4166
- modal: "composite",
4167
- tabGroup: "composite",
4168
- repeater: "whole",
4169
- presetOrCustom: "opaque",
4170
- contentTypeSelect: "opaque",
4171
- entryPicker: "leaf",
4172
- time: "opaque"
4173
- };
4174
- function classify(type) {
4175
- return FIELD_TYPE_CLASSIFICATION[type] ?? "unknown";
4176
- }
4177
- function leafToBlockFieldType(type) {
4178
- if (type === "entryPicker") return "reference";
4179
- return classify(type) === "leaf" ? type : null;
4180
- }
4181
- /**
4182
- * Recursively collect every bindable leaf in a field tree, emitting
4183
- * dot-notated ids. `prefix` carries the parent path during recursion.
4184
- */
4185
- function collectLeaves(fields, prefix, out) {
4186
- if (!fields) return;
4187
- for (const field of fields) {
4188
- const id = prefix ? `${prefix}.${field.id}` : field.id;
4189
- const cls = classify(field.type);
4190
- const leafType = leafToBlockFieldType(field.type);
4191
- if (leafType) {
4192
- out.push({
4193
- id,
4194
- type: leafType,
4195
- required: Boolean(field.required)
4196
- });
4197
- continue;
4198
- }
4199
- if (cls === "whole") {
4200
- out.push({
4201
- id,
4202
- type: "repeater",
4203
- required: Boolean(field.required),
4204
- shape: buildManifestRepeaterShape(field)
4205
- });
4206
- continue;
4207
- }
4208
- if (cls === "composite") {
4209
- const groupChildren = field.schema?.fields;
4210
- if (groupChildren) collectLeaves(groupChildren, id, out);
4211
- for (const tab of field.tabs ?? []) {
4212
- if (tab.fields) collectLeaves(tab.fields, id, out);
4213
- }
4214
- }
4215
- }
4216
- }
4217
- function buildManifestRepeaterShape(field) {
4218
- if (field.polymorphic || field.itemTypes) {
4219
- return {
4220
- kind: "unsupported",
4221
- reason: "polymorphic_unsupported"
4222
- };
4223
- }
4224
- const fields = field.repeatedItem?.fields ?? field.schema?.fields;
4225
- if (!fields || fields.length === 0) {
4226
- return {
4227
- kind: "unsupported",
4228
- reason: "missing_item_schema"
4229
- };
4230
- }
4231
- const itemFields = [];
4232
- for (const child of fields) {
4233
- if (child.type === "repeater") {
4234
- return {
4235
- kind: "unsupported",
4236
- reason: "nested_repeater_unsupported"
4237
- };
4238
- }
4239
- const type = leafToBlockFieldType(child.type);
4240
- if (!type) {
4241
- return {
4242
- kind: "unsupported",
4243
- reason: "unsupported_item_field"
4244
- };
4245
- }
4246
- itemFields.push({
4247
- id: child.id,
4248
- type,
4249
- required: Boolean(child.required)
4250
- });
4251
- }
4252
- return {
4253
- kind: "supported",
4254
- itemFields
4255
- };
4256
- }
4257
- /**
4258
- * Build the validator-facing shape from a block manifest. Composite fields
4259
- * are walked; their leaves emerge with dot-notated ids. Opaque/unknown
4260
- * fields are skipped.
4261
- *
4262
- * Accepts any value satisfying {@link AdaptableManifest}.
4263
- */
4264
- function manifestToValidationShape(manifest) {
4265
- const fields = [];
4266
- collectLeaves(manifest.fields, "", fields);
4267
- return {
4268
- id: manifest.name,
4269
- fields
4270
- };
4271
- }
4272
-
4273
- //#endregion
4274
- //#region ../content-model/src/templates/auditBindings.ts
4275
- /**
4276
- * Build a zero-initialised counter map keyed on every audit error variant.
4277
- *
4278
- * The literal *is* the source of truth: adding a new variant to
4279
- * `AuditFinding['error']` without a key here is a compile error. The
4280
- * `ALL_ERROR_KINDS` derived list and the runtime exhaustiveness in
4281
- * `emptyByKind` both flow from this single declaration.
4282
- */
4283
- function emptyByKind() {
4284
- const counters = {
4285
- malformedBindings: 0,
4286
- unknownBlockKind: 0,
4287
- invalidBindingKey: 0,
4288
- invalidFieldPath: 0,
4289
- invalidMetaPath: 0,
4290
- typeIncompatible: 0,
4291
- unknownTransform: 0,
4292
- transformInputIncompatible: 0,
4293
- requiredBindingMissing: 0
4294
- };
4295
- return counters;
4296
- }
4297
- const ALL_ERROR_KINDS = Object.keys(emptyByKind());
4298
- /**
4299
- * Audit one site's templates. Returns a report with every finding from
4300
- * every template, plus a per-`kind` summary. Pure function: no I/O, no side
4301
- * effects.
4302
- */
4303
- function auditSite(input, getManifest) {
4304
- const findings = input.contentTypes.flatMap((ct) => ct.templates.flatMap((template) => {
4305
- const errors = [...template.malformedBindings ?? [], ...validateTemplateBindings(template, ct.schema, getManifest)];
4306
- return errors.map((error) => ({
4307
- siteId: input.siteId,
4308
- contentTypeKey: ct.contentTypeKey,
4309
- templateKey: template.templateKey,
4310
- templateName: template.name,
4311
- error
4312
- }));
4313
- }));
4314
- const byKind = findings.reduce((counts, finding) => ({
4315
- ...counts,
4316
- [finding.error.kind]: counts[finding.error.kind] + 1
4317
- }), emptyByKind());
4318
- return {
4319
- siteId: input.siteId,
4320
- findings,
4321
- byKind
4322
- };
4323
- }
4324
- function auditSites(inputs, getManifest) {
4325
- const reports = inputs.map((input) => auditSite(input, getManifest));
4326
- const totalsByKind = emptyByKind();
4327
- let totalFindings = 0;
4328
- for (const report of reports) {
4329
- totalFindings += report.findings.length;
4330
- for (const kind of ALL_ERROR_KINDS) {
4331
- totalsByKind[kind] += report.byKind[kind];
4332
- }
4333
- }
4334
- return {
4335
- reports,
4336
- totalFindings,
4337
- totalsByKind
4338
- };
4339
- }
4340
- /**
4341
- * Render a `MultiSiteAuditReport` as a markdown document suitable for
4342
- * committing to `.project/audits/`. Stable ordering: sites by id, findings
4343
- * within a site by content-type → template → block-identifier → kind.
4344
- */
4345
- function formatAuditReportMarkdown(report, options) {
4346
- const lines = [];
4347
- const iso = options.generatedAt.toISOString();
4348
- lines.push(`# Template binding audit — ${options.environment}`);
4349
- lines.push("");
4350
- lines.push(`Generated: ${iso}`);
4351
- lines.push(`Total findings: **${report.totalFindings}**`);
4352
- lines.push("");
4353
- if (report.totalFindings === 0) {
4354
- lines.push("No binding violations found. ✅");
4355
- lines.push("");
4356
- return lines.join("\n");
4357
- }
4358
- lines.push("## Summary by error kind");
4359
- lines.push("");
4360
- lines.push("| Kind | Count |");
4361
- lines.push("| --- | ---: |");
4362
- for (const kind of ALL_ERROR_KINDS) {
4363
- const count = report.totalsByKind[kind];
4364
- if (count > 0) lines.push(`| \`${kind}\` | ${count} |`);
4365
- }
4366
- lines.push("");
4367
- for (const site of [...report.reports].sort((a, b) => a.siteId.localeCompare(b.siteId))) {
4368
- if (site.findings.length === 0) continue;
4369
- lines.push(`## Site \`${site.siteId}\` (${site.findings.length} finding${site.findings.length === 1 ? "" : "s"})`);
4370
- lines.push("");
4371
- const grouped = groupFindings(site.findings);
4372
- for (const [contentTypeKey, templates] of grouped) {
4373
- lines.push(`### Content type \`${contentTypeKey}\``);
4374
- lines.push("");
4375
- for (const [templateKey, findings] of templates) {
4376
- const templateName = findings[0]?.templateName ?? "";
4377
- lines.push(`**Template \`${templateKey}\`** — ${templateName}`);
4378
- lines.push("");
4379
- lines.push("| Block | Field | Kind | Detail |");
4380
- lines.push("| --- | --- | --- | --- |");
4381
- for (const finding of findings) {
4382
- const err$1 = finding.error;
4383
- const blockId = "blockIdentifier" in err$1 ? err$1.blockIdentifier : "-";
4384
- const fieldKey = "fieldKey" in err$1 ? err$1.fieldKey : "-";
4385
- const detail = describeError(err$1).replace(/\|/g, "\\|");
4386
- lines.push(`| \`${blockId}\` | \`${fieldKey}\` | \`${err$1.kind}\` | ${detail} |`);
4387
- }
4388
- lines.push("");
4389
- }
4390
- }
4391
- }
4392
- return lines.join("\n");
4393
- }
4394
- /**
4395
- * Group findings by content type → template, preserving stable ordering
4396
- * inside each group. Pure helper for the formatter; exposed for tests.
4397
- */
4398
- function groupFindings(findings) {
4399
- const byContentType = new Map();
4400
- for (const finding of findings) {
4401
- const inner = byContentType.get(finding.contentTypeKey) ?? new Map();
4402
- const list = inner.get(finding.templateKey) ?? [];
4403
- list.push(finding);
4404
- inner.set(finding.templateKey, list);
4405
- byContentType.set(finding.contentTypeKey, inner);
4406
- }
4407
- const ctEntries = [...byContentType.entries()].sort((a, b) => a[0].localeCompare(b[0]));
4408
- return ctEntries.map(([ctKey, tplMap]) => {
4409
- const tplEntries = [...tplMap.entries()].sort((a, b) => a[0].localeCompare(b[0]));
4410
- return [ctKey, tplEntries.map(([tplKey, list]) => [tplKey, [...list].sort((a, b) => "blockIdentifier" in a.error && "blockIdentifier" in b.error ? a.error.blockIdentifier.localeCompare(b.error.blockIdentifier) || a.error.kind.localeCompare(b.error.kind) : a.error.kind.localeCompare(b.error.kind))])];
4411
- });
4412
- }
4413
- /**
4414
- * Audit-report rendering of a validation error.
4415
- *
4416
- * Stored parse failures stay audit-specific. Semantic errors delegate to
4417
- * the canonical `bindingValidationErrorMessage` so a single
4418
- * source of truth covers both editor inline-display and audit report
4419
- * surfaces — adding a new error variant updates both consumers from one
4420
- * exhaustive switch.
4421
- */
4422
- const describeError = (error) => error.kind === "malformedBindings" ? `Malformed stored bindings: ${error.message}` : bindingValidationErrorMessage(error);
4423
-
4424
- //#endregion
4425
- //#region ../content-model/src/templates/editorState.ts
4426
- function isRecord(value) {
4427
- return !!value && typeof value === "object" && !Array.isArray(value);
4428
- }
4429
- function isTemplateEditorBindingDescriptor(value) {
4430
- return typeof value === "string" || isRecord(value);
4431
- }
4432
- function normalizeTemplateEditorBindings(bindings) {
4433
- const next = {};
4434
- for (const [key, value] of Object.entries(bindings ?? {})) {
4435
- if (!isTemplateEditorBindingDescriptor(value)) continue;
4436
- next[key] = value;
4437
- }
4438
- return next;
4439
- }
4440
- function serializeTemplateEditorBindingsJson(bindings) {
4441
- return JSON.stringify(bindings, null, 2);
4442
- }
4443
- function parseTemplateEditorBindingsJson(jsonValue) {
4444
- try {
4445
- const parsed = JSON.parse(jsonValue);
4446
- if (!isRecord(parsed)) {
4447
- return {
4448
- ok: false,
4449
- message: "Bindings must be an object"
4450
- };
4451
- }
4452
- const bindings = normalizeTemplateEditorBindings(parsed);
4453
- if (Object.keys(bindings).length !== Object.keys(parsed).length) {
4454
- return {
4455
- ok: false,
4456
- message: "Binding values must be strings or objects"
4457
- };
4458
- }
4459
- return {
4460
- ok: true,
4461
- bindings
4462
- };
4463
- } catch (error) {
4464
- return {
4465
- ok: false,
4466
- message: error instanceof Error ? error.message : "Invalid JSON"
4467
- };
4468
- }
4469
- }
4470
- function mergeTemplateBindingEdits(currentBindings, editedBindings) {
4471
- return {
4472
- ...currentBindings,
4473
- ...editedBindings
4474
- };
4475
- }
4476
- function setTemplateEditorBinding(bindings, propId, binding) {
4477
- return {
4478
- ...bindings,
4479
- [propId]: binding
4480
- };
4481
- }
4482
- function removeTemplateEditorBinding(bindings, propId) {
4483
- const next = { ...bindings };
4484
- delete next[propId];
4485
- return next;
4486
- }
4487
- function createEntryTemplateBindingRecords(blocks) {
4488
- const next = {};
4489
- for (const block of blocks) {
4490
- if (block.scope !== "entry") continue;
4491
- next[block.id] = normalizeTemplateEditorBindings(block.bindings);
4492
- }
4493
- return next;
4494
- }
4495
- function setTemplateBlockBinding(allBindings, blockId, propId, binding) {
4496
- return {
4497
- ...allBindings,
4498
- [blockId]: setTemplateEditorBinding(allBindings[blockId] ?? {}, propId, binding)
4499
- };
4500
- }
4501
- function removeTemplateBlockBinding(allBindings, blockId, propId) {
4502
- return {
4503
- ...allBindings,
4504
- [blockId]: removeTemplateEditorBinding(allBindings[blockId] ?? {}, propId)
4505
- };
4506
- }
4507
-
4508
- //#endregion
4509
- //#region ../content-model/src/entry-slots/serializeAllowedBlocks.ts
4510
- function serializeEntrySlotAllowedBlocks(definition) {
4511
- switch (definition.allowedBlocks.kind) {
4512
- case "default": return {
4513
- kind: "default",
4514
- blockKinds: [...definition.allowedBlocks.blockKinds]
4515
- };
4516
- case "restricted": return {
4517
- kind: "restricted",
4518
- blockKinds: [...definition.allowedBlocks.blockKinds]
4519
- };
4520
- case "none": return {
4521
- kind: "none",
4522
- blockKinds: []
4523
- };
4524
- }
4525
- }
4526
-
4527
- //#endregion
4528
- //#region ../content-model/src/entry-slots/sdkBlocks.ts
4529
- const defaultContentSchema = z.record(z.string(), z.unknown());
4530
- function createSdkEntrySlotBlockInputSchema(contentSchema = defaultContentSchema) {
4531
- return z.object({
4532
- identifier: z.string().nullable().optional(),
4533
- kind: z.string().min(1, "Block kind is required"),
4534
- content: contentSchema
4535
- });
4536
- }
4537
- function createSdkEntrySlotBlocksInputSchema(contentSchema) {
4538
- return z.record(z.string(), z.array(createSdkEntrySlotBlockInputSchema(contentSchema)));
4539
- }
4540
- const sdkEntrySlotBlockInputSchema = createSdkEntrySlotBlockInputSchema();
4541
- const sdkEntrySlotBlocksInputSchema = createSdkEntrySlotBlocksInputSchema();
4542
-
4543
- //#endregion
4544
- //#region src/commands/eventUpsertInputSchema.ts
4545
- const eventScheduleInputSchema = z.object({
4546
- recurrenceRule: z.string().nullable().optional(),
4547
- startDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional(),
4548
- defaultStartTime: z.string().min(1).optional(),
4549
- durationMinutes: z.number().int().positive().optional(),
4550
- startsAt: z.string().min(1).optional(),
4551
- endsAt: z.string().min(1).optional()
4552
- }).transform((schedule, ctx) => {
4553
- const result = classifySdkEventSchedule(schedule, { requireCanonicalFields: true });
4554
- if (!result.ok) {
4555
- result.issues.forEach((issue) => ctx.addIssue({
4556
- code: "custom",
4557
- path: [...issue.path],
4558
- message: issue.message
4559
- }));
4560
- return z.NEVER;
4561
- }
4562
- if (result.kind === "start-end") {
4563
- return {
4564
- startsAt: result.startsAtIso,
4565
- endsAt: result.endsAtIso
4566
- };
4567
- }
4568
- if (result.kind === "start-duration") {
4569
- return {
4570
- startsAt: result.startsAtIso,
4571
- durationMinutes: (Date.parse(result.endsAtIso) - Date.parse(result.startsAtIso)) / 6e4
4572
- };
4573
- }
4574
- return result.canonical;
4575
- });
4576
- function classifiedSchema(classify$1) {
4577
- return z.unknown().transform((input, ctx) => {
4578
- const result = classify$1(input);
4579
- if (result.ok) return result.value;
4580
- result.issues.forEach((issue) => ctx.addIssue({
4581
- code: "custom",
4582
- path: issue.path.map(String),
4583
- message: issue.message
4584
- }));
4585
- return z.NEVER;
4586
- });
4587
- }
4588
- const eventBookingOfferInputSchema = classifiedSchema((input) => {
4589
- const result = classifySdkEventBookingOffer(input);
4590
- return result.ok && result.bookingOffer ? {
4591
- ok: true,
4592
- value: result.bookingOffer
4593
- } : result.ok ? {
4594
- ok: false,
4595
- issues: [{
4596
- path: [],
4597
- message: "Event bookingOffer is required"
4598
- }]
4599
- } : result;
4600
- });
4601
- const eventRunCommonInputSchema = z.object({
4602
- identifier: z.string().min(1),
4603
- eventRef: z.string().min(1),
4604
- status: sdkEventUpsertOptionalFieldSchemas.status,
4605
- visibility: sdkEventUpsertOptionalFieldSchemas.visibility,
4606
- waitlistMode: sdkEventUpsertOptionalFieldSchemas.waitlistMode,
4607
- occurrences: sdkEventUpsertOptionalFieldSchemas.occurrences.unwrap(),
4608
- schedule: eventScheduleInputSchema.optional(),
4609
- bookings: sdkEventUpsertOptionalFieldSchemas.bookings,
4610
- attendeeMigration: sdkEventUpsertOptionalFieldSchemas.attendeeMigration,
4611
- bookingOffer: eventBookingOfferInputSchema.optional(),
4612
- capacity: sdkEventUpsertOptionalFieldSchemas.capacity,
4613
- venueRef: z.string().nullable().optional(),
4614
- settings: z.record(z.string(), z.unknown()).optional(),
4615
- tags: z.array(z.string()).optional()
4616
- }).strict();
4617
- const eventRunInputSchema = z.discriminatedUnion("bookingScope", [eventRunCommonInputSchema.extend({ bookingScope: z.literal("single_occurrence") }).strict(), eventRunCommonInputSchema.extend({
4618
- bookingScope: z.literal("whole_series"),
4619
- name: z.string().nullable().optional()
4620
- }).strict()]);
4621
- const eventUpsertInputSchema = z.object({
4622
- identifier: z.string().min(1).optional(),
4623
- courseBooking: sdkCourseBookingSettingsSchema.optional(),
4624
- title: z.string().min(1, "title is required"),
4625
- categoryRef: z.string().nullable().optional(),
4626
- slug: z.string().min(1).optional(),
4627
- content: z.record(z.string(), z.unknown()).optional(),
4628
- blocks: sdkEntrySlotBlocksInputSchema.optional(),
4629
- preset: z.enum(EVENT_PRESET_VALUES),
4630
- runRefs: z.tuple([z.string().min(1)], z.string().min(1)),
4631
- runs: z.tuple([eventRunInputSchema], eventRunInputSchema)
4632
- }).strict().superRefine((input, ctx) => input.runs.forEach((run, index) => {
4633
- if (new Set(run.occurrences.map((item) => item.timeZone)).size <= 1) return;
4634
- ctx.addIssue({
4635
- code: "custom",
4636
- path: [
4637
- "runs",
4638
- index,
4639
- "occurrences"
4640
- ],
4641
- message: "all occurrences must use the same timeZone"
4642
- });
4643
- }));
4644
-
4645
- //#endregion
4646
- export { findUnfilledSentinels as i, buildEntryScaffold as n, validateEntryInstance as r, eventUpsertInputSchema as t };