@lacecms/content 0.1.0-alpha.4 → 0.1.0-alpha.6
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.
- package/dist/index.d.ts +378 -38
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +815 -57
- package/dist/index.js.map +1 -1
- package/dist/schema-path.d.ts +8 -0
- package/dist/schema-path.d.ts.map +1 -0
- package/dist/schema-path.js +34 -0
- package/dist/schema-path.js.map +1 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,52 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
|
+
/** Validates, detaches and freezes optional sibling layout metadata. */
|
|
3
|
+
export function normalizeFormLayout(value, fields, path = "layout") {
|
|
4
|
+
if (value === undefined)
|
|
5
|
+
return undefined;
|
|
6
|
+
const raw = normalizeJsonValue(value, path, new WeakSet());
|
|
7
|
+
if (!isRecord(raw) ||
|
|
8
|
+
Object.keys(raw).some((key) => !["mode", "groups"].includes(key)) ||
|
|
9
|
+
(raw.mode !== "sections" && raw.mode !== "tabs") ||
|
|
10
|
+
!Array.isArray(raw.groups) ||
|
|
11
|
+
raw.groups.length === 0)
|
|
12
|
+
fail(path, "must declare mode sections/tabs and nonempty groups.");
|
|
13
|
+
const keys = new Set();
|
|
14
|
+
const placed = new Set();
|
|
15
|
+
for (const [index, group] of raw.groups.entries()) {
|
|
16
|
+
const at = `${path}.groups.${index}`;
|
|
17
|
+
if (!isRecord(group) ||
|
|
18
|
+
Object.keys(group).some((key) => !["key", "label", "description", "fields"].includes(key)) ||
|
|
19
|
+
typeof group.key !== "string" ||
|
|
20
|
+
!FIELD_KEY_PATTERN.test(group.key) ||
|
|
21
|
+
keys.has(group.key) ||
|
|
22
|
+
typeof group.label !== "string" ||
|
|
23
|
+
!group.label.trim() ||
|
|
24
|
+
(group.description !== undefined && typeof group.description !== "string") ||
|
|
25
|
+
!Array.isArray(group.fields) ||
|
|
26
|
+
group.fields.length === 0)
|
|
27
|
+
fail(at, "must declare a unique key, nonempty label and fields.");
|
|
28
|
+
keys.add(group.key);
|
|
29
|
+
for (const key of group.fields) {
|
|
30
|
+
if (typeof key !== "string" || !Object.hasOwn(fields, key) || placed.has(key))
|
|
31
|
+
fail(at, `contains unknown or repeated field ${String(key)}.`);
|
|
32
|
+
placed.add(key);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return deepFreeze(raw);
|
|
36
|
+
}
|
|
37
|
+
/** Sibling field order used by rendering and validation summaries. */
|
|
38
|
+
export function formFieldKeys(fields, layout) {
|
|
39
|
+
const placed = layout?.groups.flatMap((group) => group.fields) ?? [];
|
|
40
|
+
return [...placed, ...Object.keys(fields).filter((key) => !placed.includes(key))];
|
|
41
|
+
}
|
|
42
|
+
/** Maximum containers along a descriptor branch. */
|
|
43
|
+
export const MAX_FIELD_CONTAINER_DEPTH = 6;
|
|
44
|
+
/** Maximum directly nested groups. */
|
|
45
|
+
export const MAX_CONSECUTIVE_GROUPS = 2;
|
|
46
|
+
/** Maximum items in any one list. */
|
|
47
|
+
export const MAX_LIST_ITEMS = 100;
|
|
48
|
+
/** Maximum sum of list lengths in a snapshot. */
|
|
49
|
+
export const MAX_SNAPSHOT_LIST_ITEMS = 500;
|
|
2
50
|
/** Thrown when a field builder receives a non-portable or contradictory option. */
|
|
3
51
|
export class FieldConfigurationError extends Error {
|
|
4
52
|
constructor(message) {
|
|
@@ -109,6 +157,7 @@ function deepFreeze(value) {
|
|
|
109
157
|
}
|
|
110
158
|
return value;
|
|
111
159
|
}
|
|
160
|
+
const RENAMED_FROM_PATTERN = /^[A-Za-z][A-Za-z0-9]*$/u;
|
|
112
161
|
function readOptionalString(options, name) {
|
|
113
162
|
const value = options[name];
|
|
114
163
|
if (value === undefined) {
|
|
@@ -151,11 +200,22 @@ function addCommonOptions(definition, options) {
|
|
|
151
200
|
if (description !== undefined) {
|
|
152
201
|
definition.description = description;
|
|
153
202
|
}
|
|
203
|
+
const placeholder = readOptionalString(options, "placeholder");
|
|
204
|
+
if (placeholder !== undefined)
|
|
205
|
+
definition.placeholder = placeholder;
|
|
206
|
+
const renamedFrom = readOptionalString(options, "renamedFrom");
|
|
207
|
+
if (renamedFrom !== undefined) {
|
|
208
|
+
if (!RENAMED_FROM_PATTERN.test(renamedFrom)) {
|
|
209
|
+
fail("options.renamedFrom", "must be a valid field key.");
|
|
210
|
+
}
|
|
211
|
+
definition.renamedFrom = renamedFrom;
|
|
212
|
+
}
|
|
154
213
|
definition.required = readOptionalBoolean(options, "required") ?? false;
|
|
155
214
|
}
|
|
156
215
|
function assertAllowedOptions(options, allowed) {
|
|
157
216
|
for (const key of Object.keys(options)) {
|
|
158
|
-
|
|
217
|
+
// Every field kind accepts the temporary `renamedFrom` hint.
|
|
218
|
+
if (!allowed.includes(key) && key !== "renamedFrom") {
|
|
159
219
|
fail(`options.${key}`, "is not supported by this field type.");
|
|
160
220
|
}
|
|
161
221
|
}
|
|
@@ -178,6 +238,7 @@ function buildStringField(type, input) {
|
|
|
178
238
|
"label",
|
|
179
239
|
"maxLength",
|
|
180
240
|
"minLength",
|
|
241
|
+
"placeholder",
|
|
181
242
|
"required",
|
|
182
243
|
]);
|
|
183
244
|
const definition = { type };
|
|
@@ -194,13 +255,19 @@ function buildStringField(type, input) {
|
|
|
194
255
|
definition.maxLength = maxLength;
|
|
195
256
|
}
|
|
196
257
|
addDefault(definition, options, (value) => typeof value === "string" &&
|
|
197
|
-
(minLength === undefined || value
|
|
198
|
-
(maxLength === undefined || value
|
|
258
|
+
(minLength === undefined || textLength(value) >= minLength) &&
|
|
259
|
+
(maxLength === undefined || textLength(value) <= maxLength), "must be a string that conforms to the declared length constraints.");
|
|
199
260
|
return deepFreeze(definition);
|
|
200
261
|
}
|
|
201
262
|
function buildStringValueField(type, input) {
|
|
202
263
|
const options = normalizeOptions(input ?? {});
|
|
203
|
-
assertAllowedOptions(options, [
|
|
264
|
+
assertAllowedOptions(options, [
|
|
265
|
+
"defaultValue",
|
|
266
|
+
"description",
|
|
267
|
+
"label",
|
|
268
|
+
"required",
|
|
269
|
+
...(type === "url" ? ["placeholder"] : []),
|
|
270
|
+
]);
|
|
204
271
|
const definition = { type };
|
|
205
272
|
addCommonOptions(definition, options);
|
|
206
273
|
addDefault(definition, options, (value) => typeof value === "string", "must be a string.");
|
|
@@ -208,6 +275,14 @@ function buildStringValueField(type, input) {
|
|
|
208
275
|
}
|
|
209
276
|
/** Builders for portable Lace field descriptors. */
|
|
210
277
|
export const field = {
|
|
278
|
+
/** Define named child fields stored as one plain object. */
|
|
279
|
+
group(options) {
|
|
280
|
+
return normalizeCompositeOptions("group", options);
|
|
281
|
+
},
|
|
282
|
+
/** Define an ordered array of scalar or group values. */
|
|
283
|
+
list(options) {
|
|
284
|
+
return normalizeCompositeOptions("list", options);
|
|
285
|
+
},
|
|
211
286
|
/** Define a single-line text field. */
|
|
212
287
|
text(options) {
|
|
213
288
|
return buildStringField("text", options);
|
|
@@ -219,7 +294,13 @@ export const field = {
|
|
|
219
294
|
/** Define a safe Tiptap JSON field. */
|
|
220
295
|
richText(options) {
|
|
221
296
|
const normalized = normalizeOptions(options ?? {});
|
|
222
|
-
assertAllowedOptions(normalized, [
|
|
297
|
+
assertAllowedOptions(normalized, [
|
|
298
|
+
"defaultValue",
|
|
299
|
+
"description",
|
|
300
|
+
"label",
|
|
301
|
+
"required",
|
|
302
|
+
"placeholder",
|
|
303
|
+
]);
|
|
223
304
|
const definition = { type: "richText" };
|
|
224
305
|
addCommonOptions(definition, normalized);
|
|
225
306
|
addDefault(definition, normalized, (value) => isSafeRichTextDocument(value), "must be a safe rich-text document.");
|
|
@@ -232,6 +313,7 @@ export const field = {
|
|
|
232
313
|
"defaultValue",
|
|
233
314
|
"description",
|
|
234
315
|
"label",
|
|
316
|
+
"placeholder",
|
|
235
317
|
"max",
|
|
236
318
|
"min",
|
|
237
319
|
"required",
|
|
@@ -280,6 +362,7 @@ export const field = {
|
|
|
280
362
|
"description",
|
|
281
363
|
"label",
|
|
282
364
|
"options",
|
|
365
|
+
"placeholder",
|
|
283
366
|
"required",
|
|
284
367
|
]);
|
|
285
368
|
const rawChoices = normalized.options;
|
|
@@ -317,11 +400,154 @@ export const field = {
|
|
|
317
400
|
* representation. Runtime schemas and callbacks are deliberately absent.
|
|
318
401
|
*/
|
|
319
402
|
export function toFieldMetadata(definition) {
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
403
|
+
return normalizeFieldDefinition(definition);
|
|
404
|
+
}
|
|
405
|
+
/** Reads own data properties without executing configuration accessors. */
|
|
406
|
+
function descriptorRecord(value, path) {
|
|
407
|
+
if (!isRecord(value))
|
|
408
|
+
fail(path, "must be a plain field-definition object.");
|
|
409
|
+
const output = {};
|
|
410
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
411
|
+
if (typeof key !== "string")
|
|
412
|
+
fail(path, "must not contain symbol keys.");
|
|
413
|
+
const property = Object.getOwnPropertyDescriptor(value, key);
|
|
414
|
+
if (!property.enumerable || !("value" in property))
|
|
415
|
+
fail(`${path}.${key}`, "must be an enumerable data property.");
|
|
416
|
+
Object.defineProperty(output, key, { value: property.value, enumerable: true });
|
|
417
|
+
}
|
|
418
|
+
return output;
|
|
419
|
+
}
|
|
420
|
+
function normalizeCompositeOptions(type, value) {
|
|
421
|
+
const options = descriptorRecord(value, "options");
|
|
422
|
+
if (Object.hasOwn(options, "type"))
|
|
423
|
+
fail("options.type", "is not supported.");
|
|
424
|
+
return normalizeFieldDefinition({ ...options, type });
|
|
425
|
+
}
|
|
426
|
+
/** Validates and detaches a descriptor, including forged JSON/configuration input. */
|
|
427
|
+
export function normalizeFieldDefinition(value) {
|
|
428
|
+
return normalizeDescriptor(value, "definition", 0, 0, new WeakSet());
|
|
429
|
+
}
|
|
430
|
+
function normalizeDescriptor(value, path, depth, groups, ancestors) {
|
|
431
|
+
const raw = descriptorRecord(value, path);
|
|
432
|
+
if (ancestors.has(value))
|
|
433
|
+
fail(path, "must not contain a cyclic reference.");
|
|
434
|
+
const { type, ...options } = raw;
|
|
435
|
+
if (type !== "group" && type !== "list") {
|
|
436
|
+
try {
|
|
437
|
+
switch (type) {
|
|
438
|
+
case "boolean":
|
|
439
|
+
return field.boolean(options);
|
|
440
|
+
case "date":
|
|
441
|
+
return field.date(options);
|
|
442
|
+
case "datetime":
|
|
443
|
+
return field.datetime(options);
|
|
444
|
+
case "media":
|
|
445
|
+
return field.media(options);
|
|
446
|
+
case "number":
|
|
447
|
+
return field.number(options);
|
|
448
|
+
case "richText":
|
|
449
|
+
return field.richText(options);
|
|
450
|
+
case "select":
|
|
451
|
+
return field.select(options);
|
|
452
|
+
case "text":
|
|
453
|
+
return field.text(options);
|
|
454
|
+
case "textarea":
|
|
455
|
+
return field.textarea(options);
|
|
456
|
+
case "url":
|
|
457
|
+
return field.url(options);
|
|
458
|
+
default:
|
|
459
|
+
fail(`${path}.type`, "must name a supported field type.");
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
catch (error) {
|
|
463
|
+
if (error instanceof FieldConfigurationError)
|
|
464
|
+
fail(path, error.message);
|
|
465
|
+
throw error;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
if (depth >= MAX_FIELD_CONTAINER_DEPTH)
|
|
469
|
+
fail(path, `must not exceed ${MAX_FIELD_CONTAINER_DEPTH} containers.`);
|
|
470
|
+
if (type === "group" && groups >= MAX_CONSECUTIVE_GROUPS)
|
|
471
|
+
fail(path, `must not exceed ${MAX_CONSECUTIVE_GROUPS} consecutive groups.`);
|
|
472
|
+
const allowed = [
|
|
473
|
+
"label",
|
|
474
|
+
"description",
|
|
475
|
+
"required",
|
|
476
|
+
"defaultValue",
|
|
477
|
+
"renamedFrom",
|
|
478
|
+
...(type === "group" ? ["fields", "layout"] : ["item", "minItems", "maxItems", "itemLabel"]),
|
|
479
|
+
];
|
|
480
|
+
for (const key of Object.keys(options))
|
|
481
|
+
if (!allowed.includes(key))
|
|
482
|
+
fail(`${path}.${key}`, "is not supported by this field type.");
|
|
483
|
+
const { fields, item, defaultValue, ...common } = options;
|
|
484
|
+
const normalized = normalizeOptions(common);
|
|
485
|
+
const result = { type };
|
|
486
|
+
addCommonOptions(result, normalized);
|
|
487
|
+
ancestors.add(value);
|
|
488
|
+
try {
|
|
489
|
+
if (type === "group") {
|
|
490
|
+
const children = descriptorRecord(fields, `${path}.fields`);
|
|
491
|
+
const output = {};
|
|
492
|
+
for (const [key, child] of Object.entries(children)) {
|
|
493
|
+
if (!FIELD_KEY_PATTERN.test(key))
|
|
494
|
+
fail(`${path}.fields.${key}`, "must be a valid field key.");
|
|
495
|
+
Object.defineProperty(output, key, {
|
|
496
|
+
value: normalizeDescriptor(child, `${path}.fields.${key}`, depth + 1, groups + 1, ancestors),
|
|
497
|
+
enumerable: true,
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
result.fields = output;
|
|
501
|
+
const layout = normalizeFormLayout(options.layout, output, `${path}.layout`);
|
|
502
|
+
if (layout !== undefined)
|
|
503
|
+
result.layout = layout;
|
|
504
|
+
}
|
|
505
|
+
else {
|
|
506
|
+
const child = descriptorRecord(item, `${path}.item`);
|
|
507
|
+
if (child.type === "list")
|
|
508
|
+
fail(`${path}.item`, "must not be a direct list of lists.");
|
|
509
|
+
if (Object.hasOwn(child, "renamedFrom"))
|
|
510
|
+
fail(`${path}.item.renamedFrom`, "list item descriptors have no field key and cannot be renamed.");
|
|
511
|
+
result.item = normalizeDescriptor(item, `${path}.item`, depth + 1, 0, ancestors);
|
|
512
|
+
if (Object.hasOwn(options, "itemLabel")) {
|
|
513
|
+
const key = options.itemLabel;
|
|
514
|
+
const itemDefinition = result.item;
|
|
515
|
+
if (typeof key !== "string" ||
|
|
516
|
+
!FIELD_KEY_PATTERN.test(key) ||
|
|
517
|
+
itemDefinition.type !== "group" ||
|
|
518
|
+
!Object.hasOwn(itemDefinition.fields, key) ||
|
|
519
|
+
!["text", "textarea", "select", "url"].includes(itemDefinition.fields[key].type))
|
|
520
|
+
fail(`${path}.itemLabel`, "must name an immediate text, textarea, select or URL group child.");
|
|
521
|
+
result.itemLabel = key;
|
|
522
|
+
}
|
|
523
|
+
const min = readOptionalFiniteNumber(normalized, "minItems", true);
|
|
524
|
+
const max = readOptionalFiniteNumber(normalized, "maxItems", true);
|
|
525
|
+
if ((min ?? 0) > (max ?? MAX_LIST_ITEMS) || (max ?? MAX_LIST_ITEMS) > MAX_LIST_ITEMS)
|
|
526
|
+
fail(path, `list bounds must satisfy 0 ≤ minItems ≤ maxItems ≤ ${MAX_LIST_ITEMS}.`);
|
|
527
|
+
if (min !== undefined)
|
|
528
|
+
result.minItems = min;
|
|
529
|
+
if (max !== undefined)
|
|
530
|
+
result.maxItems = max;
|
|
531
|
+
}
|
|
532
|
+
if (Object.hasOwn(options, "defaultValue")) {
|
|
533
|
+
const portableDefault = normalizeJsonValue(defaultValue, `${path}.defaultValue`, new WeakSet());
|
|
534
|
+
try {
|
|
535
|
+
normalizeFieldValue(result, portableDefault, "draft", [], {
|
|
536
|
+
count: 0,
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
catch (error) {
|
|
540
|
+
if (error instanceof ContentValidationError)
|
|
541
|
+
fail(`${path}.defaultValue`, error.message);
|
|
542
|
+
throw error;
|
|
543
|
+
}
|
|
544
|
+
result.defaultValue = portableDefault;
|
|
545
|
+
}
|
|
546
|
+
return deepFreeze(result);
|
|
547
|
+
}
|
|
548
|
+
finally {
|
|
549
|
+
ancestors.delete(value);
|
|
323
550
|
}
|
|
324
|
-
return deepFreeze(normalized);
|
|
325
551
|
}
|
|
326
552
|
/** Thrown when submitted content fails a portable validation contract. */
|
|
327
553
|
export class ContentValidationError extends Error {
|
|
@@ -389,7 +615,13 @@ function assertMarks(value, path) {
|
|
|
389
615
|
if (!isRecord(mark.attrs)) {
|
|
390
616
|
invalid([...markPath, "attrs"], "invalid_link_attributes", "must be an object.");
|
|
391
617
|
}
|
|
392
|
-
assertExactKeys(mark.attrs, ["href"], [], [...markPath, "attrs"]);
|
|
618
|
+
assertExactKeys(mark.attrs, ["href"], ["target", "rel"], [...markPath, "attrs"]);
|
|
619
|
+
if (Object.hasOwn(mark.attrs, "target") && mark.attrs.target !== "_blank") {
|
|
620
|
+
invalid([...markPath, "attrs", "target"], "invalid_link_target", 'must be "_blank".');
|
|
621
|
+
}
|
|
622
|
+
if (Object.hasOwn(mark.attrs, "rel") && mark.attrs.rel !== "nofollow") {
|
|
623
|
+
invalid([...markPath, "attrs", "rel"], "invalid_link_rel", 'must be "nofollow".');
|
|
624
|
+
}
|
|
393
625
|
if (!isSafeUrl(mark.attrs.href)) {
|
|
394
626
|
invalid([...markPath, "attrs", "href"], "unsafe_url", "must be an approved URL.");
|
|
395
627
|
}
|
|
@@ -430,10 +662,20 @@ function assertRichTextNode(value, path) {
|
|
|
430
662
|
}
|
|
431
663
|
return;
|
|
432
664
|
}
|
|
433
|
-
if (value.type === "hardBreak") {
|
|
665
|
+
if (value.type === "hardBreak" || value.type === "horizontalRule") {
|
|
434
666
|
assertExactKeys(value, ["type"], [], path);
|
|
435
667
|
return;
|
|
436
668
|
}
|
|
669
|
+
if (value.type === "codeBlock") {
|
|
670
|
+
assertExactKeys(value, ["type"], ["content"], path);
|
|
671
|
+
if (Object.hasOwn(value, "content")) {
|
|
672
|
+
assertRichTextChildren(value.content, [...path, "content"], ["text"]);
|
|
673
|
+
for (const [index, child] of value.content.entries()) {
|
|
674
|
+
assertExactKeys(child, ["type", "text"], [], [...path, "content", index]);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
437
679
|
if (value.type === "paragraph") {
|
|
438
680
|
assertExactKeys(value, ["type"], ["content"], path);
|
|
439
681
|
if (Object.hasOwn(value, "content")) {
|
|
@@ -447,8 +689,11 @@ function assertRichTextNode(value, path) {
|
|
|
447
689
|
invalid([...path, "attrs"], "invalid_heading_attributes", "must be an object.");
|
|
448
690
|
}
|
|
449
691
|
assertExactKeys(value.attrs, ["level"], [], [...path, "attrs"]);
|
|
450
|
-
if (value.attrs.level !== 1 &&
|
|
451
|
-
|
|
692
|
+
if (value.attrs.level !== 1 &&
|
|
693
|
+
value.attrs.level !== 2 &&
|
|
694
|
+
value.attrs.level !== 3 &&
|
|
695
|
+
value.attrs.level !== 4) {
|
|
696
|
+
invalid([...path, "attrs", "level"], "invalid_heading_level", "must be 1, 2, 3, or 4.");
|
|
452
697
|
}
|
|
453
698
|
if (Object.hasOwn(value, "content")) {
|
|
454
699
|
assertRichTextChildren(value.content, [...path, "content"], ["hardBreak", "text"]);
|
|
@@ -462,12 +707,12 @@ function assertRichTextNode(value, path) {
|
|
|
462
707
|
}
|
|
463
708
|
if (value.type === "listItem") {
|
|
464
709
|
assertExactKeys(value, ["content", "type"], [], path);
|
|
465
|
-
assertRichTextChildren(value.content, [...path, "content"], ["bulletList", "orderedList", "paragraph"]);
|
|
710
|
+
assertRichTextChildren(value.content, [...path, "content"], ["bulletList", "orderedList", "paragraph", "horizontalRule", "codeBlock"]);
|
|
466
711
|
return;
|
|
467
712
|
}
|
|
468
713
|
if (value.type === "blockquote") {
|
|
469
714
|
assertExactKeys(value, ["content", "type"], [], path);
|
|
470
|
-
assertRichTextChildren(value.content, [...path, "content"], ["bulletList", "orderedList", "paragraph"]);
|
|
715
|
+
assertRichTextChildren(value.content, [...path, "content"], ["bulletList", "orderedList", "paragraph", "horizontalRule", "codeBlock"]);
|
|
471
716
|
return;
|
|
472
717
|
}
|
|
473
718
|
invalid([...path, "type"], "unknown_node", "is not permitted.");
|
|
@@ -478,7 +723,15 @@ export function validateRichTextDocument(value) {
|
|
|
478
723
|
invalid([], "invalid_document", "must be a doc node.");
|
|
479
724
|
}
|
|
480
725
|
assertExactKeys(value, ["content", "type"], [], []);
|
|
481
|
-
assertRichTextChildren(value.content, ["content"], [
|
|
726
|
+
assertRichTextChildren(value.content, ["content"], [
|
|
727
|
+
"blockquote",
|
|
728
|
+
"bulletList",
|
|
729
|
+
"heading",
|
|
730
|
+
"orderedList",
|
|
731
|
+
"paragraph",
|
|
732
|
+
"horizontalRule",
|
|
733
|
+
"codeBlock",
|
|
734
|
+
]);
|
|
482
735
|
return value;
|
|
483
736
|
}
|
|
484
737
|
function isSafeRichTextDocument(value) {
|
|
@@ -496,6 +749,10 @@ function isSafeRichTextDocument(value) {
|
|
|
496
749
|
/** Visits a field descriptor exhaustively. */
|
|
497
750
|
export function visitFieldDefinition(definition, visitor) {
|
|
498
751
|
switch (definition.type) {
|
|
752
|
+
case "group":
|
|
753
|
+
return visitor.group(definition);
|
|
754
|
+
case "list":
|
|
755
|
+
return visitor.list(definition);
|
|
499
756
|
case "boolean":
|
|
500
757
|
return visitor.boolean(definition);
|
|
501
758
|
case "date":
|
|
@@ -536,6 +793,8 @@ function isUtcIsoDatetime(value) {
|
|
|
536
793
|
}
|
|
537
794
|
function isFieldValue(definition, value) {
|
|
538
795
|
return visitFieldDefinition(definition, {
|
|
796
|
+
group: () => false,
|
|
797
|
+
list: () => false,
|
|
539
798
|
boolean: () => typeof value === "boolean",
|
|
540
799
|
date: () => isCalendarDate(value),
|
|
541
800
|
datetime: () => isUtcIsoDatetime(value),
|
|
@@ -547,55 +806,223 @@ function isFieldValue(definition, value) {
|
|
|
547
806
|
richText: () => isSafeRichTextDocument(value),
|
|
548
807
|
select: (fieldDefinition) => typeof value === "string" && fieldDefinition.options.includes(value),
|
|
549
808
|
text: (fieldDefinition) => typeof value === "string" &&
|
|
550
|
-
(fieldDefinition.minLength === undefined || value
|
|
551
|
-
(fieldDefinition.maxLength === undefined || value
|
|
809
|
+
(fieldDefinition.minLength === undefined || textLength(value) >= fieldDefinition.minLength) &&
|
|
810
|
+
(fieldDefinition.maxLength === undefined || textLength(value) <= fieldDefinition.maxLength),
|
|
552
811
|
textarea: (fieldDefinition) => typeof value === "string" &&
|
|
553
|
-
(fieldDefinition.minLength === undefined || value
|
|
554
|
-
(fieldDefinition.maxLength === undefined || value
|
|
812
|
+
(fieldDefinition.minLength === undefined || textLength(value) >= fieldDefinition.minLength) &&
|
|
813
|
+
(fieldDefinition.maxLength === undefined || textLength(value) <= fieldDefinition.maxLength),
|
|
555
814
|
url: () => isSafeUrl(value),
|
|
556
815
|
});
|
|
557
816
|
}
|
|
558
|
-
/** Compiles a field definition
|
|
559
|
-
export function compileFieldSchema(definition) {
|
|
560
|
-
return v.custom((value) =>
|
|
817
|
+
/** Compiles a field definition with the same normalization as aggregate validation. */
|
|
818
|
+
export function compileFieldSchema(definition, mode = "publish") {
|
|
819
|
+
return v.pipe(v.custom((value) => {
|
|
820
|
+
try {
|
|
821
|
+
normalizeFieldValue(definition, value, mode, [], { count: 0 });
|
|
822
|
+
return true;
|
|
823
|
+
}
|
|
824
|
+
catch (error) {
|
|
825
|
+
if (error instanceof ContentValidationError)
|
|
826
|
+
return false;
|
|
827
|
+
throw error;
|
|
828
|
+
}
|
|
829
|
+
}), v.transform((value) => normalizeFieldValue(definition, value, mode, [], { count: 0 })));
|
|
830
|
+
}
|
|
831
|
+
/** Validates and normalizes one present value; absence is handled by its field map. */
|
|
832
|
+
export function validateFieldValue(definition, value, path = [], mode = "publish") {
|
|
833
|
+
return normalizeFieldValue(definition, value, mode, path, { count: 0 });
|
|
834
|
+
}
|
|
835
|
+
function addListItems(length, path, budget) {
|
|
836
|
+
budget.count += length;
|
|
837
|
+
if (budget.count > MAX_SNAPSHOT_LIST_ITEMS)
|
|
838
|
+
invalid(path, "too_many_list_items", `must not exceed ${MAX_SNAPSHOT_LIST_ITEMS} list elements per snapshot.`);
|
|
561
839
|
}
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
840
|
+
function normalizeFieldValue(definition, value, mode, path, budget) {
|
|
841
|
+
if (definition.type === "group") {
|
|
842
|
+
if (!isRecord(value))
|
|
843
|
+
invalid(path, "invalid_field_value", "must be a group object.");
|
|
844
|
+
return normalizeFieldMap(definition.fields, value, mode, path, budget);
|
|
845
|
+
}
|
|
846
|
+
if (definition.type === "list") {
|
|
847
|
+
if (!Array.isArray(value))
|
|
848
|
+
invalid(path, "invalid_field_value", "must be a list.");
|
|
849
|
+
if (value.length > (definition.maxItems ?? MAX_LIST_ITEMS))
|
|
850
|
+
invalid(path, "list_too_long", `must contain at most ${definition.maxItems ?? MAX_LIST_ITEMS} items.`);
|
|
851
|
+
if (mode === "publish" && value.length < (definition.minItems ?? 0))
|
|
852
|
+
invalid(path, "list_too_short", `must contain at least ${definition.minItems} items for publication.`);
|
|
853
|
+
addListItems(value.length, path, budget);
|
|
854
|
+
return Array.from({ length: value.length }, (_, index) => {
|
|
855
|
+
if (!Object.hasOwn(value, index))
|
|
856
|
+
invalid([...path, index], "invalid_field_value", "must contain a value.");
|
|
857
|
+
return normalizeFieldValue(definition.item, value[index], mode, [...path, index], budget);
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
if (!isFieldValue(definition, value))
|
|
566
861
|
invalid(path, "invalid_field_value", "does not conform to its field definition.");
|
|
567
|
-
|
|
568
|
-
return result.output;
|
|
862
|
+
return value;
|
|
569
863
|
}
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
if (!isRecord(value)) {
|
|
864
|
+
function normalizeFieldMap(definitions, value, mode, path, budget) {
|
|
865
|
+
if (!isRecord(value))
|
|
573
866
|
invalid(path, "invalid_fields", "must be an object.");
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
if (!Object.hasOwn(definitions, key)) {
|
|
867
|
+
for (const key of Object.keys(value))
|
|
868
|
+
if (!Object.hasOwn(definitions, key))
|
|
577
869
|
invalid([...path, key], "unknown_field", "is not defined by this model.");
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
870
|
const output = {};
|
|
581
871
|
for (const [key, definition] of Object.entries(definitions)) {
|
|
582
|
-
|
|
583
|
-
|
|
872
|
+
let present;
|
|
873
|
+
if (Object.hasOwn(value, key))
|
|
874
|
+
present = value[key];
|
|
875
|
+
else if (Object.hasOwn(definition, "defaultValue"))
|
|
876
|
+
present = definition.defaultValue;
|
|
877
|
+
else {
|
|
878
|
+
if (mode === "publish" && definition.required)
|
|
879
|
+
invalid([...path, key], "missing_required_field", "is required for publication.");
|
|
584
880
|
continue;
|
|
585
881
|
}
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
882
|
+
Object.defineProperty(output, key, {
|
|
883
|
+
value: normalizeFieldValue(definition, present, mode, [...path, key], budget),
|
|
884
|
+
enumerable: true,
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
return output;
|
|
888
|
+
}
|
|
889
|
+
/** Validates field data for either an incomplete draft or a publish candidate. */
|
|
890
|
+
export function validateModelFields(definitions, value, mode, path = []) {
|
|
891
|
+
return normalizeFieldMap(definitions, value, mode, path, { count: 0 });
|
|
892
|
+
}
|
|
893
|
+
/** Checks already normalized model/block values against one snapshot-wide budget. */
|
|
894
|
+
export function validateSnapshotListBudget(fields, values, blocks) {
|
|
895
|
+
const budget = { count: 0 };
|
|
896
|
+
function count(definition, value, path) {
|
|
897
|
+
if (definition.type === "group" && isRecord(value))
|
|
898
|
+
walk(definition.fields, value, path);
|
|
899
|
+
if (definition.type === "list" && Array.isArray(value)) {
|
|
900
|
+
addListItems(value.length, path, budget);
|
|
901
|
+
value.forEach((item, index) => count(definition.item, item, [...path, index]));
|
|
589
902
|
}
|
|
590
|
-
|
|
591
|
-
|
|
903
|
+
}
|
|
904
|
+
function walk(definitions, data, path) {
|
|
905
|
+
for (const [key, definition] of Object.entries(definitions))
|
|
906
|
+
count(definition, data[key], [...path, key]);
|
|
907
|
+
}
|
|
908
|
+
walk(fields, values, ["fields"]);
|
|
909
|
+
blocks.forEach((block) => walk(block.fields, block.data, block.path));
|
|
910
|
+
}
|
|
911
|
+
/** Finds declared media leaves only; ordinary strings never become references. */
|
|
912
|
+
export function collectFieldMedia(definitions, values) {
|
|
913
|
+
const references = [];
|
|
914
|
+
function visit(definition, value, path) {
|
|
915
|
+
if (definition.type === "media" && typeof value === "string")
|
|
916
|
+
references.push({ mediaId: value, path });
|
|
917
|
+
else if (definition.type === "group" && isRecord(value))
|
|
918
|
+
walk(definition.fields, value, path);
|
|
919
|
+
else if (definition.type === "list" && Array.isArray(value))
|
|
920
|
+
value.forEach((item, index) => visit(definition.item, item, [...path, index]));
|
|
921
|
+
}
|
|
922
|
+
function walk(fields, data, path) {
|
|
923
|
+
for (const [key, definition] of Object.entries(fields))
|
|
924
|
+
visit(definition, data[key], [...path, key]);
|
|
925
|
+
}
|
|
926
|
+
walk(definitions, values, []);
|
|
927
|
+
return references;
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Removes one media item from declared media leaves: a matching media value is
|
|
931
|
+
* dropped from its object, and a matching element of a list of media is removed
|
|
932
|
+
* from the list. Every other value is kept; the input is returned unchanged when
|
|
933
|
+
* nothing matches.
|
|
934
|
+
*/
|
|
935
|
+
export function detachFieldMedia(definitions, values, mediaId) {
|
|
936
|
+
const matches = (definition, value) => definition.type === "media" && value === mediaId;
|
|
937
|
+
function visit(definition, value) {
|
|
938
|
+
if (definition.type === "group" && isRecord(value))
|
|
939
|
+
return walk(definition.fields, value);
|
|
940
|
+
if (definition.type !== "list" || !Array.isArray(value))
|
|
941
|
+
return value;
|
|
942
|
+
let changed = false;
|
|
943
|
+
const items = [];
|
|
944
|
+
for (const item of value) {
|
|
945
|
+
if (matches(definition.item, item)) {
|
|
946
|
+
changed = true;
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
const next = visit(definition.item, item);
|
|
950
|
+
changed ||= next !== item;
|
|
951
|
+
items.push(next);
|
|
952
|
+
}
|
|
953
|
+
return changed ? items : value;
|
|
954
|
+
}
|
|
955
|
+
function walk(fields, data) {
|
|
956
|
+
let result;
|
|
957
|
+
for (const [key, definition] of Object.entries(fields)) {
|
|
958
|
+
const value = data[key];
|
|
959
|
+
if (matches(definition, value)) {
|
|
960
|
+
result ??= { ...data };
|
|
961
|
+
delete result[key];
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
const next = visit(definition, value);
|
|
965
|
+
if (next !== value) {
|
|
966
|
+
result ??= { ...data };
|
|
967
|
+
result[key] = next;
|
|
968
|
+
}
|
|
592
969
|
}
|
|
970
|
+
return result ?? data;
|
|
593
971
|
}
|
|
594
|
-
return
|
|
972
|
+
return walk(definitions, values);
|
|
973
|
+
}
|
|
974
|
+
/** Keeps legacy scalar keys; nested locations are relative JSON Pointers. */
|
|
975
|
+
export function encodeFieldPath(path) {
|
|
976
|
+
if (path.length === 1)
|
|
977
|
+
return String(path[0]);
|
|
978
|
+
return ("/" + path.map((part) => String(part).replaceAll("~", "~0").replaceAll("/", "~1")).join("/"));
|
|
979
|
+
}
|
|
980
|
+
/** Reads a stored reference path; numeric tokens are list indices under the field-key grammar. */
|
|
981
|
+
export function decodeFieldPath(path) {
|
|
982
|
+
if (!path.startsWith("/"))
|
|
983
|
+
return [path];
|
|
984
|
+
return path
|
|
985
|
+
.slice(1)
|
|
986
|
+
.split("/")
|
|
987
|
+
.map((part) => {
|
|
988
|
+
const decoded = part.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
989
|
+
return /^(?:0|[1-9][0-9]*)$/u.test(decoded) ? Number(decoded) : decoded;
|
|
990
|
+
});
|
|
595
991
|
}
|
|
596
992
|
const BLOCK_TYPE_PATTERN = /^[A-Za-z][A-Za-z0-9-]*$/u;
|
|
597
993
|
const BLOCK_KEY_PATTERN = /^(?:[A-Za-z][A-Za-z0-9-]*|[0-7][0-9A-HJKMNP-TV-Z]{25})$/u;
|
|
598
994
|
const FIELD_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9]*$/u;
|
|
995
|
+
/** Maximum length of a block anchor. */
|
|
996
|
+
export const MAX_BLOCK_ANCHOR_LENGTH = 64;
|
|
997
|
+
/** Maximum length of a normalized block class name. */
|
|
998
|
+
export const MAX_BLOCK_CLASS_NAME_LENGTH = 256;
|
|
999
|
+
/** Maximum number of class tokens in a block class name. */
|
|
1000
|
+
export const MAX_BLOCK_CLASS_TOKENS = 16;
|
|
1001
|
+
/** Maximum length of one block class token. */
|
|
1002
|
+
export const MAX_BLOCK_CLASS_TOKEN_LENGTH = 64;
|
|
1003
|
+
const BLOCK_ANCHOR_PATTERN = /^[a-z][a-z0-9-]{0,63}$/u;
|
|
1004
|
+
const BLOCK_CLASS_TOKEN_PATTERN = /^[A-Za-z_-][A-Za-z0-9_\-:/.%#[\]]*$/u;
|
|
1005
|
+
/** Whether a value is a block anchor: a lowercase letter, then lowercase letters, digits and hyphens. */
|
|
1006
|
+
export function isBlockAnchor(value) {
|
|
1007
|
+
return typeof value === "string" && BLOCK_ANCHOR_PATTERN.test(value);
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Normalizes a block class name: whitespace-separated class tokens, repeats
|
|
1011
|
+
* dropped, joined with single spaces. Returns `undefined` for a non-string,
|
|
1012
|
+
* blank or invalid value.
|
|
1013
|
+
*/
|
|
1014
|
+
export function normalizeBlockClassName(value) {
|
|
1015
|
+
if (typeof value !== "string")
|
|
1016
|
+
return undefined;
|
|
1017
|
+
const tokens = [...new Set(value.split(/[\t\n\f\r ]+/u).filter((token) => token !== ""))];
|
|
1018
|
+
if (tokens.length === 0 ||
|
|
1019
|
+
tokens.length > MAX_BLOCK_CLASS_TOKENS ||
|
|
1020
|
+
tokens.some((token) => token.length > MAX_BLOCK_CLASS_TOKEN_LENGTH || !BLOCK_CLASS_TOKEN_PATTERN.test(token))) {
|
|
1021
|
+
return undefined;
|
|
1022
|
+
}
|
|
1023
|
+
const normalized = tokens.join(" ");
|
|
1024
|
+
return normalized.length > MAX_BLOCK_CLASS_NAME_LENGTH ? undefined : normalized;
|
|
1025
|
+
}
|
|
599
1026
|
/** Thrown when a block definition or registry is not portable or internally consistent. */
|
|
600
1027
|
export class BlockConfigurationError extends Error {
|
|
601
1028
|
constructor(message) {
|
|
@@ -603,37 +1030,117 @@ export class BlockConfigurationError extends Error {
|
|
|
603
1030
|
this.name = "BlockConfigurationError";
|
|
604
1031
|
}
|
|
605
1032
|
}
|
|
1033
|
+
/** Field types a block setting may use; every setting declares a default. */
|
|
1034
|
+
export const BLOCK_SETTING_FIELD_TYPES = Object.freeze([
|
|
1035
|
+
"boolean",
|
|
1036
|
+
"number",
|
|
1037
|
+
"select",
|
|
1038
|
+
"text",
|
|
1039
|
+
]);
|
|
606
1040
|
function blockFail(message) {
|
|
607
1041
|
throw new BlockConfigurationError(message);
|
|
608
1042
|
}
|
|
609
|
-
function normalizeBlockFields(value) {
|
|
1043
|
+
function normalizeBlockFields(value, name = "fields") {
|
|
610
1044
|
if (!isRecord(value)) {
|
|
611
|
-
blockFail(
|
|
1045
|
+
blockFail(`${name} must be a plain object.`);
|
|
612
1046
|
}
|
|
613
1047
|
const fields = {};
|
|
614
1048
|
for (const [key, definition] of Object.entries(value)) {
|
|
615
1049
|
if (!FIELD_KEY_PATTERN.test(key)) {
|
|
616
|
-
blockFail(
|
|
1050
|
+
blockFail(`${name}.${key} must be a valid field key.`);
|
|
617
1051
|
}
|
|
618
1052
|
try {
|
|
619
|
-
|
|
1053
|
+
const metadata = toFieldMetadata(definition);
|
|
1054
|
+
const rejectHints = (field, path) => {
|
|
1055
|
+
if (Object.hasOwn(field, "renamedFrom"))
|
|
1056
|
+
blockFail(`${path} must not declare renamedFrom; block data changes use block versions.`);
|
|
1057
|
+
if (field.type === "group")
|
|
1058
|
+
for (const [childKey, child] of Object.entries(field.fields))
|
|
1059
|
+
rejectHints(child, `${path}.fields.${childKey}`);
|
|
1060
|
+
if (field.type === "list")
|
|
1061
|
+
rejectHints(field.item, `${path}.item`);
|
|
1062
|
+
};
|
|
1063
|
+
rejectHints(metadata, `${name}.${key}`);
|
|
1064
|
+
fields[key] = metadata;
|
|
620
1065
|
}
|
|
621
1066
|
catch (error) {
|
|
622
1067
|
if (error instanceof FieldConfigurationError) {
|
|
623
|
-
blockFail(
|
|
1068
|
+
blockFail(`${name}.${key} must be a field definition.`);
|
|
624
1069
|
}
|
|
625
1070
|
throw error;
|
|
626
1071
|
}
|
|
627
1072
|
}
|
|
628
1073
|
return deepFreeze(fields);
|
|
629
1074
|
}
|
|
1075
|
+
const SETTING_TYPES = new Set(BLOCK_SETTING_FIELD_TYPES);
|
|
1076
|
+
/** Normalizes declared settings; an empty map yields none. */
|
|
1077
|
+
function normalizeBlockSettings(value) {
|
|
1078
|
+
if (value === undefined)
|
|
1079
|
+
return undefined;
|
|
1080
|
+
const settings = normalizeBlockFields(value, "settings");
|
|
1081
|
+
for (const [key, definition] of Object.entries(settings)) {
|
|
1082
|
+
if (!SETTING_TYPES.has(definition.type)) {
|
|
1083
|
+
blockFail(`settings.${key} must be a select, boolean, number or text field.`);
|
|
1084
|
+
}
|
|
1085
|
+
if (!Object.hasOwn(definition, "defaultValue")) {
|
|
1086
|
+
blockFail(`settings.${key} must declare a defaultValue.`);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
return Object.keys(settings).length === 0 ? undefined : settings;
|
|
1090
|
+
}
|
|
1091
|
+
const MIGRATION_KEY_PATTERN = /^[1-9][0-9]*$/u;
|
|
1092
|
+
function normalizeBlockMigrations(value, version) {
|
|
1093
|
+
if (value === undefined)
|
|
1094
|
+
return undefined;
|
|
1095
|
+
if (!isRecord(value)) {
|
|
1096
|
+
blockFail("migrations must be a plain object keyed by target version.");
|
|
1097
|
+
}
|
|
1098
|
+
const keys = Object.keys(value);
|
|
1099
|
+
if (keys.length === 0)
|
|
1100
|
+
return undefined;
|
|
1101
|
+
const targets = [];
|
|
1102
|
+
for (const key of keys) {
|
|
1103
|
+
const target = Number(key);
|
|
1104
|
+
if (!MIGRATION_KEY_PATTERN.test(key) || !Number.isSafeInteger(target)) {
|
|
1105
|
+
blockFail(`migrations.${key} must be keyed by an integer target version.`);
|
|
1106
|
+
}
|
|
1107
|
+
if (target < 2 || target > version) {
|
|
1108
|
+
blockFail(`migrations.${key} must target a version from 2 to ${version}.`);
|
|
1109
|
+
}
|
|
1110
|
+
if (typeof value[key] !== "function") {
|
|
1111
|
+
blockFail(`migrations.${key} must be a function.`);
|
|
1112
|
+
}
|
|
1113
|
+
targets.push(target);
|
|
1114
|
+
}
|
|
1115
|
+
targets.sort((left, right) => left - right);
|
|
1116
|
+
if (targets.at(-1) !== version) {
|
|
1117
|
+
blockFail(`migrations must include the current version ${version}.`);
|
|
1118
|
+
}
|
|
1119
|
+
for (let index = 1; index < targets.length; index += 1) {
|
|
1120
|
+
if (targets[index] !== targets[index - 1] + 1) {
|
|
1121
|
+
blockFail(`migrations.${targets[index - 1] + 1} is missing; migrations must be contiguous.`);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
return Object.freeze(Object.fromEntries(targets.map((target) => [target, value[String(target)]])));
|
|
1125
|
+
}
|
|
630
1126
|
/** Defines a versioned block using only portable field descriptors. */
|
|
631
1127
|
export function defineBlock(input) {
|
|
632
1128
|
if (!isRecord(input)) {
|
|
633
1129
|
blockFail("block must be a plain object.");
|
|
634
1130
|
}
|
|
635
1131
|
for (const key of Object.keys(input)) {
|
|
636
|
-
if (!new Set([
|
|
1132
|
+
if (!new Set([
|
|
1133
|
+
"defaultValue",
|
|
1134
|
+
"description",
|
|
1135
|
+
"fields",
|
|
1136
|
+
"label",
|
|
1137
|
+
"migrations",
|
|
1138
|
+
"layout",
|
|
1139
|
+
"settingsLayout",
|
|
1140
|
+
"settings",
|
|
1141
|
+
"type",
|
|
1142
|
+
"version",
|
|
1143
|
+
]).has(key)) {
|
|
637
1144
|
blockFail(`block.${key} is not permitted.`);
|
|
638
1145
|
}
|
|
639
1146
|
}
|
|
@@ -652,6 +1159,10 @@ export function defineBlock(input) {
|
|
|
652
1159
|
blockFail("description must be a string when provided.");
|
|
653
1160
|
}
|
|
654
1161
|
const fields = normalizeBlockFields(input.fields);
|
|
1162
|
+
const migrations = normalizeBlockMigrations(input.migrations, input.version);
|
|
1163
|
+
const settings = normalizeBlockSettings(input.settings);
|
|
1164
|
+
const layout = normalizeFormLayout(input.layout, fields, `block.${input.type}.layout`);
|
|
1165
|
+
const settingsLayout = normalizeFormLayout(input.settingsLayout, settings ?? {}, `block.${input.type}.settingsLayout`);
|
|
655
1166
|
let defaultValue;
|
|
656
1167
|
if (input.defaultValue !== undefined) {
|
|
657
1168
|
try {
|
|
@@ -673,6 +1184,10 @@ export function defineBlock(input) {
|
|
|
673
1184
|
...(input.description === undefined ? {} : { description: input.description }),
|
|
674
1185
|
fields,
|
|
675
1186
|
...(input.label === undefined ? {} : { label: input.label }),
|
|
1187
|
+
...(migrations === undefined ? {} : { migrations }),
|
|
1188
|
+
...(layout === undefined ? {} : { layout }),
|
|
1189
|
+
...(settingsLayout === undefined ? {} : { settingsLayout }),
|
|
1190
|
+
...(settings === undefined ? {} : { settings }),
|
|
676
1191
|
type: input.type,
|
|
677
1192
|
validate: (value, mode) => {
|
|
678
1193
|
if (!isRecord(value)) {
|
|
@@ -695,6 +1210,22 @@ export function toBlockMetadata(definition) {
|
|
|
695
1210
|
toFieldMetadata(fieldDefinition),
|
|
696
1211
|
])),
|
|
697
1212
|
...(definition.label === undefined ? {} : { label: definition.label }),
|
|
1213
|
+
...(definition.layout === undefined
|
|
1214
|
+
? {}
|
|
1215
|
+
: { layout: normalizeFormLayout(definition.layout, definition.fields) }),
|
|
1216
|
+
...(definition.settingsLayout === undefined
|
|
1217
|
+
? {}
|
|
1218
|
+
: {
|
|
1219
|
+
settingsLayout: normalizeFormLayout(definition.settingsLayout, definition.settings ?? {}),
|
|
1220
|
+
}),
|
|
1221
|
+
...(definition.settings === undefined
|
|
1222
|
+
? {}
|
|
1223
|
+
: {
|
|
1224
|
+
settings: Object.fromEntries(Object.entries(definition.settings).map(([key, fieldDefinition]) => [
|
|
1225
|
+
key,
|
|
1226
|
+
toFieldMetadata(fieldDefinition),
|
|
1227
|
+
])),
|
|
1228
|
+
}),
|
|
698
1229
|
type: definition.type,
|
|
699
1230
|
version: definition.version,
|
|
700
1231
|
};
|
|
@@ -727,6 +1258,115 @@ export function validateBlockData(definition, value, mode, path = []) {
|
|
|
727
1258
|
const withDefault = definition.defaultValue === undefined ? value : { ...definition.defaultValue, ...value };
|
|
728
1259
|
return validateModelFields(definition.fields, withDefault, mode, path);
|
|
729
1260
|
}
|
|
1261
|
+
/**
|
|
1262
|
+
* Validates a block's settings record against its declared settings, filling
|
|
1263
|
+
* every default; a block that declares none accepts only `{}`.
|
|
1264
|
+
*/
|
|
1265
|
+
export function validateBlockSettings(definition, value, path = []) {
|
|
1266
|
+
if (!isRecord(value)) {
|
|
1267
|
+
invalid(path, "invalid_block_settings", "must be an object.");
|
|
1268
|
+
}
|
|
1269
|
+
return validateModelFields(definition.settings ?? {}, value, "draft", path);
|
|
1270
|
+
}
|
|
1271
|
+
/** Thrown when stored block data cannot be migrated to its definition's version. */
|
|
1272
|
+
export class BlockMigrationError extends Error {
|
|
1273
|
+
code;
|
|
1274
|
+
blockType;
|
|
1275
|
+
fromVersion;
|
|
1276
|
+
toVersion;
|
|
1277
|
+
step;
|
|
1278
|
+
constructor(code, blockType, fromVersion, toVersion, message,
|
|
1279
|
+
/** Target version of the failing step, for failed or invalid steps. */
|
|
1280
|
+
step, options) {
|
|
1281
|
+
super(message, options);
|
|
1282
|
+
this.code = code;
|
|
1283
|
+
this.blockType = blockType;
|
|
1284
|
+
this.fromVersion = fromVersion;
|
|
1285
|
+
this.toVersion = toVersion;
|
|
1286
|
+
this.step = step;
|
|
1287
|
+
this.name = "BlockMigrationError";
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
function jsonObject(value, name) {
|
|
1291
|
+
if (value instanceof Promise || !isRecord(value)) {
|
|
1292
|
+
throw new FieldConfigurationError(`${name} must be a plain JSON object.`);
|
|
1293
|
+
}
|
|
1294
|
+
return deepFreeze(normalizeJsonValue(value, name, new WeakSet()));
|
|
1295
|
+
}
|
|
1296
|
+
/** Checks a step result: `{data, settings?}`; absent settings keep `previous`. */
|
|
1297
|
+
function migrationResult(value, previous) {
|
|
1298
|
+
if (value instanceof Promise || !isRecord(value)) {
|
|
1299
|
+
throw new FieldConfigurationError("result must be a plain object.");
|
|
1300
|
+
}
|
|
1301
|
+
for (const key of Object.keys(value)) {
|
|
1302
|
+
if (key !== "data" && key !== "settings") {
|
|
1303
|
+
throw new FieldConfigurationError(`result.${key} is not permitted.`);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
if (!Object.hasOwn(value, "data")) {
|
|
1307
|
+
throw new FieldConfigurationError("result.data is required.");
|
|
1308
|
+
}
|
|
1309
|
+
return Object.freeze({
|
|
1310
|
+
data: jsonObject(value.data, "result.data"),
|
|
1311
|
+
settings: value.settings === undefined ? previous : jsonObject(value.settings, "result.settings"),
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
/**
|
|
1315
|
+
* Migrates stored block data and settings from `fromVersion` to the
|
|
1316
|
+
* definition's version by composing its declared migrations in ascending
|
|
1317
|
+
* order. Each step receives a detached, frozen copy. The result is not
|
|
1318
|
+
* validated against the definition.
|
|
1319
|
+
*/
|
|
1320
|
+
export function migrateBlockData(definition, block, fromVersion) {
|
|
1321
|
+
const toVersion = definition.version;
|
|
1322
|
+
function fail(code, message, step, cause) {
|
|
1323
|
+
throw new BlockMigrationError(code, definition.type, fromVersion, toVersion, message, step, cause === undefined ? undefined : { cause });
|
|
1324
|
+
}
|
|
1325
|
+
if (fromVersion > toVersion) {
|
|
1326
|
+
fail("version_ahead", `Block ${definition.type} version ${fromVersion} is newer than ${toVersion}.`);
|
|
1327
|
+
}
|
|
1328
|
+
let current;
|
|
1329
|
+
try {
|
|
1330
|
+
current = Object.freeze({
|
|
1331
|
+
data: jsonObject(block.data, "data"),
|
|
1332
|
+
settings: jsonObject(block.settings, "settings"),
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
catch (error) {
|
|
1336
|
+
fail("invalid_result", `Block ${definition.type} data or settings are not JSON objects.`, fromVersion, error);
|
|
1337
|
+
}
|
|
1338
|
+
for (let step = fromVersion + 1; step <= toVersion; step += 1) {
|
|
1339
|
+
const migration = definition.migrations?.[step];
|
|
1340
|
+
if (migration === undefined) {
|
|
1341
|
+
fail("missing_step", `Block ${definition.type} has no migration from version ${fromVersion} to ${toVersion}.`);
|
|
1342
|
+
}
|
|
1343
|
+
let output;
|
|
1344
|
+
try {
|
|
1345
|
+
output = migration(current);
|
|
1346
|
+
}
|
|
1347
|
+
catch (error) {
|
|
1348
|
+
fail("migration_failed", `Block ${definition.type} migration to version ${step} threw.`, step, error);
|
|
1349
|
+
}
|
|
1350
|
+
try {
|
|
1351
|
+
current = migrationResult(output, current.settings);
|
|
1352
|
+
}
|
|
1353
|
+
catch (error) {
|
|
1354
|
+
fail("invalid_result", `Block ${definition.type} migration to version ${step} did not return {data, settings?} JSON objects.`, step, error);
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
return current;
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Resolves the alt text of one media usage: a non-blank usage alt (such as the
|
|
1361
|
+
* `image` block's `alt`), then a non-blank media alt, then an empty string.
|
|
1362
|
+
*/
|
|
1363
|
+
export function effectiveAltText(usageAlt, mediaAlt) {
|
|
1364
|
+
if (typeof usageAlt === "string" && usageAlt.trim().length > 0)
|
|
1365
|
+
return usageAlt;
|
|
1366
|
+
if (typeof mediaAlt === "string" && mediaAlt.trim().length > 0)
|
|
1367
|
+
return mediaAlt;
|
|
1368
|
+
return "";
|
|
1369
|
+
}
|
|
730
1370
|
/** Starter blocks implemented exclusively through the public block and field DSL. */
|
|
731
1371
|
export const builtInBlocks = deepFreeze({
|
|
732
1372
|
cta: defineBlock({
|
|
@@ -741,6 +1381,35 @@ export const builtInBlocks = deepFreeze({
|
|
|
741
1381
|
type: "cta",
|
|
742
1382
|
version: 1,
|
|
743
1383
|
}),
|
|
1384
|
+
gallery: defineBlock({
|
|
1385
|
+
description: "A grid of images with optional captions.",
|
|
1386
|
+
fields: {
|
|
1387
|
+
images: field.list({
|
|
1388
|
+
defaultValue: [],
|
|
1389
|
+
item: field.group({
|
|
1390
|
+
fields: {
|
|
1391
|
+
alt: field.text({
|
|
1392
|
+
description: "Leave empty to use the media item's alt text.",
|
|
1393
|
+
label: "Alt text",
|
|
1394
|
+
}),
|
|
1395
|
+
caption: field.text({
|
|
1396
|
+
description: "Leave empty to use the media item's caption.",
|
|
1397
|
+
label: "Caption",
|
|
1398
|
+
}),
|
|
1399
|
+
media: field.media({ label: "Image", required: true }),
|
|
1400
|
+
},
|
|
1401
|
+
}),
|
|
1402
|
+
itemLabel: "caption",
|
|
1403
|
+
label: "Images",
|
|
1404
|
+
maxItems: 50,
|
|
1405
|
+
minItems: 1,
|
|
1406
|
+
}),
|
|
1407
|
+
title: field.text({ label: "Title" }),
|
|
1408
|
+
},
|
|
1409
|
+
label: "Gallery",
|
|
1410
|
+
type: "gallery",
|
|
1411
|
+
version: 1,
|
|
1412
|
+
}),
|
|
744
1413
|
hero: defineBlock({
|
|
745
1414
|
description: "Large heading with optional text, image, and action.",
|
|
746
1415
|
fields: {
|
|
@@ -756,14 +1425,55 @@ export const builtInBlocks = deepFreeze({
|
|
|
756
1425
|
version: 1,
|
|
757
1426
|
}),
|
|
758
1427
|
image: defineBlock({
|
|
759
|
-
description: "A single image with alt text
|
|
1428
|
+
description: "A single image with an optional caption and alt text that overrides the media alt.",
|
|
760
1429
|
fields: {
|
|
761
|
-
alt: field.text(
|
|
1430
|
+
alt: field.text(),
|
|
762
1431
|
caption: field.text(),
|
|
763
1432
|
media: field.media({ required: true }),
|
|
764
1433
|
},
|
|
765
1434
|
label: "Image",
|
|
1435
|
+
// Version 2 only made `alt` optional, so version 1 data is already valid.
|
|
1436
|
+
migrations: { 2: (block) => block },
|
|
766
1437
|
type: "image",
|
|
1438
|
+
version: 2,
|
|
1439
|
+
}),
|
|
1440
|
+
navigation: defineBlock({
|
|
1441
|
+
description: "A list of links with optional one-level submenus.",
|
|
1442
|
+
fields: {
|
|
1443
|
+
links: field.list({
|
|
1444
|
+
defaultValue: [],
|
|
1445
|
+
item: field.group({
|
|
1446
|
+
fields: {
|
|
1447
|
+
children: field.list({
|
|
1448
|
+
item: field.group({
|
|
1449
|
+
fields: {
|
|
1450
|
+
label: field.text({ label: "Label", required: true }),
|
|
1451
|
+
url: field.url({ label: "URL", required: true }),
|
|
1452
|
+
},
|
|
1453
|
+
}),
|
|
1454
|
+
itemLabel: "label",
|
|
1455
|
+
label: "Submenu links",
|
|
1456
|
+
maxItems: 20,
|
|
1457
|
+
}),
|
|
1458
|
+
label: field.text({ label: "Label", required: true }),
|
|
1459
|
+
url: field.url({
|
|
1460
|
+
description: "Optional when the link has submenu links.",
|
|
1461
|
+
label: "URL",
|
|
1462
|
+
}),
|
|
1463
|
+
},
|
|
1464
|
+
}),
|
|
1465
|
+
itemLabel: "label",
|
|
1466
|
+
label: "Links",
|
|
1467
|
+
maxItems: 20,
|
|
1468
|
+
minItems: 1,
|
|
1469
|
+
}),
|
|
1470
|
+
name: field.text({
|
|
1471
|
+
description: "Read by screen readers, for example Main or On this page.",
|
|
1472
|
+
label: "Navigation name",
|
|
1473
|
+
}),
|
|
1474
|
+
},
|
|
1475
|
+
label: "Navigation",
|
|
1476
|
+
type: "navigation",
|
|
767
1477
|
version: 1,
|
|
768
1478
|
}),
|
|
769
1479
|
quote: defineBlock({
|
|
@@ -840,8 +1550,8 @@ function assertJsonSize(value, path) {
|
|
|
840
1550
|
}
|
|
841
1551
|
/** Validates system entry data and shared payload limits for a draft or publish candidate. */
|
|
842
1552
|
export function validateEntryPayload(input, mode) {
|
|
843
|
-
if (input.kind !== "collection" && input.kind !== "page") {
|
|
844
|
-
invalid(["kind"], "invalid_model_kind", "must be page or
|
|
1553
|
+
if (input.kind !== "collection" && input.kind !== "global" && input.kind !== "page") {
|
|
1554
|
+
invalid(["kind"], "invalid_model_kind", "must be page, collection, or global.");
|
|
845
1555
|
}
|
|
846
1556
|
if (typeof input.title !== "string" || input.title.length === 0) {
|
|
847
1557
|
invalid(["title"], "missing_title", "is required.");
|
|
@@ -853,6 +1563,9 @@ export function validateEntryPayload(input, mode) {
|
|
|
853
1563
|
(typeof input.slug !== "string" || input.slug.length > MAX_SLUG_LENGTH)) {
|
|
854
1564
|
invalid(["slug"], "slug_too_long", `must not exceed ${MAX_SLUG_LENGTH} characters.`);
|
|
855
1565
|
}
|
|
1566
|
+
if (input.kind === "global" && input.slug !== undefined) {
|
|
1567
|
+
invalid(["slug"], "slug_not_allowed", "is not allowed for a global.");
|
|
1568
|
+
}
|
|
856
1569
|
if (mode === "publish" &&
|
|
857
1570
|
input.kind === "collection" &&
|
|
858
1571
|
(input.slug === undefined || input.slug.length === 0)) {
|
|
@@ -888,13 +1601,14 @@ export function validateEntryAggregate(input, model, registry, mode) {
|
|
|
888
1601
|
const fields = validateModelFields(model.fields, input.fields, mode, ["fields"]);
|
|
889
1602
|
assertJsonSize(fields, ["fields"]);
|
|
890
1603
|
const keys = new Set();
|
|
1604
|
+
const anchors = new Set();
|
|
891
1605
|
const blocks = [];
|
|
892
1606
|
for (const [index, block] of input.blocks.entries()) {
|
|
893
1607
|
const path = ["blocks", index];
|
|
894
1608
|
if (!isRecord(block)) {
|
|
895
1609
|
invalid(path, "invalid_block", "must be an object.");
|
|
896
1610
|
}
|
|
897
|
-
assertExactKeys(block, ["data", "key", "schemaVersion", "type"], [], path);
|
|
1611
|
+
assertExactKeys(block, ["data", "key", "schemaVersion", "type"], ["anchor", "className", "hidden", "settings"], path);
|
|
898
1612
|
if (typeof block.key !== "string" || !BLOCK_KEY_PATTERN.test(block.key)) {
|
|
899
1613
|
invalid([...path, "key"], "invalid_block_key", "must be a stable block key.");
|
|
900
1614
|
}
|
|
@@ -915,15 +1629,50 @@ export function validateEntryAggregate(input, model, registry, mode) {
|
|
|
915
1629
|
if (block.schemaVersion !== definition.version) {
|
|
916
1630
|
invalid([...path, "schemaVersion"], "stale_block_version", "does not match the registered version.");
|
|
917
1631
|
}
|
|
1632
|
+
if (block.anchor !== undefined) {
|
|
1633
|
+
if (!isBlockAnchor(block.anchor)) {
|
|
1634
|
+
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.`);
|
|
1635
|
+
}
|
|
1636
|
+
if (anchors.has(block.anchor)) {
|
|
1637
|
+
invalid([...path, "anchor"], "duplicate_block_anchor", "must be unique within the entry.");
|
|
1638
|
+
}
|
|
1639
|
+
anchors.add(block.anchor);
|
|
1640
|
+
}
|
|
1641
|
+
let className;
|
|
1642
|
+
if (block.className !== undefined) {
|
|
1643
|
+
className = normalizeBlockClassName(block.className);
|
|
1644
|
+
if (className === undefined) {
|
|
1645
|
+
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.`);
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
if (block.hidden !== undefined && typeof block.hidden !== "boolean") {
|
|
1649
|
+
invalid([...path, "hidden"], "invalid_block_hidden", "must be a boolean.");
|
|
1650
|
+
}
|
|
1651
|
+
const hidden = block.hidden === true;
|
|
1652
|
+
const settings = validateBlockSettings(definition, block.settings ?? {}, [...path, "settings"]);
|
|
918
1653
|
assertJsonSize(block.data, [...path, "data"]);
|
|
919
|
-
|
|
1654
|
+
// A hidden block is never delivered, so publication accepts it unfinished.
|
|
1655
|
+
const data = validateBlockData(definition, block.data, hidden ? "draft" : mode, [
|
|
1656
|
+
...path,
|
|
1657
|
+
"data",
|
|
1658
|
+
]);
|
|
1659
|
+
assertJsonSize(data, [...path, "data"]);
|
|
920
1660
|
blocks.push(deepFreeze({
|
|
1661
|
+
...(block.anchor === undefined ? {} : { anchor: block.anchor }),
|
|
1662
|
+
...(className === undefined ? {} : { className }),
|
|
921
1663
|
data: data,
|
|
1664
|
+
hidden,
|
|
922
1665
|
key: block.key,
|
|
923
1666
|
schemaVersion: block.schemaVersion,
|
|
1667
|
+
settings,
|
|
924
1668
|
type: block.type,
|
|
925
1669
|
}));
|
|
926
1670
|
}
|
|
1671
|
+
validateSnapshotListBudget(model.fields, fields, blocks.map((block, index) => ({
|
|
1672
|
+
fields: registry.get(block.type).fields,
|
|
1673
|
+
data: block.data,
|
|
1674
|
+
path: ["blocks", index, "data"],
|
|
1675
|
+
})));
|
|
927
1676
|
return deepFreeze({
|
|
928
1677
|
blocks: deepFreeze(blocks),
|
|
929
1678
|
fields,
|
|
@@ -932,4 +1681,13 @@ export function validateEntryAggregate(input, model, registry, mode) {
|
|
|
932
1681
|
title: input.title,
|
|
933
1682
|
});
|
|
934
1683
|
}
|
|
1684
|
+
export { parseSchemaPath, encodeSchemaPath, schemaFieldAt } from "./schema-path.js";
|
|
1685
|
+
/** Raw UTF-16 units: the existing text/textarea length contract, without trimming. */
|
|
1686
|
+
export function textLength(value) {
|
|
1687
|
+
return value.length;
|
|
1688
|
+
}
|
|
1689
|
+
/** Trimmed Unicode code points: the existing SEO title/description contract. */
|
|
1690
|
+
export function seoTextLength(value) {
|
|
1691
|
+
return [...value.trim()].length;
|
|
1692
|
+
}
|
|
935
1693
|
//# sourceMappingURL=index.js.map
|