@lacecms/content 0.1.0-rc1 → 0.1.0-rc3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/blocks/built-ins.d.ts +627 -0
  2. package/dist/blocks/built-ins.d.ts.map +1 -0
  3. package/dist/blocks/built-ins.js +337 -0
  4. package/dist/blocks/built-ins.js.map +1 -0
  5. package/dist/blocks/definition.d.ts +21 -0
  6. package/dist/blocks/definition.d.ts.map +1 -0
  7. package/dist/blocks/definition.js +159 -0
  8. package/dist/blocks/definition.js.map +1 -0
  9. package/dist/blocks/errors.d.ts +7 -0
  10. package/dist/blocks/errors.d.ts.map +1 -0
  11. package/dist/blocks/errors.js +12 -0
  12. package/dist/blocks/errors.js.map +1 -0
  13. package/dist/blocks/fields.d.ts +3 -0
  14. package/dist/blocks/fields.d.ts.map +1 -0
  15. package/dist/blocks/fields.js +38 -0
  16. package/dist/blocks/fields.js.map +1 -0
  17. package/dist/blocks/gallery-migration.d.ts +8 -0
  18. package/dist/blocks/gallery-migration.d.ts.map +1 -0
  19. package/dist/blocks/gallery-migration.js +28 -0
  20. package/dist/blocks/gallery-migration.js.map +1 -0
  21. package/dist/blocks/grammar.d.ts +23 -0
  22. package/dist/blocks/grammar.d.ts.map +1 -0
  23. package/dist/blocks/grammar.js +38 -0
  24. package/dist/blocks/grammar.js.map +1 -0
  25. package/dist/blocks/list-layout.d.ts +121 -0
  26. package/dist/blocks/list-layout.d.ts.map +1 -0
  27. package/dist/blocks/list-layout.js +175 -0
  28. package/dist/blocks/list-layout.js.map +1 -0
  29. package/dist/blocks/migration.d.ts +26 -0
  30. package/dist/blocks/migration.d.ts.map +1 -0
  31. package/dist/blocks/migration.js +126 -0
  32. package/dist/blocks/migration.js.map +1 -0
  33. package/dist/blocks/registry.d.ts +6 -0
  34. package/dist/blocks/registry.d.ts.map +1 -0
  35. package/dist/blocks/registry.js +23 -0
  36. package/dist/blocks/registry.js.map +1 -0
  37. package/dist/blocks/settings.d.ts +9 -0
  38. package/dist/blocks/settings.d.ts.map +1 -0
  39. package/dist/blocks/settings.js +63 -0
  40. package/dist/blocks/settings.js.map +1 -0
  41. package/dist/blocks/types.d.ts +77 -0
  42. package/dist/blocks/types.d.ts.map +1 -0
  43. package/dist/blocks/types.js +2 -0
  44. package/dist/blocks/types.js.map +1 -0
  45. package/dist/entries/aggregate.d.ts +80 -0
  46. package/dist/entries/aggregate.d.ts.map +1 -0
  47. package/dist/entries/aggregate.js +166 -0
  48. package/dist/entries/aggregate.js.map +1 -0
  49. package/dist/entries/canonical-json.d.ts +14 -0
  50. package/dist/entries/canonical-json.d.ts.map +1 -0
  51. package/dist/entries/canonical-json.js +43 -0
  52. package/dist/entries/canonical-json.js.map +1 -0
  53. package/dist/{list-query-policy.d.ts → entries/list-query-policy.d.ts} +3 -0
  54. package/dist/entries/list-query-policy.d.ts.map +1 -0
  55. package/dist/{list-query-policy.js → entries/list-query-policy.js} +9 -0
  56. package/dist/entries/list-query-policy.js.map +1 -0
  57. package/dist/fields/builders.d.ts +35 -0
  58. package/dist/fields/builders.d.ts.map +1 -0
  59. package/dist/fields/builders.js +15 -0
  60. package/dist/fields/builders.js.map +1 -0
  61. package/dist/fields/capabilities.d.ts +157 -0
  62. package/dist/fields/capabilities.d.ts.map +1 -0
  63. package/dist/fields/capabilities.js +131 -0
  64. package/dist/fields/capabilities.js.map +1 -0
  65. package/dist/fields/definitions.d.ts +255 -0
  66. package/dist/fields/definitions.d.ts.map +1 -0
  67. package/dist/fields/definitions.js +42 -0
  68. package/dist/fields/definitions.js.map +1 -0
  69. package/dist/fields/descriptor-record.d.ts +3 -0
  70. package/dist/fields/descriptor-record.d.ts.map +1 -0
  71. package/dist/fields/descriptor-record.js +18 -0
  72. package/dist/fields/descriptor-record.js.map +1 -0
  73. package/dist/fields/filter-values.d.ts +34 -0
  74. package/dist/fields/filter-values.d.ts.map +1 -0
  75. package/dist/fields/filter-values.js +109 -0
  76. package/dist/fields/filter-values.js.map +1 -0
  77. package/dist/{internal-links.d.ts → fields/internal-link-tokens.d.ts} +1 -1
  78. package/dist/fields/internal-link-tokens.d.ts.map +1 -0
  79. package/dist/{internal-links.js → fields/internal-link-tokens.js} +8 -3
  80. package/dist/fields/internal-link-tokens.js.map +1 -0
  81. package/dist/fields/layout.d.ts +6 -0
  82. package/dist/fields/layout.d.ts.map +1 -0
  83. package/dist/fields/layout.js +45 -0
  84. package/dist/fields/layout.js.map +1 -0
  85. package/dist/fields/metadata.d.ts +4 -0
  86. package/dist/fields/metadata.d.ts.map +1 -0
  87. package/dist/fields/metadata.js +6 -0
  88. package/dist/fields/metadata.js.map +1 -0
  89. package/dist/fields/normalization.d.ts +5 -0
  90. package/dist/fields/normalization.d.ts.map +1 -0
  91. package/dist/fields/normalization.js +148 -0
  92. package/dist/fields/normalization.js.map +1 -0
  93. package/dist/fields/rich-text.d.ts +56 -0
  94. package/dist/fields/rich-text.d.ts.map +1 -0
  95. package/dist/fields/rich-text.js +169 -0
  96. package/dist/fields/rich-text.js.map +1 -0
  97. package/dist/fields/scalar-builders.d.ts +30 -0
  98. package/dist/fields/scalar-builders.d.ts.map +1 -0
  99. package/dist/fields/scalar-builders.js +310 -0
  100. package/dist/fields/scalar-builders.js.map +1 -0
  101. package/dist/{schema-path.d.ts → fields/schema-path.d.ts} +1 -1
  102. package/dist/fields/schema-path.d.ts.map +1 -0
  103. package/dist/{schema-path.js → fields/schema-path.js} +5 -5
  104. package/dist/fields/schema-path.js.map +1 -0
  105. package/dist/fields/validation.d.ts +40 -0
  106. package/dist/fields/validation.d.ts.map +1 -0
  107. package/dist/fields/validation.js +203 -0
  108. package/dist/fields/validation.js.map +1 -0
  109. package/dist/{video-embeds.d.ts → fields/video-embeds.d.ts} +2 -0
  110. package/dist/fields/video-embeds.d.ts.map +1 -0
  111. package/dist/{video-embeds.js → fields/video-embeds.js} +2 -0
  112. package/dist/fields/video-embeds.js.map +1 -0
  113. package/dist/fields/visibility.d.ts +12 -0
  114. package/dist/fields/visibility.d.ts.map +1 -0
  115. package/dist/fields/visibility.js +69 -0
  116. package/dist/fields/visibility.js.map +1 -0
  117. package/dist/index.d.ts +45 -1338
  118. package/dist/index.d.ts.map +1 -1
  119. package/dist/index.js +37 -2330
  120. package/dist/index.js.map +1 -1
  121. package/dist/references/field-paths.d.ts +6 -0
  122. package/dist/references/field-paths.d.ts.map +1 -0
  123. package/dist/references/field-paths.js +19 -0
  124. package/dist/references/field-paths.js.map +1 -0
  125. package/dist/references/internal-links.d.ts +30 -0
  126. package/dist/references/internal-links.d.ts.map +1 -0
  127. package/dist/references/internal-links.js +54 -0
  128. package/dist/references/internal-links.js.map +1 -0
  129. package/dist/references/media.d.ts +23 -0
  130. package/dist/references/media.d.ts.map +1 -0
  131. package/dist/references/media.js +76 -0
  132. package/dist/references/media.js.map +1 -0
  133. package/dist/shared/errors.d.ts +34 -0
  134. package/dist/shared/errors.d.ts.map +1 -0
  135. package/dist/shared/errors.js +61 -0
  136. package/dist/shared/errors.js.map +1 -0
  137. package/dist/shared/identifiers.d.ts +38 -0
  138. package/dist/shared/identifiers.d.ts.map +1 -0
  139. package/dist/shared/identifiers.js +80 -0
  140. package/dist/shared/identifiers.js.map +1 -0
  141. package/dist/shared/json.d.ts +20 -0
  142. package/dist/shared/json.d.ts.map +1 -0
  143. package/dist/shared/json.js +155 -0
  144. package/dist/shared/json.js.map +1 -0
  145. package/dist/shared/objects.d.ts +7 -0
  146. package/dist/shared/objects.d.ts.map +1 -0
  147. package/dist/shared/objects.js +20 -0
  148. package/dist/shared/objects.js.map +1 -0
  149. package/package.json +1 -1
  150. package/dist/internal-links.d.ts.map +0 -1
  151. package/dist/internal-links.js.map +0 -1
  152. package/dist/list-query-policy.d.ts.map +0 -1
  153. package/dist/list-query-policy.js.map +0 -1
  154. package/dist/schema-path.d.ts.map +0 -1
  155. package/dist/schema-path.js.map +0 -1
  156. package/dist/video-embeds.d.ts.map +0 -1
  157. package/dist/video-embeds.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,2331 +1,38 @@
1
- import { parseVideoEmbed } from "./video-embeds.js";
2
- import * as v from "valibot";
3
- import { decodeEntryLink, MAX_INTERNAL_LINK_REFERENCES } from "./internal-links.js";
4
- export * from "./internal-links.js";
5
- export * from "./video-embeds.js";
6
- export * from "./list-query-policy.js";
7
- /** Validates, detaches and freezes optional sibling layout metadata. */
8
- export function normalizeFormLayout(value, fields, path = "layout") {
9
- if (value === undefined)
10
- return undefined;
11
- const raw = normalizeJsonValue(value, path, new WeakSet());
12
- if (!isRecord(raw) ||
13
- Object.keys(raw).some((key) => !["mode", "groups"].includes(key)) ||
14
- (raw.mode !== "sections" && raw.mode !== "tabs") ||
15
- !Array.isArray(raw.groups) ||
16
- raw.groups.length === 0)
17
- fail(path, "must declare mode sections/tabs and nonempty groups.");
18
- const keys = new Set();
19
- const placed = new Set();
20
- for (const [index, group] of raw.groups.entries()) {
21
- const at = `${path}.groups.${index}`;
22
- if (!isRecord(group) ||
23
- Object.keys(group).some((key) => !["key", "label", "description", "fields"].includes(key)) ||
24
- typeof group.key !== "string" ||
25
- !FIELD_KEY_PATTERN.test(group.key) ||
26
- keys.has(group.key) ||
27
- typeof group.label !== "string" ||
28
- !group.label.trim() ||
29
- (group.description !== undefined && typeof group.description !== "string") ||
30
- !Array.isArray(group.fields) ||
31
- group.fields.length === 0)
32
- fail(at, "must declare a unique key, nonempty label and fields.");
33
- keys.add(group.key);
34
- for (const key of group.fields) {
35
- if (typeof key !== "string" || !Object.hasOwn(fields, key) || placed.has(key))
36
- fail(at, `contains unknown or repeated field ${String(key)}.`);
37
- placed.add(key);
38
- }
39
- }
40
- return deepFreeze(raw);
41
- }
42
- /** Sibling field order used by rendering and validation summaries. */
43
- export function formFieldKeys(fields, layout) {
44
- const placed = layout?.groups.flatMap((group) => group.fields) ?? [];
45
- return [...placed, ...Object.keys(fields).filter((key) => !placed.includes(key))];
46
- }
47
- /** Validates, detaches and freezes the conditional-field rules of one owner. */
48
- export function normalizeFieldVisibility(value, fields, path = "visibility") {
49
- if (value === undefined)
50
- return undefined;
51
- const raw = normalizeJsonValue(value, path, new WeakSet());
52
- if (!isRecord(raw))
53
- fail(path, "must be a plain object of field rules.");
54
- for (const [target, rule] of Object.entries(raw)) {
55
- const at = `${path}.${target}`;
56
- if (!Object.hasOwn(fields, target))
57
- fail(at, "must target a declared sibling field.");
58
- if (!isRecord(rule) ||
59
- Object.keys(rule).some((key) => !["field", "values"].includes(key)) ||
60
- typeof rule.field !== "string")
61
- fail(at, "must contain only field and values.");
62
- if (rule.field === target)
63
- fail(`${at}.field`, "must name another sibling field.");
64
- if (Object.hasOwn(raw, rule.field))
65
- fail(`${at}.field`, "must name an unconditional controller; chains and cycles are not allowed.");
66
- const controller = Object.hasOwn(fields, rule.field) ? fields[rule.field] : undefined;
67
- if (controller?.type !== "select" && controller?.type !== "boolean")
68
- fail(`${at}.field`, "must name a sibling select or boolean field.");
69
- const allowed = controller.type === "select" ? controller.options : [true, false];
70
- if (!Array.isArray(rule.values) ||
71
- rule.values.length === 0 ||
72
- new Set(rule.values).size !== rule.values.length ||
73
- rule.values.some((entry) => !allowed.includes(entry)))
74
- fail(`${at}.values`, "must be a nonempty unique subset of the controller's values.");
75
- }
76
- return deepFreeze(raw);
77
- }
78
- /**
79
- * Whether `target` applies in one normalized object occurrence: a target
80
- * without a rule is visible; otherwise its controller's value (present or
81
- * materialized default) must be listed. An absent controller matches nothing.
82
- */
83
- export function isFieldVisible(visibility, target, values) {
84
- const rule = visibility !== undefined && Object.hasOwn(visibility, target) ? visibility[target] : undefined;
85
- if (rule === undefined)
86
- return true;
87
- if (!Object.hasOwn(values, rule.field))
88
- return false;
89
- return rule.values.includes(values[rule.field]);
90
- }
91
- /** Maximum containers along a descriptor branch. */
92
- export const MAX_FIELD_CONTAINER_DEPTH = 6;
93
- /** Maximum directly nested groups. */
94
- export const MAX_CONSECUTIVE_GROUPS = 2;
95
- /** Maximum items in any one list. */
96
- export const MAX_LIST_ITEMS = 100;
97
- /** Maximum sum of list lengths in a snapshot. */
98
- export const MAX_SNAPSHOT_LIST_ITEMS = 500;
99
- /** Thrown when a field builder receives a non-portable or contradictory option. */
100
- export class FieldConfigurationError extends Error {
101
- constructor(message) {
102
- super(message);
103
- this.name = "FieldConfigurationError";
104
- }
105
- }
106
- function fail(path, message) {
107
- throw new FieldConfigurationError(`${path} ${message}`);
108
- }
109
- function isPlainObject(value) {
110
- const prototype = Object.getPrototypeOf(value);
111
- return prototype === null || prototype === Object.prototype;
112
- }
113
- function isArrayIndex(key) {
114
- if (key === "0") {
115
- return true;
116
- }
117
- if (!/^[1-9][0-9]*$/u.test(key)) {
118
- return false;
119
- }
120
- const index = Number(key);
121
- return Number.isSafeInteger(index) && index < 4_294_967_295;
122
- }
123
- function normalizeJsonValue(value, path, ancestors) {
124
- if (value === null || typeof value === "boolean" || typeof value === "string") {
125
- return value;
126
- }
127
- if (typeof value === "number") {
128
- if (!Number.isFinite(value)) {
129
- fail(path, "must not contain a non-finite number.");
130
- }
131
- return value;
132
- }
133
- if (typeof value !== "object") {
134
- fail(path, "must be JSON-serializable.");
135
- }
136
- if (ancestors.has(value)) {
137
- fail(path, "must not contain a cyclic reference.");
138
- }
139
- ancestors.add(value);
140
- try {
141
- if (Array.isArray(value)) {
142
- const keys = Reflect.ownKeys(value);
143
- for (const key of keys) {
144
- if (key === "length") {
145
- continue;
146
- }
147
- if (typeof key !== "string" || !isArrayIndex(key)) {
148
- fail(path, "must not contain non-index array properties or symbols.");
149
- }
150
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
151
- if (descriptor === undefined) {
152
- fail(`${path}[${key}]`, "must contain an own data property.");
153
- }
154
- if ("get" in descriptor || "set" in descriptor) {
155
- fail(`${path}[${key}]`, "must not contain accessor properties.");
156
- }
157
- }
158
- const normalized = [];
159
- for (let index = 0; index < value.length; index += 1) {
160
- if (!Object.hasOwn(value, index)) {
161
- fail(`${path}[${index}]`, "must not contain sparse array entries.");
162
- }
163
- normalized.push(normalizeJsonValue(value[index], `${path}[${index}]`, ancestors));
164
- }
165
- return normalized;
166
- }
167
- if (!isPlainObject(value)) {
168
- fail(path, "must not contain a non-plain object.");
169
- }
170
- const normalized = {};
171
- for (const key of Reflect.ownKeys(value)) {
172
- if (typeof key !== "string") {
173
- fail(path, "must not contain symbol keys.");
174
- }
175
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
176
- if (descriptor === undefined) {
177
- fail(`${path}.${key}`, "must contain an own data property.");
178
- }
179
- if ("get" in descriptor || "set" in descriptor) {
180
- fail(`${path}.${key}`, "must not contain accessor properties.");
181
- }
182
- if (!descriptor.enumerable) {
183
- fail(`${path}.${key}`, "must contain an enumerable data property.");
184
- }
185
- normalized[key] = normalizeJsonValue(descriptor.value, `${path}.${key}`, ancestors);
186
- }
187
- return normalized;
188
- }
189
- finally {
190
- ancestors.delete(value);
191
- }
192
- }
193
- function normalizeOptions(options) {
194
- const normalized = normalizeJsonValue(options, "options", new WeakSet());
195
- if (normalized === null || Array.isArray(normalized) || typeof normalized !== "object") {
196
- fail("options", "must be a plain object.");
197
- }
198
- return normalized;
199
- }
200
- function deepFreeze(value) {
201
- if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
202
- for (const child of Object.values(value)) {
203
- deepFreeze(child);
204
- }
205
- Object.freeze(value);
206
- }
207
- return value;
208
- }
209
- const RENAMED_FROM_PATTERN = /^[A-Za-z][A-Za-z0-9]*$/u;
210
- function readOptionalString(options, name) {
211
- const value = options[name];
212
- if (value === undefined) {
213
- return undefined;
214
- }
215
- if (typeof value !== "string") {
216
- fail(`options.${name}`, "must be a string.");
217
- }
218
- return value;
219
- }
220
- function readOptionalBoolean(options, name) {
221
- const value = options[name];
222
- if (value === undefined) {
223
- return undefined;
224
- }
225
- if (typeof value !== "boolean") {
226
- fail(`options.${name}`, "must be a boolean.");
227
- }
228
- return value;
229
- }
230
- function readOptionalFiniteNumber(options, name, integer) {
231
- const value = options[name];
232
- if (value === undefined) {
233
- return undefined;
234
- }
235
- if (typeof value !== "number" ||
236
- !Number.isFinite(value) ||
237
- (integer && !Number.isSafeInteger(value)) ||
238
- (integer && value < 0)) {
239
- fail(`options.${name}`, integer ? "must be a non-negative safe integer." : "must be a finite number.");
240
- }
241
- return value;
242
- }
243
- function addCommonOptions(definition, options) {
244
- const label = readOptionalString(options, "label");
245
- if (label !== undefined) {
246
- definition.label = label;
247
- }
248
- const description = readOptionalString(options, "description");
249
- if (description !== undefined) {
250
- definition.description = description;
251
- }
252
- const placeholder = readOptionalString(options, "placeholder");
253
- if (placeholder !== undefined)
254
- definition.placeholder = placeholder;
255
- const renamedFrom = readOptionalString(options, "renamedFrom");
256
- if (renamedFrom !== undefined) {
257
- if (!RENAMED_FROM_PATTERN.test(renamedFrom)) {
258
- fail("options.renamedFrom", "must be a valid field key.");
259
- }
260
- definition.renamedFrom = renamedFrom;
261
- }
262
- definition.required = readOptionalBoolean(options, "required") ?? false;
263
- }
264
- function assertAllowedOptions(options, allowed) {
265
- for (const key of Object.keys(options)) {
266
- // Every field kind accepts the temporary `renamedFrom` hint.
267
- if (!allowed.includes(key) && key !== "renamedFrom") {
268
- fail(`options.${key}`, "is not supported by this field type.");
269
- }
270
- }
271
- }
272
- function addDefault(definition, options, isValid, message) {
273
- if (!Object.hasOwn(options, "defaultValue")) {
274
- return;
275
- }
276
- const value = options.defaultValue;
277
- if (value === undefined || !isValid(value)) {
278
- fail("options.defaultValue", message);
279
- }
280
- definition.defaultValue = value;
281
- }
282
- function buildStringField(type, input) {
283
- const options = normalizeOptions(input ?? {});
284
- assertAllowedOptions(options, [
285
- "defaultValue",
286
- "description",
287
- "label",
288
- "maxLength",
289
- "minLength",
290
- "placeholder",
291
- "required",
292
- ]);
293
- const definition = { type };
294
- addCommonOptions(definition, options);
295
- const minLength = readOptionalFiniteNumber(options, "minLength", true);
296
- const maxLength = readOptionalFiniteNumber(options, "maxLength", true);
297
- if (minLength !== undefined && maxLength !== undefined && minLength > maxLength) {
298
- fail("options", "must not set minLength greater than maxLength.");
299
- }
300
- if (minLength !== undefined) {
301
- definition.minLength = minLength;
302
- }
303
- if (maxLength !== undefined) {
304
- definition.maxLength = maxLength;
305
- }
306
- addDefault(definition, options, (value) => typeof value === "string" &&
307
- (minLength === undefined || textLength(value) >= minLength) &&
308
- (maxLength === undefined || textLength(value) <= maxLength), "must be a string that conforms to the declared length constraints.");
309
- return deepFreeze(definition);
310
- }
311
- function buildStringValueField(type, input) {
312
- const options = normalizeOptions(input ?? {});
313
- assertAllowedOptions(options, [
314
- "defaultValue",
315
- "description",
316
- "label",
317
- "required",
318
- ...(type === "url" ? ["placeholder", "embedProviders"] : []),
319
- ]);
320
- const definition = { type };
321
- addCommonOptions(definition, options);
322
- if (type === "url" && options.embedProviders !== undefined) {
323
- const providers = options.embedProviders;
324
- if (!Array.isArray(providers) ||
325
- providers.length === 0 ||
326
- providers.some((provider) => provider !== "youtube" && provider !== "vimeo") ||
327
- new Set(providers).size !== providers.length)
328
- fail("options.embedProviders", "must be a non-empty unique list of youtube and vimeo.");
329
- definition.embedProviders = ["youtube", "vimeo"].filter((provider) => providers.includes(provider));
330
- }
331
- addDefault(definition, options, (value) => {
332
- if (typeof value !== "string")
333
- return false;
334
- if (definition.embedProviders === undefined)
335
- return true;
336
- const embed = parseVideoEmbed(value);
337
- return (isSafeUrl(value) &&
338
- embed !== undefined &&
339
- definition.embedProviders.includes(embed.provider));
340
- }, definition.embedProviders === undefined
341
- ? "must be a string."
342
- : "must be a string matching the declared embed providers.");
343
- return deepFreeze(definition);
344
- }
345
- /** Builders for portable Lace field descriptors. */
346
- export const field = {
347
- /** Define named child fields stored as one plain object. */
348
- group(options) {
349
- return normalizeCompositeOptions("group", options);
350
- },
351
- /** Define an ordered array of scalar or group values. */
352
- list(options) {
353
- return normalizeCompositeOptions("list", options);
354
- },
355
- /** Define a single-line text field. */
356
- text(options) {
357
- return buildStringField("text", options);
358
- },
359
- /** Define a multiline text field. */
360
- textarea(options) {
361
- return buildStringField("textarea", options);
362
- },
363
- /** Define a safe Tiptap JSON field. */
364
- richText(options) {
365
- const normalized = normalizeOptions(options ?? {});
366
- assertAllowedOptions(normalized, [
367
- "defaultValue",
368
- "description",
369
- "label",
370
- "required",
371
- "placeholder",
372
- ]);
373
- const definition = { type: "richText" };
374
- addCommonOptions(definition, normalized);
375
- addDefault(definition, normalized, (value) => isSafeRichTextDocument(value), "must be a safe rich-text document.");
376
- return deepFreeze(definition);
377
- },
378
- /** Define a finite numeric field. */
379
- number(options) {
380
- const normalized = normalizeOptions(options ?? {});
381
- assertAllowedOptions(normalized, [
382
- "defaultValue",
383
- "description",
384
- "label",
385
- "placeholder",
386
- "max",
387
- "min",
388
- "required",
389
- ]);
390
- const definition = { type: "number" };
391
- addCommonOptions(definition, normalized);
392
- const min = readOptionalFiniteNumber(normalized, "min", false);
393
- const max = readOptionalFiniteNumber(normalized, "max", false);
394
- if (min !== undefined && max !== undefined && min > max) {
395
- fail("options", "must not set min greater than max.");
396
- }
397
- if (min !== undefined) {
398
- definition.min = min;
399
- }
400
- if (max !== undefined) {
401
- definition.max = max;
402
- }
403
- addDefault(definition, normalized, (value) => typeof value === "number" &&
404
- Number.isFinite(value) &&
405
- (min === undefined || value >= min) &&
406
- (max === undefined || value <= max), "must be a finite number that conforms to the declared numeric bounds.");
407
- return deepFreeze(definition);
408
- },
409
- /** Define a boolean field. */
410
- boolean(options) {
411
- const normalized = normalizeOptions(options ?? {});
412
- assertAllowedOptions(normalized, ["defaultValue", "description", "label", "required"]);
413
- const definition = { type: "boolean" };
414
- addCommonOptions(definition, normalized);
415
- addDefault(definition, normalized, (value) => typeof value === "boolean", "must be a boolean.");
416
- return deepFreeze(definition);
417
- },
418
- /** Define a date string field. */
419
- date(options) {
420
- return buildStringValueField("date", options);
421
- },
422
- /** Define a datetime string field. */
423
- datetime(options) {
424
- return buildStringValueField("datetime", options);
425
- },
426
- /** Define a select field with a non-empty unique list of string choices. */
427
- select(options) {
428
- const normalized = normalizeOptions(options);
429
- assertAllowedOptions(normalized, [
430
- "defaultValue",
431
- "description",
432
- "label",
433
- "options",
434
- "presentation",
435
- "placeholder",
436
- "required",
437
- ]);
438
- const rawChoices = normalized.options;
439
- if (!Array.isArray(rawChoices) || rawChoices.length === 0) {
440
- fail("options.options", "must be a non-empty array of strings.");
441
- }
442
- const choices = [];
443
- const seen = new Set();
444
- for (const [index, choice] of rawChoices.entries()) {
445
- if (typeof choice !== "string") {
446
- fail(`options.options[${index}]`, "must be a string.");
447
- }
448
- if (seen.has(choice)) {
449
- fail(`options.options[${index}]`, "must not duplicate a select choice.");
450
- }
451
- seen.add(choice);
452
- choices.push(choice);
453
- }
454
- const definition = { options: choices, type: "select" };
455
- addCommonOptions(definition, normalized);
456
- if (normalized.presentation !== undefined)
457
- definition.presentation = normalizeSelectPresentation(normalized.presentation, choices);
458
- addDefault(definition, normalized, (value) => typeof value === "string" && seen.has(value), "must be one of the declared select choices.");
459
- return deepFreeze(definition);
460
- },
461
- /** Define a safe URL field, optionally restricted to supported video providers. */
462
- url(options) {
463
- return buildStringValueField("url", options);
464
- },
465
- /** Define a field holding a media identifier. */
466
- media(options) {
467
- return buildStringValueField("media", options);
468
- },
469
- };
470
- function normalizeSelectPresentation(value, options) {
471
- const path = "options.presentation";
472
- const exact = (raw, keys, at) => {
473
- const record = descriptorRecord(raw, at);
474
- for (const key of Object.keys(record))
475
- if (!keys.includes(key))
476
- fail(`${at}.${key}`, "is not supported.");
477
- return record;
478
- };
479
- const text = (raw, at) => {
480
- if (typeof raw !== "string" ||
481
- !raw.trim() ||
482
- /[<>]/u.test(raw) ||
483
- [...raw].some((character) => character.charCodeAt(0) < 32))
484
- fail(at, "must be nonempty plain text.");
485
- return raw;
486
- };
487
- const raw = exact(value, ["control", "choices"], path);
488
- if (raw.control !== "cards")
489
- fail(`${path}.control`, 'must be "cards".');
490
- if (!Array.isArray(raw.choices) || raw.choices.length !== options.length)
491
- fail(`${path}.choices`, "must cover every select option exactly once.");
492
- const seen = new Set();
493
- const choices = raw.choices.map((choice, index) => {
494
- const at = `${path}.choices[${index}]`;
495
- const entry = exact(choice, ["value", "label", "description", "diagram"], at);
496
- if (typeof entry.value !== "string" || !options.includes(entry.value) || seen.has(entry.value))
497
- fail(`${at}.value`, "must name a unique declared select option.");
498
- seen.add(entry.value);
499
- const result = {
500
- value: entry.value,
501
- label: text(entry.label, `${at}.label`),
502
- ...(entry.description !== undefined
503
- ? { description: text(entry.description, `${at}.description`) }
504
- : {}),
505
- ...(entry.diagram !== undefined ? { diagram: diagram(entry.diagram, `${at}.diagram`) } : {}),
506
- };
507
- return result;
508
- });
509
- return deepFreeze({ control: "cards", choices });
510
- function diagram(input, at) {
511
- const rawDiagram = exact(input, ["cells"], at);
512
- if (!Array.isArray(rawDiagram.cells) ||
513
- rawDiagram.cells.length < 1 ||
514
- rawDiagram.cells.length > 16)
515
- fail(`${at}.cells`, "must contain 1–16 rectangles.");
516
- const cells = [];
517
- for (const [index, inputCell] of rawDiagram.cells.entries()) {
518
- const cellPath = `${at}.cells[${index}]`;
519
- const rawCell = exact(inputCell, ["x", "y", "width", "height"], cellPath);
520
- for (const key of ["x", "y", "width", "height"]) {
521
- const n = rawCell[key];
522
- if (typeof n !== "number" ||
523
- !Number.isInteger(n) ||
524
- n < (key === "x" || key === "y" ? 0 : 1))
525
- fail(`${cellPath}.${key}`, "must be an integer within the 12 by 12 canvas.");
526
- }
527
- const cell = rawCell;
528
- if (cell.x + cell.width > 12 || cell.y + cell.height > 12)
529
- fail(cellPath, "must fit within the 12 by 12 canvas.");
530
- if (cells.some((other) => cell.x < other.x + other.width &&
531
- cell.x + cell.width > other.x &&
532
- cell.y < other.y + other.height &&
533
- cell.y + cell.height > other.y))
534
- fail(cellPath, "must not overlap another rectangle.");
535
- cells.push({ ...cell });
536
- }
537
- return { cells };
538
- }
539
- }
540
- /**
541
- * Project a field descriptor into a detached, immutable JSON-safe admin form
542
- * representation. Runtime schemas and callbacks are deliberately absent.
543
- */
544
- export function toFieldMetadata(definition) {
545
- return normalizeFieldDefinition(definition);
546
- }
547
- /** Reads own data properties without executing configuration accessors. */
548
- function descriptorRecord(value, path) {
549
- if (!isRecord(value))
550
- fail(path, "must be a plain field-definition object.");
551
- const output = {};
552
- for (const key of Reflect.ownKeys(value)) {
553
- if (typeof key !== "string")
554
- fail(path, "must not contain symbol keys.");
555
- const property = Object.getOwnPropertyDescriptor(value, key);
556
- if (!property.enumerable || !("value" in property))
557
- fail(`${path}.${key}`, "must be an enumerable data property.");
558
- Object.defineProperty(output, key, { value: property.value, enumerable: true });
559
- }
560
- return output;
561
- }
562
- function normalizeCompositeOptions(type, value) {
563
- const options = descriptorRecord(value, "options");
564
- if (Object.hasOwn(options, "type"))
565
- fail("options.type", "is not supported.");
566
- return normalizeFieldDefinition({ ...options, type });
567
- }
568
- /** Validates and detaches a descriptor, including forged JSON/configuration input. */
569
- export function normalizeFieldDefinition(value) {
570
- return normalizeDescriptor(value, "definition", 0, 0, new WeakSet());
571
- }
572
- function normalizeDescriptor(value, path, depth, groups, ancestors) {
573
- const raw = descriptorRecord(value, path);
574
- if (ancestors.has(value))
575
- fail(path, "must not contain a cyclic reference.");
576
- const { type, ...options } = raw;
577
- if (type !== "group" && type !== "list") {
578
- try {
579
- switch (type) {
580
- case "boolean":
581
- return field.boolean(options);
582
- case "date":
583
- return field.date(options);
584
- case "datetime":
585
- return field.datetime(options);
586
- case "media":
587
- return field.media(options);
588
- case "number":
589
- return field.number(options);
590
- case "richText":
591
- return field.richText(options);
592
- case "select":
593
- return field.select(options);
594
- case "text":
595
- return field.text(options);
596
- case "textarea":
597
- return field.textarea(options);
598
- case "url":
599
- return field.url(options);
600
- default:
601
- fail(`${path}.type`, "must name a supported field type.");
602
- }
603
- }
604
- catch (error) {
605
- if (error instanceof FieldConfigurationError)
606
- fail(path, error.message);
607
- throw error;
608
- }
609
- }
610
- if (depth >= MAX_FIELD_CONTAINER_DEPTH)
611
- fail(path, `must not exceed ${MAX_FIELD_CONTAINER_DEPTH} containers.`);
612
- if (type === "group" && groups >= MAX_CONSECUTIVE_GROUPS)
613
- fail(path, `must not exceed ${MAX_CONSECUTIVE_GROUPS} consecutive groups.`);
614
- const allowed = [
615
- "label",
616
- "description",
617
- "required",
618
- "defaultValue",
619
- "renamedFrom",
620
- ...(type === "group"
621
- ? ["fields", "layout", "visibility"]
622
- : ["item", "minItems", "maxItems", "itemLabel"]),
623
- ];
624
- for (const key of Object.keys(options))
625
- if (!allowed.includes(key))
626
- fail(`${path}.${key}`, "is not supported by this field type.");
627
- const { fields, item, defaultValue, ...common } = options;
628
- const normalized = normalizeOptions(common);
629
- const result = { type };
630
- addCommonOptions(result, normalized);
631
- ancestors.add(value);
632
- try {
633
- if (type === "group") {
634
- const children = descriptorRecord(fields, `${path}.fields`);
635
- const output = {};
636
- for (const [key, child] of Object.entries(children)) {
637
- if (!FIELD_KEY_PATTERN.test(key))
638
- fail(`${path}.fields.${key}`, "must be a valid field key.");
639
- Object.defineProperty(output, key, {
640
- value: normalizeDescriptor(child, `${path}.fields.${key}`, depth + 1, groups + 1, ancestors),
641
- enumerable: true,
642
- });
643
- }
644
- result.fields = output;
645
- const layout = normalizeFormLayout(options.layout, output, `${path}.layout`);
646
- if (layout !== undefined)
647
- result.layout = layout;
648
- const visibility = normalizeFieldVisibility(options.visibility, output, `${path}.visibility`);
649
- if (visibility !== undefined)
650
- result.visibility = visibility;
651
- }
652
- else {
653
- const child = descriptorRecord(item, `${path}.item`);
654
- if (child.type === "list")
655
- fail(`${path}.item`, "must not be a direct list of lists.");
656
- if (Object.hasOwn(child, "renamedFrom"))
657
- fail(`${path}.item.renamedFrom`, "list item descriptors have no field key and cannot be renamed.");
658
- result.item = normalizeDescriptor(item, `${path}.item`, depth + 1, 0, ancestors);
659
- if (Object.hasOwn(options, "itemLabel")) {
660
- const key = options.itemLabel;
661
- const itemDefinition = result.item;
662
- if (typeof key !== "string" ||
663
- !FIELD_KEY_PATTERN.test(key) ||
664
- itemDefinition.type !== "group" ||
665
- !Object.hasOwn(itemDefinition.fields, key) ||
666
- !["text", "textarea", "select", "url"].includes(itemDefinition.fields[key].type))
667
- fail(`${path}.itemLabel`, "must name an immediate text, textarea, select or URL group child.");
668
- result.itemLabel = key;
669
- }
670
- const min = readOptionalFiniteNumber(normalized, "minItems", true);
671
- const max = readOptionalFiniteNumber(normalized, "maxItems", true);
672
- if ((min ?? 0) > (max ?? MAX_LIST_ITEMS) || (max ?? MAX_LIST_ITEMS) > MAX_LIST_ITEMS)
673
- fail(path, `list bounds must satisfy 0 ≤ minItems ≤ maxItems ≤ ${MAX_LIST_ITEMS}.`);
674
- if (min !== undefined)
675
- result.minItems = min;
676
- if (max !== undefined)
677
- result.maxItems = max;
678
- }
679
- if (Object.hasOwn(options, "defaultValue")) {
680
- const portableDefault = normalizeJsonValue(defaultValue, `${path}.defaultValue`, new WeakSet());
681
- try {
682
- normalizeFieldValue(result, portableDefault, "draft", [], {
683
- count: 0,
684
- });
685
- }
686
- catch (error) {
687
- if (error instanceof ContentValidationError)
688
- fail(`${path}.defaultValue`, error.message);
689
- throw error;
690
- }
691
- result.defaultValue = portableDefault;
692
- }
693
- return deepFreeze(result);
694
- }
695
- finally {
696
- ancestors.delete(value);
697
- }
698
- }
699
- /** Thrown when submitted content fails a portable validation contract. */
700
- export class ContentValidationError extends Error {
701
- issues;
702
- constructor(issues) {
703
- super(issues.map((issue) => `${formatValidationPath(issue.path)} ${issue.message}`).join("; "));
704
- this.name = "ContentValidationError";
705
- this.issues = issues;
706
- }
707
- }
708
- function formatValidationPath(path) {
709
- if (path.length === 0) {
710
- return "$";
711
- }
712
- return path.reduce((result, segment) => {
713
- return typeof segment === "number" ? `${result}[${segment}]` : `${result}.${segment}`;
714
- }, "$");
715
- }
716
- function invalid(path, code, message) {
717
- throw new ContentValidationError([{ code, message, path }]);
718
- }
719
- function isRecord(value) {
720
- return (value !== null && typeof value === "object" && !Array.isArray(value) && isPlainObject(value));
721
- }
722
- function assertExactKeys(value, required, optional, path) {
723
- const allowed = new Set([...required, ...optional]);
724
- for (const key of Object.keys(value)) {
725
- if (!allowed.has(key)) {
726
- invalid([...path, key], "unknown_key", "is not permitted.");
727
- }
728
- }
729
- for (const key of required) {
730
- if (!Object.hasOwn(value, key)) {
731
- invalid([...path, key], "missing_key", "is required.");
732
- }
733
- }
734
- }
735
- /** Returns whether a URL is permitted as an href, including rich-text links. */
736
- export function isSafeUrl(value) {
737
- if (typeof value !== "string" ||
738
- value.length === 0 ||
739
- /\s/u.test(value) ||
740
- value.includes(String.fromCodePoint(0))) {
741
- return false;
742
- }
743
- if (value.startsWith("#")) {
744
- return true;
745
- }
746
- if (value.startsWith("/")) {
747
- return !value.startsWith("//");
748
- }
749
- return /^(?:https?:\/\/[^/?#\s]+(?:[/?#][^\s]*)?|mailto:[^\s@]+@[^\s@]+|tel:\+?[0-9(). -]+)$/u.test(value);
750
- }
751
- /** Ordinary URL fields support safe manual URLs and canonical entry tokens. */
752
- export function isUrlFieldTarget(value) {
753
- return isSafeUrl(value) || decodeEntryLink(value) !== undefined;
754
- }
755
- function assertMarks(value, path) {
756
- if (!Array.isArray(value)) {
757
- invalid(path, "invalid_marks", "must be an array.");
758
- }
759
- for (const [index, mark] of value.entries()) {
760
- const markPath = [...path, index];
761
- if (!isRecord(mark) || typeof mark.type !== "string") {
762
- invalid(markPath, "invalid_mark", "must be a mark object.");
763
- }
764
- if (mark.type === "link") {
765
- assertExactKeys(mark, ["attrs", "type"], [], markPath);
766
- if (!isRecord(mark.attrs)) {
767
- invalid([...markPath, "attrs"], "invalid_link_attributes", "must be an object.");
768
- }
769
- assertExactKeys(mark.attrs, ["href"], ["target", "rel"], [...markPath, "attrs"]);
770
- if (Object.hasOwn(mark.attrs, "target") && mark.attrs.target !== "_blank") {
771
- invalid([...markPath, "attrs", "target"], "invalid_link_target", 'must be "_blank".');
772
- }
773
- if (Object.hasOwn(mark.attrs, "rel") && mark.attrs.rel !== "nofollow") {
774
- invalid([...markPath, "attrs", "rel"], "invalid_link_rel", 'must be "nofollow".');
775
- }
776
- if (!isSafeUrl(mark.attrs.href)) {
777
- invalid([...markPath, "attrs", "href"], "unsafe_url", "must be an approved URL.");
778
- }
779
- continue;
780
- }
781
- if (mark.type === "bold" ||
782
- mark.type === "code" ||
783
- mark.type === "italic" ||
784
- mark.type === "strike") {
785
- assertExactKeys(mark, ["type"], [], markPath);
786
- continue;
787
- }
788
- invalid([...markPath, "type"], "unknown_mark", "is not permitted.");
789
- }
790
- }
791
- function assertRichTextChildren(value, path, allowed) {
792
- if (!Array.isArray(value)) {
793
- invalid(path, "invalid_content", "must be an array.");
794
- }
795
- for (const [index, child] of value.entries()) {
796
- assertRichTextNode(child, [...path, index]);
797
- if (!allowed.includes(child.type)) {
798
- invalid([...path, index, "type"], "invalid_child", "is not permitted in this node.");
799
- }
800
- }
801
- }
802
- function assertRichTextNode(value, path) {
803
- if (!isRecord(value) || typeof value.type !== "string") {
804
- invalid(path, "invalid_node", "must be a rich-text node object.");
805
- }
806
- if (value.type === "text") {
807
- assertExactKeys(value, ["text", "type"], ["marks"], path);
808
- if (typeof value.text !== "string") {
809
- invalid([...path, "text"], "invalid_text", "must be a string.");
810
- }
811
- if (Object.hasOwn(value, "marks")) {
812
- assertMarks(value.marks, [...path, "marks"]);
813
- }
814
- return;
815
- }
816
- if (value.type === "hardBreak" || value.type === "horizontalRule") {
817
- assertExactKeys(value, ["type"], [], path);
818
- return;
819
- }
820
- if (value.type === "codeBlock") {
821
- assertExactKeys(value, ["type"], ["content"], path);
822
- if (Object.hasOwn(value, "content")) {
823
- assertRichTextChildren(value.content, [...path, "content"], ["text"]);
824
- for (const [index, child] of value.content.entries()) {
825
- assertExactKeys(child, ["type", "text"], [], [...path, "content", index]);
826
- }
827
- }
828
- return;
829
- }
830
- if (value.type === "paragraph") {
831
- assertExactKeys(value, ["type"], ["content"], path);
832
- if (Object.hasOwn(value, "content")) {
833
- assertRichTextChildren(value.content, [...path, "content"], ["hardBreak", "text"]);
834
- }
835
- return;
836
- }
837
- if (value.type === "heading") {
838
- assertExactKeys(value, ["attrs", "type"], ["content"], path);
839
- if (!isRecord(value.attrs)) {
840
- invalid([...path, "attrs"], "invalid_heading_attributes", "must be an object.");
841
- }
842
- assertExactKeys(value.attrs, ["level"], [], [...path, "attrs"]);
843
- if (value.attrs.level !== 1 &&
844
- value.attrs.level !== 2 &&
845
- value.attrs.level !== 3 &&
846
- value.attrs.level !== 4) {
847
- invalid([...path, "attrs", "level"], "invalid_heading_level", "must be 1, 2, 3, or 4.");
848
- }
849
- if (Object.hasOwn(value, "content")) {
850
- assertRichTextChildren(value.content, [...path, "content"], ["hardBreak", "text"]);
851
- }
852
- return;
853
- }
854
- if (value.type === "bulletList" || value.type === "orderedList") {
855
- assertExactKeys(value, ["content", "type"], [], path);
856
- assertRichTextChildren(value.content, [...path, "content"], ["listItem"]);
857
- return;
858
- }
859
- if (value.type === "listItem") {
860
- assertExactKeys(value, ["content", "type"], [], path);
861
- assertRichTextChildren(value.content, [...path, "content"], ["bulletList", "orderedList", "paragraph", "horizontalRule", "codeBlock"]);
862
- return;
863
- }
864
- if (value.type === "blockquote") {
865
- assertExactKeys(value, ["content", "type"], [], path);
866
- assertRichTextChildren(value.content, [...path, "content"], ["bulletList", "orderedList", "paragraph", "horizontalRule", "codeBlock"]);
867
- return;
868
- }
869
- invalid([...path, "type"], "unknown_node", "is not permitted.");
870
- }
871
- /** Validates and returns a closed, safe rich-text document. */
872
- export function validateRichTextDocument(value) {
873
- if (!isRecord(value) || value.type !== "doc") {
874
- invalid([], "invalid_document", "must be a doc node.");
875
- }
876
- assertExactKeys(value, ["content", "type"], [], []);
877
- assertRichTextChildren(value.content, ["content"], [
878
- "blockquote",
879
- "bulletList",
880
- "heading",
881
- "orderedList",
882
- "paragraph",
883
- "horizontalRule",
884
- "codeBlock",
885
- ]);
886
- return value;
887
- }
888
- function isSafeRichTextDocument(value) {
889
- try {
890
- validateRichTextDocument(value);
891
- return true;
892
- }
893
- catch (error) {
894
- if (error instanceof ContentValidationError) {
895
- return false;
896
- }
897
- throw error;
898
- }
899
- }
900
- /** Visits a field descriptor exhaustively. */
901
- export function visitFieldDefinition(definition, visitor) {
902
- switch (definition.type) {
903
- case "group":
904
- return visitor.group(definition);
905
- case "list":
906
- return visitor.list(definition);
907
- case "boolean":
908
- return visitor.boolean(definition);
909
- case "date":
910
- return visitor.date(definition);
911
- case "datetime":
912
- return visitor.datetime(definition);
913
- case "media":
914
- return visitor.media(definition);
915
- case "number":
916
- return visitor.number(definition);
917
- case "richText":
918
- return visitor.richText(definition);
919
- case "select":
920
- return visitor.select(definition);
921
- case "text":
922
- return visitor.text(definition);
923
- case "textarea":
924
- return visitor.textarea(definition);
925
- case "url":
926
- return visitor.url(definition);
927
- }
928
- }
929
- function isCalendarDate(value) {
930
- if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/u.test(value)) {
931
- return false;
932
- }
933
- const parts = value.split("-");
934
- const year = Number(parts[0]);
935
- const month = Number(parts[1]);
936
- const day = Number(parts[2]);
937
- const date = new Date(Date.UTC(year, month - 1, day));
938
- return (date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day);
939
- }
940
- function isUtcIsoDatetime(value) {
941
- return (typeof value === "string" &&
942
- /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/u.test(value) &&
943
- !Number.isNaN(Date.parse(value)));
944
- }
945
- function isFieldValue(definition, value) {
946
- return visitFieldDefinition(definition, {
947
- group: () => false,
948
- list: () => false,
949
- boolean: () => typeof value === "boolean",
950
- date: () => isCalendarDate(value),
951
- datetime: () => isUtcIsoDatetime(value),
952
- media: () => typeof value === "string" && value.length > 0,
953
- number: (fieldDefinition) => typeof value === "number" &&
954
- Number.isFinite(value) &&
955
- (fieldDefinition.min === undefined || value >= fieldDefinition.min) &&
956
- (fieldDefinition.max === undefined || value <= fieldDefinition.max),
957
- richText: () => isSafeRichTextDocument(value),
958
- select: (fieldDefinition) => typeof value === "string" && fieldDefinition.options.includes(value),
959
- text: (fieldDefinition) => typeof value === "string" &&
960
- (fieldDefinition.minLength === undefined || textLength(value) >= fieldDefinition.minLength) &&
961
- (fieldDefinition.maxLength === undefined || textLength(value) <= fieldDefinition.maxLength),
962
- textarea: (fieldDefinition) => typeof value === "string" &&
963
- (fieldDefinition.minLength === undefined || textLength(value) >= fieldDefinition.minLength) &&
964
- (fieldDefinition.maxLength === undefined || textLength(value) <= fieldDefinition.maxLength),
965
- url: (descriptor) => {
966
- if (descriptor.embedProviders === undefined)
967
- return isUrlFieldTarget(value);
968
- if (!isSafeUrl(value))
969
- return false;
970
- const embed = parseVideoEmbed(value);
971
- return embed !== undefined && descriptor.embedProviders.includes(embed.provider);
972
- },
973
- });
974
- }
975
- /** Compiles a field definition with the same normalization as aggregate validation. */
976
- export function compileFieldSchema(definition, mode = "publish") {
977
- return v.pipe(v.custom((value) => {
978
- try {
979
- normalizeFieldValue(definition, value, mode, [], { count: 0 });
980
- return true;
981
- }
982
- catch (error) {
983
- if (error instanceof ContentValidationError)
984
- return false;
985
- throw error;
986
- }
987
- }), v.transform((value) => normalizeFieldValue(definition, value, mode, [], { count: 0 })));
988
- }
989
- /** Validates and normalizes one present value; absence is handled by its field map. */
990
- export function validateFieldValue(definition, value, path = [], mode = "publish") {
991
- return normalizeFieldValue(definition, value, mode, path, { count: 0 });
992
- }
993
- function addListItems(length, path, budget) {
994
- budget.count += length;
995
- if (budget.count > MAX_SNAPSHOT_LIST_ITEMS)
996
- invalid(path, "too_many_list_items", `must not exceed ${MAX_SNAPSHOT_LIST_ITEMS} list elements per snapshot.`);
997
- }
998
- function normalizeFieldValue(definition, value, mode, path, budget) {
999
- if (definition.type === "group") {
1000
- if (!isRecord(value))
1001
- invalid(path, "invalid_field_value", "must be a group object.");
1002
- return normalizeFieldMap(definition.fields, value, mode, path, budget, definition.visibility);
1003
- }
1004
- if (definition.type === "list") {
1005
- if (!Array.isArray(value))
1006
- invalid(path, "invalid_field_value", "must be a list.");
1007
- if (value.length > (definition.maxItems ?? MAX_LIST_ITEMS))
1008
- invalid(path, "list_too_long", `must contain at most ${definition.maxItems ?? MAX_LIST_ITEMS} items.`);
1009
- if (mode === "publish" && value.length < (definition.minItems ?? 0))
1010
- invalid(path, "list_too_short", `must contain at least ${definition.minItems} items for publication.`);
1011
- addListItems(value.length, path, budget);
1012
- return Array.from({ length: value.length }, (_, index) => {
1013
- if (!Object.hasOwn(value, index))
1014
- invalid([...path, index], "invalid_field_value", "must contain a value.");
1015
- return normalizeFieldValue(definition.item, value[index], mode, [...path, index], budget);
1016
- });
1017
- }
1018
- if (!isFieldValue(definition, value))
1019
- invalid(path, "invalid_field_value", "does not conform to its field definition.");
1020
- return value;
1021
- }
1022
- function normalizeFieldMap(definitions, value, mode, path, budget, visibility) {
1023
- if (!isRecord(value))
1024
- invalid(path, "invalid_fields", "must be an object.");
1025
- for (const key of Object.keys(value))
1026
- if (!Object.hasOwn(definitions, key))
1027
- invalid([...path, key], "unknown_field", "is not defined by this model.");
1028
- const normalized = new Map();
1029
- const normalize = (key, definition, fieldMode) => {
1030
- let present;
1031
- if (Object.hasOwn(value, key))
1032
- present = value[key];
1033
- else if (Object.hasOwn(definition, "defaultValue"))
1034
- present = definition.defaultValue;
1035
- else {
1036
- if (fieldMode === "publish" && definition.required)
1037
- invalid([...path, key], "missing_required_field", "is required for publication.");
1038
- return;
1039
- }
1040
- normalized.set(key, normalizeFieldValue(definition, present, fieldMode, [...path, key], budget));
1041
- };
1042
- const conditional = (key) => visibility !== undefined && Object.hasOwn(visibility, key);
1043
- // Controllers are unconditional, so their normalized values decide every target.
1044
- for (const [key, definition] of Object.entries(definitions))
1045
- if (!conditional(key))
1046
- normalize(key, definition, mode);
1047
- const controllers = Object.fromEntries(normalized);
1048
- for (const [key, definition] of Object.entries(definitions))
1049
- if (conditional(key))
1050
- normalize(key, definition, isFieldVisible(visibility, key, controllers) ? mode : "draft");
1051
- const output = {};
1052
- for (const key of Object.keys(definitions))
1053
- if (normalized.has(key))
1054
- Object.defineProperty(output, key, { value: normalized.get(key), enumerable: true });
1055
- return output;
1056
- }
1057
- /** Validates field data for either an incomplete draft or a publish candidate. */
1058
- export function validateModelFields(definitions, value, mode, path = [], visibility) {
1059
- return normalizeFieldMap(definitions, value, mode, path, { count: 0 }, visibility);
1060
- }
1061
- /**
1062
- * Removes every hidden target from already normalized values, recursively
1063
- * through visible groups and list items, without inserting or reordering.
1064
- */
1065
- export function publishedFieldValues(definitions, values, visibility) {
1066
- const project = (definition, value) => {
1067
- if (definition.type === "group" && isRecord(value))
1068
- return publishedFieldValues(definition.fields, value, definition.visibility);
1069
- if (definition.type === "list" && Array.isArray(value))
1070
- return value.map((item) => project(definition.item, item));
1071
- return value;
1072
- };
1073
- const output = {};
1074
- for (const [key, value] of Object.entries(values)) {
1075
- if (!isFieldVisible(visibility, key, values))
1076
- continue;
1077
- const definition = Object.hasOwn(definitions, key) ? definitions[key] : undefined;
1078
- Object.defineProperty(output, key, {
1079
- value: definition === undefined ? value : project(definition, value),
1080
- enumerable: true,
1081
- });
1082
- }
1083
- return output;
1084
- }
1085
- /**
1086
- * Whether an owner or any nested group, including list-item groups, declares
1087
- * conditional-field rules, so its published projection can differ from its values.
1088
- */
1089
- export function declaresFieldVisibility(definitions, visibility) {
1090
- if (visibility !== undefined && Object.keys(visibility).length > 0)
1091
- return true;
1092
- const visit = (definition) => definition.type === "group"
1093
- ? declaresFieldVisibility(definition.fields, definition.visibility)
1094
- : definition.type === "list" && visit(definition.item);
1095
- return Object.values(definitions).some(visit);
1096
- }
1097
- /** The published projection of one block's normalized data. */
1098
- export function publishedBlockData(definition, data) {
1099
- return publishedFieldValues(definition.fields, data, definition.visibility);
1100
- }
1101
- /** Checks already normalized model/block values against one snapshot-wide budget. */
1102
- export function validateSnapshotListBudget(fields, values, blocks) {
1103
- const budget = { count: 0 };
1104
- function count(definition, value, path) {
1105
- if (definition.type === "group" && isRecord(value))
1106
- walk(definition.fields, value, path);
1107
- if (definition.type === "list" && Array.isArray(value)) {
1108
- addListItems(value.length, path, budget);
1109
- value.forEach((item, index) => count(definition.item, item, [...path, index]));
1110
- }
1111
- }
1112
- function walk(definitions, data, path) {
1113
- for (const [key, definition] of Object.entries(definitions))
1114
- count(definition, data[key], [...path, key]);
1115
- }
1116
- walk(fields, values, ["fields"]);
1117
- blocks.forEach((block) => walk(block.fields, block.data, block.path));
1118
- }
1119
- /** Discover references only in normalized ordinary URL descriptors. */
1120
- export function collectFieldInternalLinks(definitions, values) {
1121
- const references = [];
1122
- function visit(definition, value, path) {
1123
- if (definition.type === "url" && definition.embedProviders === undefined) {
1124
- const targetId = decodeEntryLink(value);
1125
- if (targetId !== undefined)
1126
- references.push({ targetId, path });
1127
- }
1128
- else if (definition.type === "group" && isRecord(value)) {
1129
- walk(definition.fields, value, path);
1130
- }
1131
- else if (definition.type === "list" && Array.isArray(value)) {
1132
- value.forEach((item, index) => visit(definition.item, item, [...path, index]));
1133
- }
1134
- }
1135
- function walk(fields, data, path) {
1136
- for (const [key, definition] of Object.entries(fields))
1137
- visit(definition, data[key], [...path, key]);
1138
- }
1139
- walk(definitions, values, []);
1140
- return deepFreeze(references);
1141
- }
1142
- /** Collect and bound every declared internal URL in one normalized snapshot. */
1143
- export function collectSnapshotInternalLinks(fields, values, blocks, visibility) {
1144
- const references = [];
1145
- const pointerOf = (path) => `/${path.map((part) => String(part).replaceAll("~", "~0").replaceAll("/", "~1")).join("/")}`;
1146
- function add(definitions, data, sourceKey, area, delivered, rootPath, rules) {
1147
- // The projection keeps paths, so a link is visible exactly when it survives it.
1148
- const visible = declaresFieldVisibility(definitions, rules)
1149
- ? new Set(collectFieldInternalLinks(definitions, publishedFieldValues(definitions, data, rules)).map((reference) => pointerOf(reference.path)))
1150
- : undefined;
1151
- for (const reference of collectFieldInternalLinks(definitions, data)) {
1152
- if (references.length === MAX_INTERNAL_LINK_REFERENCES)
1153
- invalid([...rootPath, ...reference.path], "too_many_internal_links", `must not contain more than ${MAX_INTERNAL_LINK_REFERENCES} internal links.`);
1154
- const pointer = pointerOf(reference.path);
1155
- references.push({
1156
- sourceKey,
1157
- area,
1158
- delivered: delivered && (visible === undefined || visible.has(pointer)),
1159
- targetId: reference.targetId,
1160
- pointer,
1161
- });
1162
- }
1163
- }
1164
- add(fields, values, "$fields", "fields", true, ["fields"], visibility);
1165
- blocks.forEach((block, index) => add(block.fields, block.data, block.key, "data", block.hidden !== true, ["blocks", index, "data"], block.visibility));
1166
- return deepFreeze(references);
1167
- }
1168
- /** Finds declared media leaves only; ordinary strings never become references. */
1169
- export function collectFieldMedia(definitions, values) {
1170
- const references = [];
1171
- function visit(definition, value, path) {
1172
- if (definition.type === "media" && typeof value === "string")
1173
- references.push({ mediaId: value, path });
1174
- else if (definition.type === "group" && isRecord(value))
1175
- walk(definition.fields, value, path);
1176
- else if (definition.type === "list" && Array.isArray(value))
1177
- value.forEach((item, index) => visit(definition.item, item, [...path, index]));
1178
- }
1179
- function walk(fields, data, path) {
1180
- for (const [key, definition] of Object.entries(fields))
1181
- visit(definition, data[key], [...path, key]);
1182
- }
1183
- walk(definitions, values, []);
1184
- return references;
1185
- }
1186
- /**
1187
- * Removes one media item from declared media leaves: a matching media value is
1188
- * dropped from its object, and a matching element of a list of media is removed
1189
- * from the list. Every other value is kept; the input is returned unchanged when
1190
- * nothing matches.
1191
- */
1192
- export function detachFieldMedia(definitions, values, mediaId) {
1193
- const matches = (definition, value) => definition.type === "media" && value === mediaId;
1194
- function visit(definition, value) {
1195
- if (definition.type === "group" && isRecord(value))
1196
- return walk(definition.fields, value);
1197
- if (definition.type !== "list" || !Array.isArray(value))
1198
- return value;
1199
- let changed = false;
1200
- const items = [];
1201
- for (const item of value) {
1202
- if (matches(definition.item, item)) {
1203
- changed = true;
1204
- continue;
1205
- }
1206
- const next = visit(definition.item, item);
1207
- changed ||= next !== item;
1208
- items.push(next);
1209
- }
1210
- return changed ? items : value;
1211
- }
1212
- function walk(fields, data) {
1213
- let result;
1214
- for (const [key, definition] of Object.entries(fields)) {
1215
- const value = data[key];
1216
- if (matches(definition, value)) {
1217
- result ??= { ...data };
1218
- delete result[key];
1219
- continue;
1220
- }
1221
- const next = visit(definition, value);
1222
- if (next !== value) {
1223
- result ??= { ...data };
1224
- result[key] = next;
1225
- }
1226
- }
1227
- return result ?? data;
1228
- }
1229
- return walk(definitions, values);
1230
- }
1231
- /** Keeps legacy scalar keys; nested locations are relative JSON Pointers. */
1232
- export function encodeFieldPath(path) {
1233
- if (path.length === 1)
1234
- return String(path[0]);
1235
- return ("/" + path.map((part) => String(part).replaceAll("~", "~0").replaceAll("/", "~1")).join("/"));
1236
- }
1237
- /** Reads a stored reference path; numeric tokens are list indices under the field-key grammar. */
1238
- export function decodeFieldPath(path) {
1239
- if (!path.startsWith("/"))
1240
- return [path];
1241
- return path
1242
- .slice(1)
1243
- .split("/")
1244
- .map((part) => {
1245
- const decoded = part.replaceAll("~1", "/").replaceAll("~0", "~");
1246
- return /^(?:0|[1-9][0-9]*)$/u.test(decoded) ? Number(decoded) : decoded;
1247
- });
1248
- }
1249
- const BLOCK_TYPE_PATTERN = /^[A-Za-z][A-Za-z0-9-]*$/u;
1250
- const BLOCK_KEY_PATTERN = /^(?:[A-Za-z][A-Za-z0-9-]*|[0-7][0-9A-HJKMNP-TV-Z]{25})$/u;
1251
- const FIELD_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9]*$/u;
1252
- /** Maximum length of a block anchor. */
1253
- export const MAX_BLOCK_ANCHOR_LENGTH = 64;
1254
- /** Maximum length of a normalized block class name. */
1255
- export const MAX_BLOCK_CLASS_NAME_LENGTH = 256;
1256
- /** Maximum number of class tokens in a block class name. */
1257
- export const MAX_BLOCK_CLASS_TOKENS = 16;
1258
- /** Maximum length of one block class token. */
1259
- export const MAX_BLOCK_CLASS_TOKEN_LENGTH = 64;
1260
- const BLOCK_ANCHOR_PATTERN = /^[a-z][a-z0-9-]{0,63}$/u;
1261
- const BLOCK_CLASS_TOKEN_PATTERN = /^[A-Za-z_-][A-Za-z0-9_\-:/.%#[\]]*$/u;
1262
- /** Whether a value is a block anchor: a lowercase letter, then lowercase letters, digits and hyphens. */
1263
- export function isBlockAnchor(value) {
1264
- return typeof value === "string" && BLOCK_ANCHOR_PATTERN.test(value);
1265
- }
1266
- /**
1267
- * Normalizes a block class name: whitespace-separated class tokens, repeats
1268
- * dropped, joined with single spaces. Returns `undefined` for a non-string,
1269
- * blank or invalid value.
1270
- */
1271
- export function normalizeBlockClassName(value) {
1272
- if (typeof value !== "string")
1273
- return undefined;
1274
- const tokens = [...new Set(value.split(/[\t\n\f\r ]+/u).filter((token) => token !== ""))];
1275
- if (tokens.length === 0 ||
1276
- tokens.length > MAX_BLOCK_CLASS_TOKENS ||
1277
- tokens.some((token) => token.length > MAX_BLOCK_CLASS_TOKEN_LENGTH || !BLOCK_CLASS_TOKEN_PATTERN.test(token))) {
1278
- return undefined;
1279
- }
1280
- const normalized = tokens.join(" ");
1281
- return normalized.length > MAX_BLOCK_CLASS_NAME_LENGTH ? undefined : normalized;
1282
- }
1283
- /** Thrown when a block definition or registry is not portable or internally consistent. */
1284
- export class BlockConfigurationError extends Error {
1285
- constructor(message) {
1286
- super(message);
1287
- this.name = "BlockConfigurationError";
1288
- }
1289
- }
1290
- /** Field types a block setting may use; every setting declares a default. */
1291
- export const BLOCK_SETTING_FIELD_TYPES = Object.freeze([
1292
- "boolean",
1293
- "number",
1294
- "select",
1295
- "text",
1296
- ]);
1297
- /** Validates and detaches settings-only visibility metadata. */
1298
- export function normalizeSettingsVisibility(value, settings, path = "settingsVisibility") {
1299
- if (value === undefined)
1300
- return undefined;
1301
- const raw = normalizeJsonValue(value, path, new WeakSet());
1302
- if (!isRecord(raw))
1303
- fail(path, "must be a plain object of setting rules.");
1304
- for (const [target, rule] of Object.entries(raw)) {
1305
- const at = `${path}.${target}`;
1306
- if (!Object.hasOwn(settings, target))
1307
- fail(at, "must target a declared scalar setting.");
1308
- if (!isRecord(rule) ||
1309
- Object.keys(rule).some((key) => !["setting", "values"].includes(key)) ||
1310
- typeof rule.setting !== "string")
1311
- fail(at, "must contain only setting and values.");
1312
- if (rule.setting === target || Object.hasOwn(raw, rule.setting))
1313
- fail(`${at}.setting`, "must be an unconditional sibling select; self references, chains and cycles are not allowed.");
1314
- const controller = Object.hasOwn(settings, rule.setting)
1315
- ? settings[rule.setting]
1316
- : undefined;
1317
- if (controller?.type !== "select" ||
1318
- !controller.required ||
1319
- !Object.hasOwn(controller, "defaultValue") ||
1320
- typeof controller.defaultValue !== "string" ||
1321
- !controller.options.includes(controller.defaultValue))
1322
- fail(`${at}.setting`, "must name a required select setting with a valid default.");
1323
- if (!Array.isArray(rule.values) ||
1324
- rule.values.length === 0 ||
1325
- new Set(rule.values).size !== rule.values.length ||
1326
- rule.values.some((option) => typeof option !== "string" || !controller.options.includes(option)))
1327
- fail(`${at}.values`, "must be a nonempty unique subset of the controller options.");
1328
- }
1329
- return deepFreeze(raw);
1330
- }
1331
- function blockFail(message) {
1332
- throw new BlockConfigurationError(message);
1333
- }
1334
- function normalizeBlockFields(value, name = "fields") {
1335
- if (!isRecord(value)) {
1336
- blockFail(`${name} must be a plain object.`);
1337
- }
1338
- const fields = {};
1339
- for (const [key, definition] of Object.entries(value)) {
1340
- if (!FIELD_KEY_PATTERN.test(key)) {
1341
- blockFail(`${name}.${key} must be a valid field key.`);
1342
- }
1343
- try {
1344
- const metadata = toFieldMetadata(definition);
1345
- const rejectHints = (field, path) => {
1346
- if (Object.hasOwn(field, "renamedFrom"))
1347
- blockFail(`${path} must not declare renamedFrom; block data changes use block versions.`);
1348
- if (field.type === "group")
1349
- for (const [childKey, child] of Object.entries(field.fields))
1350
- rejectHints(child, `${path}.fields.${childKey}`);
1351
- if (field.type === "list")
1352
- rejectHints(field.item, `${path}.item`);
1353
- };
1354
- rejectHints(metadata, `${name}.${key}`);
1355
- fields[key] = metadata;
1356
- }
1357
- catch (error) {
1358
- if (error instanceof FieldConfigurationError) {
1359
- blockFail(`${name}.${key} must be a field definition.`);
1360
- }
1361
- throw error;
1362
- }
1363
- }
1364
- return deepFreeze(fields);
1365
- }
1366
- const SETTING_TYPES = new Set(BLOCK_SETTING_FIELD_TYPES);
1367
- /** Normalizes declared settings; an empty map yields none. */
1368
- function normalizeBlockSettings(value) {
1369
- if (value === undefined)
1370
- return undefined;
1371
- const settings = normalizeBlockFields(value, "settings");
1372
- for (const [key, definition] of Object.entries(settings)) {
1373
- if (!SETTING_TYPES.has(definition.type)) {
1374
- blockFail(`settings.${key} must be a select, boolean, number or text field.`);
1375
- }
1376
- if (!Object.hasOwn(definition, "defaultValue")) {
1377
- blockFail(`settings.${key} must declare a defaultValue.`);
1378
- }
1379
- }
1380
- return Object.keys(settings).length === 0 ? undefined : settings;
1381
- }
1382
- const MIGRATION_KEY_PATTERN = /^[1-9][0-9]*$/u;
1383
- function normalizeBlockMigrations(value, version) {
1384
- if (value === undefined)
1385
- return undefined;
1386
- if (!isRecord(value)) {
1387
- blockFail("migrations must be a plain object keyed by target version.");
1388
- }
1389
- const keys = Object.keys(value);
1390
- if (keys.length === 0)
1391
- return undefined;
1392
- const targets = [];
1393
- for (const key of keys) {
1394
- const target = Number(key);
1395
- if (!MIGRATION_KEY_PATTERN.test(key) || !Number.isSafeInteger(target)) {
1396
- blockFail(`migrations.${key} must be keyed by an integer target version.`);
1397
- }
1398
- if (target < 2 || target > version) {
1399
- blockFail(`migrations.${key} must target a version from 2 to ${version}.`);
1400
- }
1401
- if (typeof value[key] !== "function") {
1402
- blockFail(`migrations.${key} must be a function.`);
1403
- }
1404
- targets.push(target);
1405
- }
1406
- targets.sort((left, right) => left - right);
1407
- if (targets.at(-1) !== version) {
1408
- blockFail(`migrations must include the current version ${version}.`);
1409
- }
1410
- for (let index = 1; index < targets.length; index += 1) {
1411
- if (targets[index] !== targets[index - 1] + 1) {
1412
- blockFail(`migrations.${targets[index - 1] + 1} is missing; migrations must be contiguous.`);
1413
- }
1414
- }
1415
- return Object.freeze(Object.fromEntries(targets.map((target) => [target, value[String(target)]])));
1416
- }
1417
- /** Defines a versioned block using only portable field descriptors. */
1418
- export function defineBlock(input) {
1419
- if (!isRecord(input)) {
1420
- blockFail("block must be a plain object.");
1421
- }
1422
- for (const key of Object.keys(input)) {
1423
- if (!new Set([
1424
- "defaultValue",
1425
- "description",
1426
- "fields",
1427
- "label",
1428
- "migrations",
1429
- "layout",
1430
- "settingsLayout",
1431
- "settingsVisibility",
1432
- "settings",
1433
- "type",
1434
- "version",
1435
- "visibility",
1436
- ]).has(key)) {
1437
- blockFail(`block.${key} is not permitted.`);
1438
- }
1439
- }
1440
- if (typeof input.type !== "string" || !BLOCK_TYPE_PATTERN.test(input.type)) {
1441
- blockFail("type must begin with an ASCII letter and contain only letters, digits, and hyphens.");
1442
- }
1443
- if (typeof input.version !== "number" ||
1444
- !Number.isSafeInteger(input.version) ||
1445
- input.version < 1) {
1446
- blockFail("version must be a positive integer.");
1447
- }
1448
- if (input.label !== undefined && typeof input.label !== "string") {
1449
- blockFail("label must be a string when provided.");
1450
- }
1451
- if (input.description !== undefined && typeof input.description !== "string") {
1452
- blockFail("description must be a string when provided.");
1453
- }
1454
- const fields = normalizeBlockFields(input.fields);
1455
- const migrations = normalizeBlockMigrations(input.migrations, input.version);
1456
- const settings = normalizeBlockSettings(input.settings);
1457
- const layout = normalizeFormLayout(input.layout, fields, `block.${input.type}.layout`);
1458
- const settingsLayout = normalizeFormLayout(input.settingsLayout, settings ?? {}, `block.${input.type}.settingsLayout`);
1459
- const settingsVisibility = normalizeSettingsVisibility(input.settingsVisibility, settings ?? {}, `block.${input.type}.settingsVisibility`);
1460
- const visibility = normalizeFieldVisibility(input.visibility, fields, `block.${input.type}.visibility`);
1461
- let defaultValue;
1462
- if (input.defaultValue !== undefined) {
1463
- try {
1464
- const normalized = normalizeJsonValue(input.defaultValue, "defaultValue", new WeakSet());
1465
- if (!isRecord(normalized)) {
1466
- blockFail("defaultValue must be a plain object.");
1467
- }
1468
- defaultValue = deepFreeze(validateModelFields(fields, normalized, "draft", [], visibility));
1469
- }
1470
- catch (error) {
1471
- if (error instanceof ContentValidationError) {
1472
- blockFail("defaultValue must conform to the block fields.");
1473
- }
1474
- throw error;
1475
- }
1476
- }
1477
- const definition = {
1478
- ...(defaultValue === undefined ? {} : { defaultValue }),
1479
- ...(input.description === undefined ? {} : { description: input.description }),
1480
- fields,
1481
- ...(input.label === undefined ? {} : { label: input.label }),
1482
- ...(migrations === undefined ? {} : { migrations }),
1483
- ...(layout === undefined ? {} : { layout }),
1484
- ...(settingsLayout === undefined ? {} : { settingsLayout }),
1485
- ...(settingsVisibility === undefined ? {} : { settingsVisibility }),
1486
- ...(settings === undefined ? {} : { settings }),
1487
- type: input.type,
1488
- validate: (value, mode) => {
1489
- const rules = visibility;
1490
- if (!isRecord(value)) {
1491
- return validateModelFields(fields, value, mode, [], rules);
1492
- }
1493
- const withDefault = defaultValue === undefined ? value : { ...defaultValue, ...value };
1494
- return validateModelFields(fields, withDefault, mode, [], rules);
1495
- },
1496
- version: input.version,
1497
- ...(visibility === undefined ? {} : { visibility }),
1498
- };
1499
- return deepFreeze(definition);
1500
- }
1501
- /** Projects a block definition into detached, JSON-safe metadata. */
1502
- export function toBlockMetadata(definition) {
1503
- const metadata = {
1504
- ...(definition.defaultValue === undefined ? {} : { defaultValue: definition.defaultValue }),
1505
- ...(definition.description === undefined ? {} : { description: definition.description }),
1506
- fields: Object.fromEntries(Object.entries(definition.fields).map(([key, fieldDefinition]) => [
1507
- key,
1508
- toFieldMetadata(fieldDefinition),
1509
- ])),
1510
- ...(definition.label === undefined ? {} : { label: definition.label }),
1511
- ...(definition.layout === undefined
1512
- ? {}
1513
- : { layout: normalizeFormLayout(definition.layout, definition.fields) }),
1514
- ...(definition.settingsLayout === undefined
1515
- ? {}
1516
- : {
1517
- settingsLayout: normalizeFormLayout(definition.settingsLayout, definition.settings ?? {}),
1518
- }),
1519
- ...(definition.settingsVisibility === undefined
1520
- ? {}
1521
- : {
1522
- settingsVisibility: normalizeSettingsVisibility(definition.settingsVisibility, definition.settings ?? {}),
1523
- }),
1524
- ...(definition.settings === undefined
1525
- ? {}
1526
- : {
1527
- settings: Object.fromEntries(Object.entries(definition.settings).map(([key, fieldDefinition]) => [
1528
- key,
1529
- toFieldMetadata(fieldDefinition),
1530
- ])),
1531
- }),
1532
- type: definition.type,
1533
- version: definition.version,
1534
- ...(definition.visibility === undefined
1535
- ? {}
1536
- : { visibility: normalizeFieldVisibility(definition.visibility, definition.fields) }),
1537
- };
1538
- return deepFreeze(metadata);
1539
- }
1540
- /** Creates a registry and rejects duplicate current block types. */
1541
- export function defineBlockRegistry(blocks) {
1542
- if (!Array.isArray(blocks)) {
1543
- blockFail("blocks must be an array of block definitions.");
1544
- }
1545
- const definitions = new Map();
1546
- for (const definition of blocks) {
1547
- if (definitions.has(definition.type)) {
1548
- blockFail(`blocks contains duplicate block type "${definition.type}".`);
1549
- }
1550
- definitions.set(definition.type, definition);
1551
- }
1552
- const normalized = deepFreeze([...definitions.values()]);
1553
- return Object.freeze({ blocks: normalized, get: (type) => definitions.get(type) });
1554
- }
1555
- /** Projects a registry to immutable JSON-safe metadata for admin and public clients. */
1556
- export function toBlockRegistryMetadata(registry) {
1557
- return deepFreeze(registry.blocks.map(toBlockMetadata));
1558
- }
1559
- /** Validates one block's field record, applying its whole-record default first. */
1560
- export function validateBlockData(definition, value, mode, path = []) {
1561
- const rules = definition.visibility;
1562
- if (!isRecord(value)) {
1563
- return validateModelFields(definition.fields, value, mode, path, rules);
1564
- }
1565
- const withDefault = definition.defaultValue === undefined ? value : { ...definition.defaultValue, ...value };
1566
- return validateModelFields(definition.fields, withDefault, mode, path, rules);
1567
- }
1568
- /**
1569
- * Validates a block's settings record against its declared settings, filling
1570
- * every default; a block that declares none accepts only `{}`.
1571
- */
1572
- export function validateBlockSettings(definition, value, path = []) {
1573
- if (!isRecord(value)) {
1574
- invalid(path, "invalid_block_settings", "must be an object.");
1575
- }
1576
- return validateModelFields(definition.settings ?? {}, value, "draft", path);
1577
- }
1578
- /** Thrown when stored block data cannot be migrated to its definition's version. */
1579
- export class BlockMigrationError extends Error {
1580
- code;
1581
- blockType;
1582
- fromVersion;
1583
- toVersion;
1584
- step;
1585
- constructor(code, blockType, fromVersion, toVersion, message,
1586
- /** Target version of the failing step, for failed or invalid steps. */
1587
- step, options) {
1588
- super(message, options);
1589
- this.code = code;
1590
- this.blockType = blockType;
1591
- this.fromVersion = fromVersion;
1592
- this.toVersion = toVersion;
1593
- this.step = step;
1594
- this.name = "BlockMigrationError";
1595
- }
1596
- }
1597
- function jsonObject(value, name) {
1598
- if (value instanceof Promise || !isRecord(value)) {
1599
- throw new FieldConfigurationError(`${name} must be a plain JSON object.`);
1600
- }
1601
- return deepFreeze(normalizeJsonValue(value, name, new WeakSet()));
1602
- }
1603
- /** Checks a step result: `{data, settings?}`; absent settings keep `previous`. */
1604
- function migrationResult(value, previous) {
1605
- if (value instanceof Promise || !isRecord(value)) {
1606
- throw new FieldConfigurationError("result must be a plain object.");
1607
- }
1608
- for (const key of Object.keys(value)) {
1609
- if (key !== "data" && key !== "settings") {
1610
- throw new FieldConfigurationError(`result.${key} is not permitted.`);
1611
- }
1612
- }
1613
- if (!Object.hasOwn(value, "data")) {
1614
- throw new FieldConfigurationError("result.data is required.");
1615
- }
1616
- return Object.freeze({
1617
- data: jsonObject(value.data, "result.data"),
1618
- settings: value.settings === undefined ? previous : jsonObject(value.settings, "result.settings"),
1619
- });
1620
- }
1621
- /**
1622
- * Migrates stored block data and settings from `fromVersion` to the
1623
- * definition's version by composing its declared migrations in ascending
1624
- * order. Each step receives a detached, frozen copy. The result is not
1625
- * validated against the definition.
1626
- */
1627
- export function migrateBlockData(definition, block, fromVersion) {
1628
- const toVersion = definition.version;
1629
- function fail(code, message, step, cause) {
1630
- throw new BlockMigrationError(code, definition.type, fromVersion, toVersion, message, step, cause === undefined ? undefined : { cause });
1631
- }
1632
- if (fromVersion > toVersion) {
1633
- fail("version_ahead", `Block ${definition.type} version ${fromVersion} is newer than ${toVersion}.`);
1634
- }
1635
- let current;
1636
- try {
1637
- current = Object.freeze({
1638
- data: jsonObject(block.data, "data"),
1639
- settings: jsonObject(block.settings, "settings"),
1640
- });
1641
- }
1642
- catch (error) {
1643
- fail("invalid_result", `Block ${definition.type} data or settings are not JSON objects.`, fromVersion, error);
1644
- }
1645
- for (let step = fromVersion + 1; step <= toVersion; step += 1) {
1646
- const migration = definition.migrations?.[step];
1647
- if (migration === undefined) {
1648
- fail("missing_step", `Block ${definition.type} has no migration from version ${fromVersion} to ${toVersion}.`);
1649
- }
1650
- let output;
1651
- try {
1652
- output = migration(current);
1653
- }
1654
- catch (error) {
1655
- fail("migration_failed", `Block ${definition.type} migration to version ${step} threw.`, step, error);
1656
- }
1657
- try {
1658
- current = migrationResult(output, current.settings);
1659
- }
1660
- catch (error) {
1661
- fail("invalid_result", `Block ${definition.type} migration to version ${step} did not return {data, settings?} JSON objects.`, step, error);
1662
- }
1663
- }
1664
- return current;
1665
- }
1666
- /**
1667
- * Resolves the alt text of one media usage: a non-blank usage alt (such as the
1668
- * `image` block's `alt`), then a non-blank media alt, then an empty string.
1669
- */
1670
- export function effectiveAltText(usageAlt, mediaAlt) {
1671
- if (typeof usageAlt === "string" && usageAlt.trim().length > 0)
1672
- return usageAlt;
1673
- if (typeof mediaAlt === "string" && mediaAlt.trim().length > 0)
1674
- return mediaAlt;
1675
- return "";
1676
- }
1677
- /** Shared presentation rules for the independent scalar list settings. */
1678
- export function listLayoutSettingsVisibility() {
1679
- return deepFreeze({
1680
- layoutWrap: { setting: "layoutMode", values: ["flex-row", "flex-column"] },
1681
- layoutPreset: { setting: "layoutMode", values: ["grid"] },
1682
- });
1683
- }
1684
- /** Shared scalar settings for one explicitly adopted list, in any block. */
1685
- export function listLayoutSettings() {
1686
- const cells = (rects) => ({
1687
- cells: rects.map(([x, y, width, height]) => ({ x, y, width, height })),
1688
- });
1689
- const columns = (count) => cells(Array.from({ length: count }, (_, i) => [i * (12 / count), 0, 12 / count - 1, 12]));
1690
- return deepFreeze({
1691
- layoutMode: field.select({
1692
- options: ["flex-row", "flex-column", "grid"],
1693
- required: true,
1694
- defaultValue: "grid",
1695
- label: "Arrangement",
1696
- presentation: {
1697
- control: "cards",
1698
- choices: [
1699
- {
1700
- value: "flex-row",
1701
- label: "Horizontal",
1702
- description: "Items flow across rows.",
1703
- diagram: columns(3),
1704
- },
1705
- {
1706
- value: "flex-column",
1707
- label: "Vertical",
1708
- description: "Items flow down columns. Wrapping needs a height set in site CSS.",
1709
- diagram: cells([
1710
- [0, 0, 12, 3],
1711
- [0, 4, 12, 3],
1712
- [0, 8, 12, 3],
1713
- ]),
1714
- },
1715
- {
1716
- value: "grid",
1717
- label: "Grid",
1718
- description: "Items use the selected grid preset.",
1719
- diagram: cells([
1720
- [0, 0, 5, 5],
1721
- [6, 0, 5, 5],
1722
- [0, 6, 5, 5],
1723
- [6, 6, 5, 5],
1724
- ]),
1725
- },
1726
- ],
1727
- },
1728
- }),
1729
- layoutWrap: field.boolean({
1730
- defaultValue: true,
1731
- label: "Wrap items",
1732
- description: "Applies to horizontal and vertical flex lists. Vertical wrapping requires a height set in site CSS.",
1733
- }),
1734
- layoutPreset: field.select({
1735
- options: [
1736
- "auto",
1737
- "columns-2",
1738
- "columns-3",
1739
- "columns-4",
1740
- "narrow-wide",
1741
- "wide-narrow",
1742
- "featured-first",
1743
- ],
1744
- required: true,
1745
- defaultValue: "auto",
1746
- label: "Grid preset",
1747
- description: "Applies when Grid is selected. Schematics show composition; your site controls styling.",
1748
- presentation: {
1749
- control: "cards",
1750
- choices: [
1751
- {
1752
- value: "auto",
1753
- label: "Auto",
1754
- description: "As many equal columns as fit.",
1755
- diagram: cells([
1756
- [0, 0, 3, 5],
1757
- [4, 0, 3, 5],
1758
- [8, 0, 3, 5],
1759
- [0, 6, 3, 5],
1760
- [4, 6, 3, 5],
1761
- ]),
1762
- },
1763
- {
1764
- value: "columns-2",
1765
- label: "Two columns",
1766
- description: "Two equal columns from 32rem.",
1767
- diagram: columns(2),
1768
- },
1769
- {
1770
- value: "columns-3",
1771
- label: "Three columns",
1772
- description: "Two from 32rem, three from 48rem.",
1773
- diagram: columns(3),
1774
- },
1775
- {
1776
- value: "columns-4",
1777
- label: "Four columns",
1778
- description: "Two from 32rem, three from 48rem, four from 64rem.",
1779
- diagram: columns(4),
1780
- },
1781
- {
1782
- value: "narrow-wide",
1783
- label: "Narrow + wide",
1784
- description: "Alternating 1:2 columns from 32rem.",
1785
- diagram: cells([
1786
- [0, 0, 3, 12],
1787
- [4, 0, 8, 12],
1788
- ]),
1789
- },
1790
- {
1791
- value: "wide-narrow",
1792
- label: "Wide + narrow",
1793
- description: "Alternating 2:1 columns from 32rem.",
1794
- diagram: cells([
1795
- [0, 0, 8, 12],
1796
- [9, 0, 3, 12],
1797
- ]),
1798
- },
1799
- {
1800
- value: "featured-first",
1801
- label: "Featured first",
1802
- description: "First item spans two columns from 32rem.",
1803
- diagram: cells([
1804
- [0, 0, 12, 5],
1805
- [0, 6, 5, 5],
1806
- [6, 6, 5, 5],
1807
- ]),
1808
- },
1809
- ],
1810
- },
1811
- }),
1812
- });
1813
- }
1814
- // The opt-in full-screen original of the `image` and `gallery` blocks.
1815
- const lightboxSetting = field.boolean({
1816
- defaultValue: false,
1817
- description: "Opens the original image full screen when it is selected.",
1818
- label: "Open full screen",
1819
- });
1820
- // The optional link of an `image` block and of each `gallery` item.
1821
- const imageLinkField = field.url({
1822
- description: "Selecting the image opens this link instead of the full-screen view.",
1823
- label: "Link",
1824
- });
1825
- // The aspect ratio of a `videoEmbed` block and of each `gallery` video item.
1826
- const videoAspectRatioField = field.select({
1827
- options: ["16:9", "4:3", "1:1", "4:5", "9:16"],
1828
- required: true,
1829
- defaultValue: "16:9",
1830
- label: "Aspect ratio",
1831
- description: "Reserves the video area before the player loads.",
1832
- presentation: {
1833
- control: "cards",
1834
- choices: [
1835
- {
1836
- value: "16:9",
1837
- label: "16:9",
1838
- description: "Wide landscape.",
1839
- diagram: { cells: [{ x: 0, y: 2, width: 12, height: 7 }] },
1840
- },
1841
- {
1842
- value: "4:3",
1843
- label: "4:3",
1844
- description: "Classic landscape.",
1845
- diagram: { cells: [{ x: 0, y: 1, width: 12, height: 9 }] },
1846
- },
1847
- {
1848
- value: "1:1",
1849
- label: "1:1",
1850
- description: "Square.",
1851
- diagram: { cells: [{ x: 1, y: 1, width: 9, height: 9 }] },
1852
- },
1853
- {
1854
- value: "4:5",
1855
- label: "4:5",
1856
- description: "Portrait.",
1857
- diagram: { cells: [{ x: 2, y: 1, width: 8, height: 10 }] },
1858
- },
1859
- {
1860
- value: "9:16",
1861
- label: "9:16",
1862
- description: "Tall portrait.",
1863
- diagram: { cells: [{ x: 3, y: 0, width: 6, height: 11 }] },
1864
- },
1865
- ],
1866
- },
1867
- });
1868
- // The playback mode of a `videoEmbed` block and of each `gallery` video item.
1869
- const videoPlaybackField = field.select({
1870
- options: ["player", "ambient"],
1871
- required: true,
1872
- defaultValue: "player",
1873
- label: "Playback",
1874
- description: "Ambient videos play muted and loop without controls.",
1875
- presentation: {
1876
- control: "cards",
1877
- choices: [
1878
- { value: "player", label: "Player", description: "Visitors start the video." },
1879
- {
1880
- value: "ambient",
1881
- label: "Ambient",
1882
- description: "Muted, looping, no controls; respects reduced motion.",
1883
- },
1884
- ],
1885
- },
1886
- });
1887
- /** Starter blocks implemented exclusively through the public block and field DSL. */
1888
- export const builtInBlocks = deepFreeze({
1889
- cta: defineBlock({
1890
- description: "A heading and a link that prompts the reader to act.",
1891
- fields: {
1892
- actionLabel: field.text({ required: true }),
1893
- actionUrl: field.url({ required: true }),
1894
- body: field.richText(),
1895
- heading: field.text({ required: true }),
1896
- },
1897
- label: "Call to action",
1898
- type: "cta",
1899
- version: 1,
1900
- }),
1901
- gallery: defineBlock({
1902
- description: "A list of images and videos with selectable layouts and optional captions.",
1903
- fields: {
1904
- images: field.list({
1905
- defaultValue: [],
1906
- item: field.group({
1907
- // The kind comes first, then each kind reads image (or video) before
1908
- // its overrides: media, alt, caption, link or URL, title, caption,
1909
- // playback, aspect ratio.
1910
- fields: {
1911
- kind: field.select({
1912
- options: ["image", "video"],
1913
- required: true,
1914
- defaultValue: "image",
1915
- label: "Type",
1916
- presentation: {
1917
- control: "cards",
1918
- choices: [
1919
- {
1920
- value: "image",
1921
- label: "Image",
1922
- description: "A picture from the media library.",
1923
- },
1924
- { value: "video", label: "Video", description: "A YouTube or Vimeo video." },
1925
- ],
1926
- },
1927
- }),
1928
- media: field.media({ label: "Image", required: true }),
1929
- videoUrl: field.url({
1930
- required: true,
1931
- embedProviders: ["youtube", "vimeo"],
1932
- label: "Video URL",
1933
- description: "Paste a YouTube or Vimeo video link, not iframe code.",
1934
- }),
1935
- alt: field.text({
1936
- description: "Leave empty to use the media item's alt text.",
1937
- label: "Alt text",
1938
- }),
1939
- videoTitle: field.text({
1940
- required: true,
1941
- minLength: 1,
1942
- label: "Video title",
1943
- description: "Names the video for visitors using assistive technology.",
1944
- }),
1945
- caption: field.text({
1946
- description: "An empty image caption uses the media item's caption.",
1947
- label: "Caption",
1948
- }),
1949
- link: imageLinkField,
1950
- playback: videoPlaybackField,
1951
- aspectRatio: videoAspectRatioField,
1952
- },
1953
- visibility: {
1954
- media: { field: "kind", values: ["image"] },
1955
- alt: { field: "kind", values: ["image"] },
1956
- link: { field: "kind", values: ["image"] },
1957
- videoUrl: { field: "kind", values: ["video"] },
1958
- videoTitle: { field: "kind", values: ["video"] },
1959
- playback: { field: "kind", values: ["video"] },
1960
- aspectRatio: { field: "kind", values: ["video"] },
1961
- },
1962
- }),
1963
- itemLabel: "caption",
1964
- label: "Images and videos",
1965
- maxItems: 50,
1966
- minItems: 1,
1967
- }),
1968
- title: field.text({ label: "Title" }),
1969
- },
1970
- label: "Gallery",
1971
- // Version 2 only added the lightbox setting, version 3 only the optional
1972
- // item link and version 4 scalar layout defaults. Version 5 adds item kinds
1973
- // whose default makes every stored item an image; data stays valid.
1974
- migrations: {
1975
- 2: (block) => block,
1976
- 3: (block) => block,
1977
- 4: (block) => block,
1978
- 5: (block) => block,
1979
- },
1980
- settings: { ...listLayoutSettings(), lightbox: lightboxSetting },
1981
- settingsVisibility: listLayoutSettingsVisibility(),
1982
- settingsLayout: {
1983
- mode: "sections",
1984
- groups: [
1985
- { key: "layout", label: "Layout", fields: ["layoutMode", "layoutWrap", "layoutPreset"] },
1986
- { key: "behavior", label: "Behavior", fields: ["lightbox"] },
1987
- ],
1988
- },
1989
- type: "gallery",
1990
- version: 5,
1991
- }),
1992
- hero: defineBlock({
1993
- description: "Large heading with optional text, image, and action.",
1994
- fields: {
1995
- body: field.richText(),
1996
- eyebrow: field.text(),
1997
- heading: field.text({ required: true }),
1998
- image: field.media(),
1999
- primaryActionLabel: field.text(),
2000
- primaryActionUrl: field.url(),
2001
- },
2002
- label: "Hero",
2003
- type: "hero",
2004
- version: 1,
2005
- }),
2006
- image: defineBlock({
2007
- description: "A single image with an optional caption and alt text that overrides the media alt.",
2008
- // Media comes first so editors show the image before its overrides.
2009
- fields: {
2010
- media: field.media({ required: true }),
2011
- alt: field.text(),
2012
- caption: field.text(),
2013
- link: imageLinkField,
2014
- },
2015
- label: "Image",
2016
- // Version 2 only made `alt` optional, version 3 only added the lightbox
2017
- // setting and version 4 only the optional link, so earlier data is valid.
2018
- migrations: { 2: (block) => block, 3: (block) => block, 4: (block) => block },
2019
- settings: { lightbox: lightboxSetting },
2020
- type: "image",
2021
- version: 4,
2022
- }),
2023
- link: defineBlock({
2024
- description: "A link to a page or URL, presented as a button or text.",
2025
- fields: {
2026
- label: field.text({ label: "Label", minLength: 1, maxLength: 200, required: true }),
2027
- url: field.url({ label: "Destination", required: true }),
2028
- },
2029
- settings: {
2030
- appearance: field.select({
2031
- label: "Appearance",
2032
- options: ["button", "text"],
2033
- defaultValue: "button",
2034
- required: true,
2035
- }),
2036
- newTab: field.boolean({ label: "Open in new tab", defaultValue: false, required: true }),
2037
- },
2038
- label: "Link",
2039
- type: "link",
2040
- version: 1,
2041
- }),
2042
- navigation: defineBlock({
2043
- description: "A list of links with optional one-level submenus.",
2044
- fields: {
2045
- links: field.list({
2046
- defaultValue: [],
2047
- item: field.group({
2048
- fields: {
2049
- children: field.list({
2050
- item: field.group({
2051
- fields: {
2052
- label: field.text({ label: "Label", required: true }),
2053
- url: field.url({ label: "URL", required: true }),
2054
- },
2055
- }),
2056
- itemLabel: "label",
2057
- label: "Submenu links",
2058
- maxItems: 20,
2059
- }),
2060
- label: field.text({ label: "Label", required: true }),
2061
- url: field.url({
2062
- description: "Optional when the link has submenu links.",
2063
- label: "URL",
2064
- }),
2065
- },
2066
- }),
2067
- itemLabel: "label",
2068
- label: "Links",
2069
- maxItems: 20,
2070
- minItems: 1,
2071
- }),
2072
- name: field.text({
2073
- description: "Read by screen readers, for example Main or On this page.",
2074
- label: "Navigation name",
2075
- }),
2076
- },
2077
- label: "Navigation",
2078
- type: "navigation",
2079
- version: 1,
2080
- }),
2081
- quote: defineBlock({
2082
- description: "A quotation with optional attribution.",
2083
- fields: {
2084
- attribution: field.text(),
2085
- quote: field.text({ required: true }),
2086
- },
2087
- label: "Quote",
2088
- type: "quote",
2089
- version: 1,
2090
- }),
2091
- richText: defineBlock({
2092
- description: "Formatted text with headings, lists, and links.",
2093
- fields: { content: field.richText({ required: true }) },
2094
- label: "Rich text",
2095
- type: "richText",
2096
- version: 1,
2097
- }),
2098
- videoEmbed: defineBlock({
2099
- type: "videoEmbed",
2100
- version: 2,
2101
- label: "Video embed",
2102
- description: "A YouTube or Vimeo video with an optional image preview.",
2103
- migrations: { 2: (block) => block },
2104
- settings: {
2105
- aspectRatio: videoAspectRatioField,
2106
- playback: videoPlaybackField,
2107
- },
2108
- fields: {
2109
- url: field.url({
2110
- required: true,
2111
- embedProviders: ["youtube", "vimeo"],
2112
- label: "Video URL",
2113
- description: "Paste a YouTube or Vimeo video link, not iframe code.",
2114
- }),
2115
- title: field.text({
2116
- required: true,
2117
- minLength: 1,
2118
- label: "Title",
2119
- description: "Names the video for visitors using assistive technology.",
2120
- }),
2121
- poster: field.media({
2122
- label: "Preview image",
2123
- description: "Optional. Defers player loading until selected in Player mode; stays underneath Ambient playback.",
2124
- }),
2125
- caption: field.text({ label: "Caption" }),
2126
- },
2127
- }),
2128
- });
2129
- /** Maximum title length shared by draft, publish, REST, and admin validation. */
2130
- export const MAX_TITLE_LENGTH = 200;
2131
- /** Maximum slug length shared by publish, REST, and admin validation. */
2132
- export const MAX_SLUG_LENGTH = 100;
2133
- /** Maximum flat top-level block count for one entry. */
2134
- export const MAX_TOP_LEVEL_BLOCKS = 200;
2135
- /** Maximum UTF-8 bytes in fields JSON or a single block data JSON value. */
2136
- export const MAX_JSON_BYTES = 1_000_000;
2137
- /** Returns canonical JSON with recursively sorted object keys. */
2138
- export function canonicalizeJson(value) {
2139
- if (value === null ||
2140
- typeof value === "boolean" ||
2141
- typeof value === "number" ||
2142
- typeof value === "string") {
2143
- return JSON.stringify(value);
2144
- }
2145
- if (Array.isArray(value)) {
2146
- return `[${value.map(canonicalizeJson).join(",")}]`;
2147
- }
2148
- const object = value;
2149
- const entries = Object.keys(object)
2150
- .sort()
2151
- .map((key) => `${JSON.stringify(key)}:${canonicalizeJson(object[key])}`);
2152
- return `{${entries.join(",")}}`;
2153
- }
2154
- /** Gets the UTF-8 byte count of portable JSON through canonical serialization. */
2155
- export function canonicalJsonByteLength(value) {
2156
- const TextEncoderConstructor = globalThis.TextEncoder;
2157
- if (TextEncoderConstructor === undefined) {
2158
- throw new Error("TextEncoder is required for canonical JSON byte measurement.");
2159
- }
2160
- return new TextEncoderConstructor().encode(canonicalizeJson(value)).byteLength;
2161
- }
2162
- function getWebCrypto() {
2163
- const crypto = globalThis.crypto;
2164
- if (crypto === undefined) {
2165
- throw new Error("Web Crypto is required for canonical JSON hashing.");
2166
- }
2167
- return crypto;
2168
- }
2169
- /** Hashes canonical JSON UTF-8 bytes with Web Crypto SHA-256 as lowercase hexadecimal. */
2170
- export async function sha256CanonicalJson(value, webCrypto = getWebCrypto()) {
2171
- const TextEncoderConstructor = globalThis.TextEncoder;
2172
- if (TextEncoderConstructor === undefined) {
2173
- throw new Error("TextEncoder is required for canonical JSON hashing.");
2174
- }
2175
- const digest = new Uint8Array(await webCrypto.subtle.digest("SHA-256", new TextEncoderConstructor().encode(canonicalizeJson(value))));
2176
- return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
2177
- }
2178
- function assertJsonSize(value, path) {
2179
- if (canonicalJsonByteLength(value) > MAX_JSON_BYTES) {
2180
- invalid(path, "json_too_large", `must not exceed ${MAX_JSON_BYTES} UTF-8 bytes.`);
2181
- }
2182
- }
2183
- /** Validates system entry data and shared payload limits for a draft or publish candidate. */
2184
- export function validateEntryPayload(input, mode) {
2185
- if (input.kind !== "collection" && input.kind !== "global" && input.kind !== "page") {
2186
- invalid(["kind"], "invalid_model_kind", "must be page, collection, or global.");
2187
- }
2188
- if (typeof input.title !== "string" || input.title.length === 0) {
2189
- invalid(["title"], "missing_title", "is required.");
2190
- }
2191
- if (input.title.length > MAX_TITLE_LENGTH) {
2192
- invalid(["title"], "title_too_long", `must not exceed ${MAX_TITLE_LENGTH} characters.`);
2193
- }
2194
- if (input.slug !== undefined &&
2195
- (typeof input.slug !== "string" || input.slug.length > MAX_SLUG_LENGTH)) {
2196
- invalid(["slug"], "slug_too_long", `must not exceed ${MAX_SLUG_LENGTH} characters.`);
2197
- }
2198
- if (input.kind === "global" && input.slug !== undefined) {
2199
- invalid(["slug"], "slug_not_allowed", "is not allowed for a global.");
2200
- }
2201
- if (mode === "publish" &&
2202
- input.kind === "collection" &&
2203
- (input.slug === undefined || input.slug.length === 0)) {
2204
- invalid(["slug"], "missing_slug", "is required for collection publication.");
2205
- }
2206
- if (!Array.isArray(input.blocks)) {
2207
- invalid(["blocks"], "invalid_blocks", "must be an array.");
2208
- }
2209
- if (input.blocks.length > MAX_TOP_LEVEL_BLOCKS) {
2210
- invalid(["blocks"], "too_many_blocks", `must not contain more than ${MAX_TOP_LEVEL_BLOCKS} blocks.`);
2211
- }
2212
- assertJsonSize(input.fields, ["fields"]);
2213
- for (const [index, block] of input.blocks.entries()) {
2214
- if (!isRecord(block) || !Object.hasOwn(block, "data")) {
2215
- invalid(["blocks", index], "invalid_block", "must contain JSON data.");
2216
- }
2217
- assertJsonSize(block.data, ["blocks", index, "data"]);
2218
- }
2219
- return input;
2220
- }
2221
- /** Validates all system, model-field, and ordered block data for one content entry. */
2222
- export function validateEntryAggregate(input, model, registry, mode) {
2223
- if (input.kind !== model.kind) {
2224
- invalid(["kind"], "model_kind_mismatch", "must match the content model kind.");
2225
- }
2226
- validateEntryPayload({
2227
- blocks: input.blocks,
2228
- fields: {},
2229
- kind: input.kind,
2230
- ...(input.slug === undefined ? {} : { slug: input.slug }),
2231
- title: input.title,
2232
- }, mode);
2233
- const fields = validateModelFields(model.fields, input.fields, mode, ["fields"], model.visibility);
2234
- assertJsonSize(fields, ["fields"]);
2235
- const keys = new Set();
2236
- const anchors = new Set();
2237
- const blocks = [];
2238
- for (const [index, block] of input.blocks.entries()) {
2239
- const path = ["blocks", index];
2240
- if (!isRecord(block)) {
2241
- invalid(path, "invalid_block", "must be an object.");
2242
- }
2243
- assertExactKeys(block, ["data", "key", "schemaVersion", "type"], ["anchor", "className", "hidden", "settings"], path);
2244
- if (typeof block.key !== "string" || !BLOCK_KEY_PATTERN.test(block.key)) {
2245
- invalid([...path, "key"], "invalid_block_key", "must be a stable block key.");
2246
- }
2247
- if (keys.has(block.key)) {
2248
- invalid([...path, "key"], "duplicate_block_key", "must be unique within the entry.");
2249
- }
2250
- keys.add(block.key);
2251
- if (typeof block.type !== "string") {
2252
- invalid([...path, "type"], "invalid_block_type", "must be a string.");
2253
- }
2254
- if (!model.blocks.includes(block.type)) {
2255
- invalid([...path, "type"], "disallowed_block_type", "is not allowed by this model.");
2256
- }
2257
- const definition = registry.get(block.type);
2258
- if (definition === undefined) {
2259
- invalid([...path, "type"], "unregistered_block_type", "is not registered.");
2260
- }
2261
- if (block.schemaVersion !== definition.version) {
2262
- invalid([...path, "schemaVersion"], "stale_block_version", "does not match the registered version.");
2263
- }
2264
- if (block.anchor !== undefined) {
2265
- if (!isBlockAnchor(block.anchor)) {
2266
- invalid([...path, "anchor"], "invalid_block_anchor", `must start with a lowercase letter and use only lowercase letters, digits and hyphens, up to ${MAX_BLOCK_ANCHOR_LENGTH} characters.`);
2267
- }
2268
- if (anchors.has(block.anchor)) {
2269
- invalid([...path, "anchor"], "duplicate_block_anchor", "must be unique within the entry.");
2270
- }
2271
- anchors.add(block.anchor);
2272
- }
2273
- let className;
2274
- if (block.className !== undefined) {
2275
- className = normalizeBlockClassName(block.className);
2276
- if (className === undefined) {
2277
- invalid([...path, "className"], "invalid_block_class_name", `must hold 1 to ${MAX_BLOCK_CLASS_TOKENS} valid class tokens, up to ${MAX_BLOCK_CLASS_NAME_LENGTH} characters.`);
2278
- }
2279
- }
2280
- if (block.hidden !== undefined && typeof block.hidden !== "boolean") {
2281
- invalid([...path, "hidden"], "invalid_block_hidden", "must be a boolean.");
2282
- }
2283
- const hidden = block.hidden === true;
2284
- const settings = validateBlockSettings(definition, block.settings ?? {}, [...path, "settings"]);
2285
- assertJsonSize(block.data, [...path, "data"]);
2286
- // A hidden block is never delivered, so publication accepts it unfinished.
2287
- const data = validateBlockData(definition, block.data, hidden ? "draft" : mode, [
2288
- ...path,
2289
- "data",
2290
- ]);
2291
- assertJsonSize(data, [...path, "data"]);
2292
- blocks.push(deepFreeze({
2293
- ...(block.anchor === undefined ? {} : { anchor: block.anchor }),
2294
- ...(className === undefined ? {} : { className }),
2295
- data: data,
2296
- hidden,
2297
- key: block.key,
2298
- schemaVersion: block.schemaVersion,
2299
- settings,
2300
- type: block.type,
2301
- }));
2302
- }
2303
- validateSnapshotListBudget(model.fields, fields, blocks.map((block, index) => ({
2304
- fields: registry.get(block.type).fields,
2305
- data: block.data,
2306
- path: ["blocks", index, "data"],
2307
- })));
2308
- collectSnapshotInternalLinks(model.fields, fields, blocks.map((block) => ({
2309
- key: block.key,
2310
- fields: registry.get(block.type).fields,
2311
- data: block.data,
2312
- hidden: block.hidden,
2313
- })));
2314
- return deepFreeze({
2315
- blocks: deepFreeze(blocks),
2316
- fields,
2317
- kind: input.kind,
2318
- ...(input.slug === undefined ? {} : { slug: input.slug }),
2319
- title: input.title,
2320
- });
2321
- }
2322
- export { parseSchemaPath, encodeSchemaPath, schemaFieldAt } from "./schema-path.js";
2323
- /** Raw UTF-16 units: the existing text/textarea length contract, without trimming. */
2324
- export function textLength(value) {
2325
- return value.length;
2326
- }
2327
- /** Trimmed Unicode code points: the existing SEO title/description contract. */
2328
- export function seoTextLength(value) {
2329
- return [...value.trim()].length;
2330
- }
1
+ // Directory dependencies: shared ← fields ← references, blocks ← entries.
2
+ // shared
3
+ export { LaceError, InvariantError } from "./shared/errors.js";
4
+ export * from "./shared/objects.js";
5
+ export * from "./shared/identifiers.js";
6
+ export { FieldConfigurationError, ContentValidationError } from "./shared/errors.js";
7
+ export { isPortableJsonValue } from "./shared/json.js";
8
+ // fields
9
+ export * from "./fields/video-embeds.js";
10
+ export * from "./fields/internal-link-tokens.js";
11
+ export { parseSchemaPath, encodeSchemaPath, schemaFieldAt } from "./fields/schema-path.js";
12
+ export { fieldTypeCapabilities, FIELD_FILTER_OPERATIONS, fieldTypesWith, } from "./fields/capabilities.js";
13
+ export { FIELD_PRESENCE_OPERATIONS, MAX_FILTER_SELECT_VALUES, MAX_FILTER_TEXT_LENGTH, fieldFilterValueFailure, filterInstant, } from "./fields/filter-values.js";
14
+ export { isSafeUrl, isUrlFieldTarget, validateRichTextDocument } from "./fields/rich-text.js";
15
+ export { FIELD_KEY_PATTERN, FIELD_KEY_SOURCE, MAX_FIELD_CONTAINER_DEPTH, MAX_CONSECUTIVE_GROUPS, MAX_LIST_ITEMS, MAX_SNAPSHOT_LIST_ITEMS, visitFieldDefinition, } from "./fields/definitions.js";
16
+ export { normalizeFormLayout, formFieldKeys } from "./fields/layout.js";
17
+ export { normalizeFieldVisibility, effectiveVisibilityValues, isFieldVisible, } from "./fields/visibility.js";
18
+ export { compileFieldSchema, validateFieldValue, validateModelFields, publishedFieldValues, declaresFieldVisibility, validateSnapshotListBudget, textLength, seoTextLength, } from "./fields/validation.js";
19
+ export { field } from "./fields/builders.js";
20
+ export { toFieldMetadata } from "./fields/metadata.js";
21
+ export { normalizeFieldDefinition } from "./fields/normalization.js";
22
+ // references
23
+ export { encodeFieldPath, decodeFieldPath } from "./references/field-paths.js";
24
+ export { collectFieldMedia, detachFieldMedia, effectiveAltText } from "./references/media.js";
25
+ export { collectFieldInternalLinks, collectSnapshotInternalLinks, } from "./references/internal-links.js";
26
+ export { BLOCK_TYPE_PATTERN, BLOCK_TYPE_SOURCE, MAX_BLOCK_ANCHOR_LENGTH, MAX_BLOCK_CLASS_NAME_LENGTH, MAX_BLOCK_CLASS_TOKENS, MAX_BLOCK_CLASS_TOKEN_LENGTH, isBlockAnchor, normalizeBlockClassName, } from "./blocks/grammar.js";
27
+ export { publishedBlockData, defineBlock, toBlockMetadata, validateBlockData, validateBlockSettings, } from "./blocks/definition.js";
28
+ export { BlockConfigurationError } from "./blocks/errors.js";
29
+ export { BLOCK_SETTING_FIELD_TYPES, normalizeSettingsVisibility } from "./blocks/settings.js";
30
+ export { defineBlockRegistry, toBlockRegistryMetadata } from "./blocks/registry.js";
31
+ export { BlockMigrationError, migrateBlockData } from "./blocks/migration.js";
32
+ export { listLayoutItemFields, listLayoutSettingsVisibility, listLayoutSettings, } from "./blocks/list-layout.js";
33
+ export { builtInBlocks } from "./blocks/built-ins.js";
34
+ // entries
35
+ export * from "./entries/list-query-policy.js";
36
+ export { canonicalizeJson, canonicalJsonByteLength, sha256CanonicalJson, } from "./entries/canonical-json.js";
37
+ export { MAX_TITLE_LENGTH, MAX_TOP_LEVEL_BLOCKS, MAX_DRAFT_MEDIA_REFERENCES, MAX_JSON_BYTES, validateEntryPayload, validateEntryAggregate, } from "./entries/aggregate.js";
2331
38
  //# sourceMappingURL=index.js.map