@storyblok/schema 0.1.0-alpha.2 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/generated/types/block.d.cts +6 -0
- package/dist/generated/types/block.d.mts +6 -0
- package/dist/generated/types/field.d.cts +22 -3
- package/dist/generated/types/field.d.mts +22 -3
- package/dist/helpers/define-block.cjs +6 -1
- package/dist/helpers/define-block.cjs.map +1 -1
- package/dist/helpers/define-block.d.cts +14 -4
- package/dist/helpers/define-block.d.mts +14 -4
- package/dist/helpers/define-block.mjs +6 -1
- package/dist/helpers/define-block.mjs.map +1 -1
- package/dist/helpers/define-field.cjs +8 -1
- package/dist/helpers/define-field.cjs.map +1 -1
- package/dist/helpers/define-field.d.cts +12 -3
- package/dist/helpers/define-field.d.mts +12 -3
- package/dist/helpers/define-field.mjs +8 -1
- package/dist/helpers/define-field.mjs.map +1 -1
- package/dist/helpers/define-folder.cjs +19 -0
- package/dist/helpers/define-folder.cjs.map +1 -0
- package/dist/helpers/define-folder.d.cts +39 -0
- package/dist/helpers/define-folder.d.mts +39 -0
- package/dist/helpers/define-folder.mjs +18 -0
- package/dist/helpers/define-folder.mjs.map +1 -0
- package/dist/helpers/define-schema.cjs +1 -0
- package/dist/helpers/define-schema.cjs.map +1 -1
- package/dist/helpers/define-schema.d.cts +3 -0
- package/dist/helpers/define-schema.d.mts +3 -0
- package/dist/helpers/define-schema.mjs +1 -0
- package/dist/helpers/define-schema.mjs.map +1 -1
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +2 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +2 -1
- package/dist/utils/slugify-folder-path.cjs +21 -0
- package/dist/utils/slugify-folder-path.cjs.map +1 -0
- package/dist/utils/slugify-folder-path.mjs +20 -0
- package/dist/utils/slugify-folder-path.mjs.map +1 -0
- package/dist/validators/shapes.cjs.map +1 -1
- package/dist/validators/shapes.d.cts +6 -2
- package/dist/validators/shapes.d.mts +6 -2
- package/dist/validators/shapes.mjs.map +1 -1
- package/dist/validators/validate-story.cjs +60 -24
- package/dist/validators/validate-story.cjs.map +1 -1
- package/dist/validators/validate-story.mjs +60 -24
- package/dist/validators/validate-story.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -2,6 +2,7 @@ import { isRecord } from "../utils/is-record.mjs";
|
|
|
2
2
|
import { toValues } from "./shapes.mjs";
|
|
3
3
|
import { zAssetFieldValue, zMultilinkFieldValue, zRichtextFieldValue, zTableFieldValue } from "../generated/overlay/zod.gen.mjs";
|
|
4
4
|
import "./internal-schemas.mjs";
|
|
5
|
+
import { slugifyFolderPath } from "../utils/slugify-folder-path.mjs";
|
|
5
6
|
import { z } from "zod";
|
|
6
7
|
|
|
7
8
|
//#region src/validators/validate-story.ts
|
|
@@ -66,7 +67,7 @@ function validateFieldValue(field, value, blocksByName, fieldPluginsByType, path
|
|
|
66
67
|
break;
|
|
67
68
|
case "richtext":
|
|
68
69
|
checkValue(zRichtextFieldValue, value, path, entity, issues);
|
|
69
|
-
validateRichtextBloks(value, blocksByName, fieldPluginsByType, path, issues);
|
|
70
|
+
validateRichtextBloks(value, field, blocksByName, fieldPluginsByType, path, entity, issues);
|
|
70
71
|
break;
|
|
71
72
|
case "custom": {
|
|
72
73
|
checkValue(zPluginEnvelope, value, path, entity, issues);
|
|
@@ -84,17 +85,7 @@ function validateFieldValue(field, value, blocksByName, fieldPluginsByType, path
|
|
|
84
85
|
}
|
|
85
86
|
checkCount(value.length, field.minimum, field.maximum, "block(s)", path, entity, issues);
|
|
86
87
|
value.forEach((item, index) => {
|
|
87
|
-
|
|
88
|
-
severity: "error",
|
|
89
|
-
code: "disallowed_component",
|
|
90
|
-
path: [
|
|
91
|
-
...path,
|
|
92
|
-
index,
|
|
93
|
-
"component"
|
|
94
|
-
],
|
|
95
|
-
entity,
|
|
96
|
-
message: `Component "${item.component}" is not allowed in field "${field.name}"; allowed: ${field.allow.join(", ")}.`
|
|
97
|
-
});
|
|
88
|
+
checkComponentAllowed(field, item, [...path, index], blocksByName, entity, issues);
|
|
98
89
|
validateBlokContent(item, blocksByName, fieldPluginsByType, [...path, index], issues);
|
|
99
90
|
});
|
|
100
91
|
break;
|
|
@@ -141,6 +132,42 @@ function validateFieldValue(field, value, blocksByName, fieldPluginsByType, path
|
|
|
141
132
|
break;
|
|
142
133
|
}
|
|
143
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* Enforces a field's `allow` list for one embedded blok. Shared by the `bloks`
|
|
137
|
+
* case and the richtext walk so both apply the same rule: `mapFieldToWire`
|
|
138
|
+
* pushes folder/name `allow` as an editor/API restriction on *both* field types,
|
|
139
|
+
* so validation must reject the same components the editor and API would.
|
|
140
|
+
*
|
|
141
|
+
* `itemPath` is the path to the blok item (its index); the reported issue points
|
|
142
|
+
* at that item's `component` key. A component is allowed when it is named
|
|
143
|
+
* directly in `allow` or its block sits in (or under) an allowed folder — both
|
|
144
|
+
* sides canonicalized to slug space so a folder referenced two ways (a
|
|
145
|
+
* `defineFolder` ref vs. a string shorthand with different casing/separators)
|
|
146
|
+
* matches the way the CLI/editor group it.
|
|
147
|
+
*/
|
|
148
|
+
function checkComponentAllowed(field, item, itemPath, blocksByName, entity, issues) {
|
|
149
|
+
const allowEntries = field.allow ?? [];
|
|
150
|
+
if (allowEntries.length === 0 || !isRecord(item) || typeof item.component !== "string") return;
|
|
151
|
+
const blockNamesAllowed = allowEntries.filter((entry) => typeof entry === "string");
|
|
152
|
+
const folderPathsAllowed = allowEntries.filter((entry) => typeof entry === "object" && entry !== null && typeof entry.folder === "string");
|
|
153
|
+
const itemBlockFolder = blocksByName.get(item.component)?.folder;
|
|
154
|
+
const allowedByName = blockNamesAllowed.includes(item.component);
|
|
155
|
+
const itemFolderSlug = typeof itemBlockFolder === "string" ? slugifyFolderPath(itemBlockFolder) : void 0;
|
|
156
|
+
const allowedByFolder = itemFolderSlug !== void 0 && folderPathsAllowed.some(({ folder }) => {
|
|
157
|
+
const allowedSlug = slugifyFolderPath(folder);
|
|
158
|
+
return itemFolderSlug === allowedSlug || itemFolderSlug.startsWith(`${allowedSlug}/`);
|
|
159
|
+
});
|
|
160
|
+
if (!allowedByName && !allowedByFolder) {
|
|
161
|
+
const allowedList = allowEntries.map((entry) => typeof entry === "string" ? entry : `folder:${entry.folder}`).join(", ");
|
|
162
|
+
issues.push({
|
|
163
|
+
severity: "error",
|
|
164
|
+
code: "disallowed_component",
|
|
165
|
+
path: [...itemPath, "component"],
|
|
166
|
+
entity,
|
|
167
|
+
message: `Component "${item.component}" is not allowed in field "${field.name}"; allowed: ${allowedList}.`
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
144
171
|
/** Reports a constraint (bound/length/count) violation as an error issue. */
|
|
145
172
|
function pushConstraint(message, path, entity, issues) {
|
|
146
173
|
issues.push({
|
|
@@ -190,24 +217,33 @@ function pushTypeIssue(value, expected, path, entity, issues) {
|
|
|
190
217
|
message: `Expected ${expected}, received ${value === null ? "null" : typeof value}.`
|
|
191
218
|
});
|
|
192
219
|
}
|
|
193
|
-
/**
|
|
194
|
-
|
|
220
|
+
/**
|
|
221
|
+
* Walks richtext `content` nodes and validates embedded bloks (`type: 'blok'`).
|
|
222
|
+
* `field` is the owning richtext field: each embedded blok is checked against its
|
|
223
|
+
* `allow` list ({@link checkComponentAllowed}), matching the group/name
|
|
224
|
+
* restriction `mapFieldToWire` pushes for richtext fields.
|
|
225
|
+
*/
|
|
226
|
+
function validateRichtextBloks(value, field, blocksByName, fieldPluginsByType, path, entity, issues) {
|
|
195
227
|
if (!isRecord(value) || !Array.isArray(value.content)) return;
|
|
196
228
|
value.content.forEach((node, index) => {
|
|
197
229
|
if (!isRecord(node)) return;
|
|
198
|
-
if (node.type === "blok" && isRecord(node.attrs) && Array.isArray(node.attrs.body)) node.attrs.body.forEach((blok, blokIndex) =>
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
230
|
+
if (node.type === "blok" && isRecord(node.attrs) && Array.isArray(node.attrs.body)) node.attrs.body.forEach((blok, blokIndex) => {
|
|
231
|
+
const blokPath = [
|
|
232
|
+
...path,
|
|
233
|
+
"content",
|
|
234
|
+
index,
|
|
235
|
+
"attrs",
|
|
236
|
+
"body",
|
|
237
|
+
blokIndex
|
|
238
|
+
];
|
|
239
|
+
checkComponentAllowed(field, blok, blokPath, blocksByName, entity, issues);
|
|
240
|
+
validateBlokContent(blok, blocksByName, fieldPluginsByType, blokPath, issues);
|
|
241
|
+
});
|
|
242
|
+
else if (Array.isArray(node.content)) validateRichtextBloks(node, field, blocksByName, fieldPluginsByType, [
|
|
207
243
|
...path,
|
|
208
244
|
"content",
|
|
209
245
|
index
|
|
210
|
-
], issues);
|
|
246
|
+
], entity, issues);
|
|
211
247
|
});
|
|
212
248
|
}
|
|
213
249
|
/** Validates a single blok content object against its component definition. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-story.mjs","names":[],"sources":["../../src/validators/validate-story.ts"],"sourcesContent":["import { z } from 'zod';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { SchemaBlockLike, SchemaFieldLike, SchemaLike } from './shapes';\nimport type { ValidationIssue, ValidationResult } from './types';\nimport {\n zAssetFieldValue,\n zMultilinkFieldValue,\n zRichtextFieldValue,\n zTableFieldValue,\n} from './internal-schemas';\nimport { isRecord, toValues } from './shapes';\n\n/** Field-content keys that are not user-defined fields. */\nconst RESERVED_KEYS = new Set(['_uid', 'component', '_editable']);\n\n/**\n * Relaxed plugin envelope used by the `custom` case. Mirrors the generated\n * `zPluginFieldValue` but relaxes `_uid` from a UUID to a plain string, matching\n * the CMS, which persists arbitrary `_uid` strings. Kept local so a codegen\n * regenerate cannot revert it.\n */\nconst zPluginEnvelope = z.object({ plugin: z.string(), _uid: z.optional(z.string()) });\n\n/** Maps a Standard Schema validator to a {@link ValidationIssue} reporter at `path`. */\nfunction checkValue(\n schema: StandardSchemaV1,\n value: unknown,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n const result = schema['~standard'].validate(value);\n // `validateStory` is synchronous. The internal Zod schemas never return a\n // thenable, but a registered field plugin may ship an async validator — which\n // cannot be awaited here. Surface it as an error instead of silently passing,\n // which would report a false `ok: true`.\n if (result instanceof Promise) {\n issues.push({\n severity: 'error',\n code: 'async_validator_unsupported',\n path,\n entity,\n message: 'Field plugin validator is asynchronous; validateStory runs synchronously and cannot await it.',\n });\n return;\n }\n if (result.issues) {\n for (const issue of result.issues) {\n const issuePath = (issue.path ?? []).map(segment =>\n (typeof segment === 'object' && segment !== null ? String(segment.key) : (segment as string | number)),\n );\n issues.push({\n severity: 'error',\n code: 'invalid_value',\n path: [...path, ...issuePath],\n entity,\n message: issue.message,\n });\n }\n }\n}\n\nfunction validateFieldValue(\n field: SchemaFieldLike,\n value: unknown,\n blocksByName: Map<string, SchemaBlockLike>,\n fieldPluginsByType: Map<string, StandardSchemaV1>,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n switch (field.type) {\n case 'asset':\n checkValue(zAssetFieldValue, value, path, entity, issues);\n break;\n case 'multiasset':\n if (!Array.isArray(value)) {\n pushTypeIssue(value, 'array', path, entity, issues);\n break;\n }\n value.forEach((item, index) => checkValue(zAssetFieldValue, item, [...path, index], entity, issues));\n checkCount(value.length, field.minimum_entries, field.maximum_entries, 'asset(s)', path, entity, issues);\n break;\n case 'multilink':\n checkValue(zMultilinkFieldValue, value, path, entity, issues);\n break;\n case 'table':\n checkValue(zTableFieldValue, value, path, entity, issues);\n break;\n case 'richtext':\n checkValue(zRichtextFieldValue, value, path, entity, issues);\n validateRichtextBloks(value, blocksByName, fieldPluginsByType, path, issues);\n break;\n case 'custom': {\n checkValue(zPluginEnvelope, value, path, entity, issues);\n const validator = field.field_type ? fieldPluginsByType.get(field.field_type) : undefined;\n if (validator && isRecord(value)) {\n // Envelope keys sit alongside the plugin's own keys; strip them so the\n // plugin validator sees only its value. Sibling keys keep issue paths\n // accurate (an issue at ['color'] maps to [...path, 'color']).\n const { plugin: _plugin, _uid, ...pluginValue } = value;\n checkValue(validator, pluginValue, path, entity, issues);\n }\n break;\n }\n case 'bloks':\n if (!Array.isArray(value)) {\n pushTypeIssue(value, 'array', path, entity, issues);\n break;\n }\n checkCount(value.length, field.minimum, field.maximum, 'block(s)', path, entity, issues);\n value.forEach((item, index) => {\n if (\n field.allow && field.allow.length > 0\n && isRecord(item) && typeof item.component === 'string'\n && !field.allow.includes(item.component)\n ) {\n issues.push({\n severity: 'error',\n code: 'disallowed_component',\n path: [...path, index, 'component'],\n entity,\n message: `Component \"${item.component}\" is not allowed in field \"${field.name}\"; allowed: ${field.allow.join(', ')}.`,\n });\n }\n validateBlokContent(item, blocksByName, fieldPluginsByType, [...path, index], issues);\n });\n break;\n case 'text':\n case 'textarea':\n case 'markdown':\n if (typeof value !== 'string') {\n pushTypeIssue(value, 'string', path, entity, issues);\n break;\n }\n checkStringLength(field, value, path, entity, issues);\n break;\n case 'option':\n case 'datetime':\n if (typeof value !== 'string') {\n pushTypeIssue(value, 'string', path, entity, issues);\n }\n break;\n case 'number':\n if (typeof value !== 'number') {\n pushTypeIssue(value, 'number', path, entity, issues);\n break;\n }\n if (field.min_value != null && value < field.min_value) {\n pushConstraint(`Value ${value} is below the minimum of ${field.min_value}.`, path, entity, issues);\n }\n if (field.max_value != null && value > field.max_value) {\n pushConstraint(`Value ${value} exceeds the maximum of ${field.max_value}.`, path, entity, issues);\n }\n if (field.decimals != null && decimalPlaces(value) > field.decimals) {\n pushConstraint(`Value ${value} has more than ${field.decimals} decimal place(s).`, path, entity, issues);\n }\n if (field.steps != null && field.steps > 0 && !isMultipleOf(value, field.steps, field.min_value ?? 0)) {\n const base = field.min_value ?? 0;\n pushConstraint(\n `Value ${value} is not a multiple of the step ${field.steps}${base ? ` (offset from ${base})` : ''}.`,\n path,\n entity,\n issues,\n );\n }\n break;\n case 'boolean':\n if (typeof value !== 'boolean') {\n pushTypeIssue(value, 'boolean', path, entity, issues);\n }\n break;\n case 'options':\n if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {\n pushTypeIssue(value, 'string[]', path, entity, issues);\n break;\n }\n checkCount(value.length, toCount(field.min_options), toCount(field.max_options), 'option(s)', path, entity, issues);\n break;\n case 'section':\n case 'tab':\n // Layout-only field types carry no content value.\n break;\n default:\n // Exhaustiveness guard: when a new `FieldType` is added, this fails to\n // compile until the field type is handled (or explicitly skipped) above.\n field.type satisfies never;\n break;\n }\n}\n\n/** Reports a constraint (bound/length/count) violation as an error issue. */\nfunction pushConstraint(\n message: string,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n issues.push({ severity: 'error', code: 'constraint_violation', path, entity, message });\n}\n\n/** Checks an array length against optional inclusive `min`/`max` bounds. */\nfunction checkCount(\n length: number,\n min: number | undefined,\n max: number | undefined,\n noun: string,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n if (min != null && length < min) {\n pushConstraint(`Expected at least ${min} ${noun}, received ${length}.`, path, entity, issues);\n }\n if (max != null && length > max) {\n pushConstraint(`Expected at most ${max} ${noun}, received ${length}.`, path, entity, issues);\n }\n}\n\n/** Checks a string against optional `max_length`/`maxlength` and `minlength` bounds. */\nfunction checkStringLength(\n field: SchemaFieldLike,\n value: string,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n const max = field.max_length ?? field.maxlength;\n if (max != null && value.length > max) {\n pushConstraint(`Text length ${value.length} exceeds the maximum of ${max}.`, path, entity, issues);\n }\n if (field.minlength != null && value.length < field.minlength) {\n pushConstraint(`Text length ${value.length} is below the minimum of ${field.minlength}.`, path, entity, issues);\n }\n}\n\n/** Counts a number's fractional digits, handling exponential notation (e.g. `1e-7` → 7). */\nfunction decimalPlaces(value: number): number {\n if (!Number.isFinite(value)) {\n return 0;\n }\n const text = String(value).toLowerCase();\n const [mantissa, exponent] = text.split('e');\n const fractionDigits = mantissa.includes('.') ? mantissa.split('.')[1].length : 0;\n // A negative exponent (e.g. `1e-7`) adds that many fractional digits.\n return exponent ? Math.max(0, fractionDigits - Number(exponent)) : fractionDigits;\n}\n\n/** Whether `value` lands on a `step` increment offset from `base`, with float tolerance. */\nfunction isMultipleOf(value: number, step: number, base: number): boolean {\n const ratio = (value - base) / step;\n const tolerance = 1e-9 * Math.max(1, Math.abs(ratio));\n return Math.abs(ratio - Math.round(ratio)) <= tolerance;\n}\n\n/** Parses a numeric constraint stored as a string (e.g. `min_options`). Empty/non-numeric → undefined. */\nfunction toCount(value: string | undefined): number | undefined {\n if (value == null || value === '') {\n return undefined;\n }\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction pushTypeIssue(\n value: unknown,\n expected: string,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n issues.push({\n severity: 'error',\n code: 'invalid_value',\n path,\n entity,\n message: `Expected ${expected}, received ${value === null ? 'null' : typeof value}.`,\n });\n}\n\n/** Walks richtext `content` nodes and validates embedded bloks (`type: 'blok'`). */\nfunction validateRichtextBloks(\n value: unknown,\n blocksByName: Map<string, SchemaBlockLike>,\n fieldPluginsByType: Map<string, StandardSchemaV1>,\n path: (string | number)[],\n issues: ValidationIssue[],\n): void {\n if (!isRecord(value) || !Array.isArray(value.content)) {\n return;\n }\n value.content.forEach((node, index) => {\n if (!isRecord(node)) {\n return;\n }\n if (node.type === 'blok' && isRecord(node.attrs) && Array.isArray(node.attrs.body)) {\n node.attrs.body.forEach((blok, blokIndex) =>\n validateBlokContent(blok, blocksByName, fieldPluginsByType, [...path, 'content', index, 'attrs', 'body', blokIndex], issues),\n );\n }\n else if (Array.isArray(node.content)) {\n // Recurse into nested marks/nodes that may themselves embed bloks.\n validateRichtextBloks(node, blocksByName, fieldPluginsByType, [...path, 'content', index], issues);\n }\n });\n}\n\n/** Validates a single blok content object against its component definition. */\nfunction validateBlokContent(\n content: unknown,\n blocksByName: Map<string, SchemaBlockLike>,\n fieldPluginsByType: Map<string, StandardSchemaV1>,\n path: (string | number)[],\n issues: ValidationIssue[],\n): void {\n if (!isRecord(content)) {\n issues.push({\n severity: 'error',\n code: 'invalid_content',\n path,\n entity: 'story',\n message: 'Expected a block content object.',\n });\n return;\n }\n\n const component = content.component;\n const block = typeof component === 'string' ? blocksByName.get(component) : undefined;\n if (!block) {\n issues.push({\n severity: 'error',\n code: 'unknown_component',\n path: [...path, 'component'],\n entity: 'story',\n message: `Unknown component \"${String(component)}\".`,\n });\n return;\n }\n\n const entity = `block:${block.name}`;\n const fields = block.fields ?? [];\n const fieldsByName = new Map(fields.map(field => [field.name, field]));\n\n for (const key of Object.keys(content)) {\n if (!RESERVED_KEYS.has(key) && !fieldsByName.has(key)) {\n issues.push({\n severity: 'warning',\n code: 'unknown_field',\n path: [...path, key],\n entity,\n message: `Unknown field \"${key}\" on component \"${block.name}\".`,\n });\n }\n }\n\n for (const field of fields) {\n const value = content[field.name];\n if (value === undefined || value === null) {\n if (field.required) {\n issues.push({\n severity: 'error',\n code: 'missing_required_field',\n path: [...path, field.name],\n entity,\n message: `Missing required field \"${field.name}\" on component \"${block.name}\".`,\n });\n }\n continue;\n }\n validateFieldValue(field, value, blocksByName, fieldPluginsByType, [...path, field.name], entity, issues);\n }\n}\n\n/**\n * Validates a story's content against a schema without throwing. Reports unknown\n * components (error), unknown fields (warning), missing required fields (error),\n * and invalid field-value shapes (error), recursing into nested `bloks` and\n * richtext-embedded bloks.\n *\n * @example\n * const result = validateStory(story, { blocks: { page, hero } });\n */\nexport function validateStory(story: unknown, schema: SchemaLike): ValidationResult {\n const issues: ValidationIssue[] = [];\n const blocksByName = new Map(toValues(schema.blocks).map(block => [block.name, block]));\n const fieldPluginsByType = new Map(\n toValues(schema.fieldPlugins).map(plugin => [plugin.fieldType, plugin.value]),\n );\n const content = isRecord(story) ? story.content : undefined;\n validateBlokContent(content, blocksByName, fieldPluginsByType, ['content'], issues);\n return { ok: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AI,IAAI,OAAO,KAAI,UAAS,CAAC,MAAM,MAAM,MAAM,CAAC,CAAC;AAEtE,MAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,CACpC,KAAI,CAAC,cAAc,IAAI,IAAI,IAAI,CAAC,aAAa,IAAI,IAAI,CACnD,QAAO,KAAK;EACV,UAAU;EACV,MAAM;EACN,MAAM,CAAC,GAAG,MAAM,IAAI;EACpB;EACA,SAAS,kBAAkB,IAAI,kBAAkB,MAAM,KAAK;EAC7D,CAAC;AAIN,MAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,QAAQ,QAAQ,MAAM;AAC5B,MAAI,UAAU,UAAa,UAAU,MAAM;AACzC,OAAI,MAAM,SACR,QAAO,KAAK;IACV,UAAU;IACV,MAAM;IACN,MAAM,CAAC,GAAG,MAAM,MAAM,KAAK;IAC3B;IACA,SAAS,2BAA2B,MAAM,KAAK,kBAAkB,MAAM,KAAK;IAC7E,CAAC;AAEJ;;AAEF,qBAAmB,OAAO,OAAO,cAAc,oBAAoB,CAAC,GAAG,MAAM,MAAM,KAAK,EAAE,QAAQ,OAAO;;;;;;;;;;;;AAa7G,SAAgB,cAAc,OAAgB,QAAsC;CAClF,MAAM,SAA4B,EAAE;CACpC,MAAM,eAAe,IAAI,IAAI,SAAS,OAAO,OAAO,CAAC,KAAI,UAAS,CAAC,MAAM,MAAM,MAAM,CAAC,CAAC;CACvF,MAAM,qBAAqB,IAAI,IAC7B,SAAS,OAAO,aAAa,CAAC,KAAI,WAAU,CAAC,OAAO,WAAW,OAAO,MAAM,CAAC,CAC9E;AAED,qBADgB,SAAS,MAAM,GAAG,MAAM,UAAU,QACrB,cAAc,oBAAoB,CAAC,UAAU,EAAE,OAAO;AACnF,QAAO;EAAE,IAAI,OAAO,OAAM,UAAS,MAAM,aAAa,QAAQ;EAAE;EAAQ"}
|
|
1
|
+
{"version":3,"file":"validate-story.mjs","names":[],"sources":["../../src/validators/validate-story.ts"],"sourcesContent":["import { z } from 'zod';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { SchemaBlockLike, SchemaFieldLike, SchemaLike } from './shapes';\nimport type { ValidationIssue, ValidationResult } from './types';\nimport {\n zAssetFieldValue,\n zMultilinkFieldValue,\n zRichtextFieldValue,\n zTableFieldValue,\n} from './internal-schemas';\nimport { isRecord, toValues } from './shapes';\nimport { slugifyFolderPath } from '../utils/slugify-folder-path';\n\n/** Field-content keys that are not user-defined fields. */\nconst RESERVED_KEYS = new Set(['_uid', 'component', '_editable']);\n\n/**\n * Relaxed plugin envelope used by the `custom` case. Mirrors the generated\n * `zPluginFieldValue` but relaxes `_uid` from a UUID to a plain string, matching\n * the CMS, which persists arbitrary `_uid` strings. Kept local so a codegen\n * regenerate cannot revert it.\n */\nconst zPluginEnvelope = z.object({ plugin: z.string(), _uid: z.optional(z.string()) });\n\n/** Maps a Standard Schema validator to a {@link ValidationIssue} reporter at `path`. */\nfunction checkValue(\n schema: StandardSchemaV1,\n value: unknown,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n const result = schema['~standard'].validate(value);\n // `validateStory` is synchronous. The internal Zod schemas never return a\n // thenable, but a registered field plugin may ship an async validator — which\n // cannot be awaited here. Surface it as an error instead of silently passing,\n // which would report a false `ok: true`.\n if (result instanceof Promise) {\n issues.push({\n severity: 'error',\n code: 'async_validator_unsupported',\n path,\n entity,\n message: 'Field plugin validator is asynchronous; validateStory runs synchronously and cannot await it.',\n });\n return;\n }\n if (result.issues) {\n for (const issue of result.issues) {\n const issuePath = (issue.path ?? []).map(segment =>\n (typeof segment === 'object' && segment !== null ? String(segment.key) : (segment as string | number)),\n );\n issues.push({\n severity: 'error',\n code: 'invalid_value',\n path: [...path, ...issuePath],\n entity,\n message: issue.message,\n });\n }\n }\n}\n\nfunction validateFieldValue(\n field: SchemaFieldLike,\n value: unknown,\n blocksByName: Map<string, SchemaBlockLike>,\n fieldPluginsByType: Map<string, StandardSchemaV1>,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n switch (field.type) {\n case 'asset':\n checkValue(zAssetFieldValue, value, path, entity, issues);\n break;\n case 'multiasset':\n if (!Array.isArray(value)) {\n pushTypeIssue(value, 'array', path, entity, issues);\n break;\n }\n value.forEach((item, index) => checkValue(zAssetFieldValue, item, [...path, index], entity, issues));\n checkCount(value.length, field.minimum_entries, field.maximum_entries, 'asset(s)', path, entity, issues);\n break;\n case 'multilink':\n checkValue(zMultilinkFieldValue, value, path, entity, issues);\n break;\n case 'table':\n checkValue(zTableFieldValue, value, path, entity, issues);\n break;\n case 'richtext':\n checkValue(zRichtextFieldValue, value, path, entity, issues);\n validateRichtextBloks(value, field, blocksByName, fieldPluginsByType, path, entity, issues);\n break;\n case 'custom': {\n checkValue(zPluginEnvelope, value, path, entity, issues);\n const validator = field.field_type ? fieldPluginsByType.get(field.field_type) : undefined;\n if (validator && isRecord(value)) {\n // Envelope keys sit alongside the plugin's own keys; strip them so the\n // plugin validator sees only its value. Sibling keys keep issue paths\n // accurate (an issue at ['color'] maps to [...path, 'color']).\n const { plugin: _plugin, _uid, ...pluginValue } = value;\n checkValue(validator, pluginValue, path, entity, issues);\n }\n break;\n }\n case 'bloks':\n if (!Array.isArray(value)) {\n pushTypeIssue(value, 'array', path, entity, issues);\n break;\n }\n checkCount(value.length, field.minimum, field.maximum, 'block(s)', path, entity, issues);\n value.forEach((item, index) => {\n checkComponentAllowed(field, item, [...path, index], blocksByName, entity, issues);\n validateBlokContent(item, blocksByName, fieldPluginsByType, [...path, index], issues);\n });\n break;\n case 'text':\n case 'textarea':\n case 'markdown':\n if (typeof value !== 'string') {\n pushTypeIssue(value, 'string', path, entity, issues);\n break;\n }\n checkStringLength(field, value, path, entity, issues);\n break;\n case 'option':\n case 'datetime':\n if (typeof value !== 'string') {\n pushTypeIssue(value, 'string', path, entity, issues);\n }\n break;\n case 'number':\n if (typeof value !== 'number') {\n pushTypeIssue(value, 'number', path, entity, issues);\n break;\n }\n if (field.min_value != null && value < field.min_value) {\n pushConstraint(`Value ${value} is below the minimum of ${field.min_value}.`, path, entity, issues);\n }\n if (field.max_value != null && value > field.max_value) {\n pushConstraint(`Value ${value} exceeds the maximum of ${field.max_value}.`, path, entity, issues);\n }\n if (field.decimals != null && decimalPlaces(value) > field.decimals) {\n pushConstraint(`Value ${value} has more than ${field.decimals} decimal place(s).`, path, entity, issues);\n }\n if (field.steps != null && field.steps > 0 && !isMultipleOf(value, field.steps, field.min_value ?? 0)) {\n const base = field.min_value ?? 0;\n pushConstraint(\n `Value ${value} is not a multiple of the step ${field.steps}${base ? ` (offset from ${base})` : ''}.`,\n path,\n entity,\n issues,\n );\n }\n break;\n case 'boolean':\n if (typeof value !== 'boolean') {\n pushTypeIssue(value, 'boolean', path, entity, issues);\n }\n break;\n case 'options':\n if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {\n pushTypeIssue(value, 'string[]', path, entity, issues);\n break;\n }\n checkCount(value.length, toCount(field.min_options), toCount(field.max_options), 'option(s)', path, entity, issues);\n break;\n case 'section':\n case 'tab':\n // Layout-only field types carry no content value.\n break;\n default:\n // Exhaustiveness guard: when a new `FieldType` is added, this fails to\n // compile until the field type is handled (or explicitly skipped) above.\n field.type satisfies never;\n break;\n }\n}\n\n/**\n * Enforces a field's `allow` list for one embedded blok. Shared by the `bloks`\n * case and the richtext walk so both apply the same rule: `mapFieldToWire`\n * pushes folder/name `allow` as an editor/API restriction on *both* field types,\n * so validation must reject the same components the editor and API would.\n *\n * `itemPath` is the path to the blok item (its index); the reported issue points\n * at that item's `component` key. A component is allowed when it is named\n * directly in `allow` or its block sits in (or under) an allowed folder — both\n * sides canonicalized to slug space so a folder referenced two ways (a\n * `defineFolder` ref vs. a string shorthand with different casing/separators)\n * matches the way the CLI/editor group it.\n */\nfunction checkComponentAllowed(\n field: SchemaFieldLike,\n item: unknown,\n itemPath: (string | number)[],\n blocksByName: Map<string, SchemaBlockLike>,\n entity: string,\n issues: ValidationIssue[],\n): void {\n const allowEntries = field.allow ?? [];\n if (allowEntries.length === 0 || !isRecord(item) || typeof item.component !== 'string') {\n return;\n }\n const blockNamesAllowed = allowEntries.filter((entry): entry is string => typeof entry === 'string');\n const folderPathsAllowed = allowEntries.filter(\n (entry): entry is { folder: string } =>\n typeof entry === 'object' && entry !== null && typeof entry.folder === 'string',\n );\n const itemBlock = blocksByName.get(item.component);\n const itemBlockFolder = itemBlock?.folder;\n const allowedByName = blockNamesAllowed.includes(item.component);\n const itemFolderSlug = typeof itemBlockFolder === 'string' ? slugifyFolderPath(itemBlockFolder) : undefined;\n const allowedByFolder = itemFolderSlug !== undefined\n && folderPathsAllowed.some(({ folder }) => {\n const allowedSlug = slugifyFolderPath(folder);\n return itemFolderSlug === allowedSlug || itemFolderSlug.startsWith(`${allowedSlug}/`);\n });\n if (!allowedByName && !allowedByFolder) {\n const allowedList = allowEntries\n .map(entry => (typeof entry === 'string' ? entry : `folder:${entry.folder}`))\n .join(', ');\n issues.push({\n severity: 'error',\n code: 'disallowed_component',\n path: [...itemPath, 'component'],\n entity,\n message: `Component \"${item.component}\" is not allowed in field \"${field.name}\"; allowed: ${allowedList}.`,\n });\n }\n}\n\n/** Reports a constraint (bound/length/count) violation as an error issue. */\nfunction pushConstraint(\n message: string,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n issues.push({ severity: 'error', code: 'constraint_violation', path, entity, message });\n}\n\n/** Checks an array length against optional inclusive `min`/`max` bounds. */\nfunction checkCount(\n length: number,\n min: number | undefined,\n max: number | undefined,\n noun: string,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n if (min != null && length < min) {\n pushConstraint(`Expected at least ${min} ${noun}, received ${length}.`, path, entity, issues);\n }\n if (max != null && length > max) {\n pushConstraint(`Expected at most ${max} ${noun}, received ${length}.`, path, entity, issues);\n }\n}\n\n/** Checks a string against optional `max_length`/`maxlength` and `minlength` bounds. */\nfunction checkStringLength(\n field: SchemaFieldLike,\n value: string,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n const max = field.max_length ?? field.maxlength;\n if (max != null && value.length > max) {\n pushConstraint(`Text length ${value.length} exceeds the maximum of ${max}.`, path, entity, issues);\n }\n if (field.minlength != null && value.length < field.minlength) {\n pushConstraint(`Text length ${value.length} is below the minimum of ${field.minlength}.`, path, entity, issues);\n }\n}\n\n/** Counts a number's fractional digits, handling exponential notation (e.g. `1e-7` → 7). */\nfunction decimalPlaces(value: number): number {\n if (!Number.isFinite(value)) {\n return 0;\n }\n const text = String(value).toLowerCase();\n const [mantissa, exponent] = text.split('e');\n const fractionDigits = mantissa.includes('.') ? mantissa.split('.')[1].length : 0;\n // A negative exponent (e.g. `1e-7`) adds that many fractional digits.\n return exponent ? Math.max(0, fractionDigits - Number(exponent)) : fractionDigits;\n}\n\n/** Whether `value` lands on a `step` increment offset from `base`, with float tolerance. */\nfunction isMultipleOf(value: number, step: number, base: number): boolean {\n const ratio = (value - base) / step;\n const tolerance = 1e-9 * Math.max(1, Math.abs(ratio));\n return Math.abs(ratio - Math.round(ratio)) <= tolerance;\n}\n\n/** Parses a numeric constraint stored as a string (e.g. `min_options`). Empty/non-numeric → undefined. */\nfunction toCount(value: string | undefined): number | undefined {\n if (value == null || value === '') {\n return undefined;\n }\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction pushTypeIssue(\n value: unknown,\n expected: string,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n issues.push({\n severity: 'error',\n code: 'invalid_value',\n path,\n entity,\n message: `Expected ${expected}, received ${value === null ? 'null' : typeof value}.`,\n });\n}\n\n/**\n * Walks richtext `content` nodes and validates embedded bloks (`type: 'blok'`).\n * `field` is the owning richtext field: each embedded blok is checked against its\n * `allow` list ({@link checkComponentAllowed}), matching the group/name\n * restriction `mapFieldToWire` pushes for richtext fields.\n */\nfunction validateRichtextBloks(\n value: unknown,\n field: SchemaFieldLike,\n blocksByName: Map<string, SchemaBlockLike>,\n fieldPluginsByType: Map<string, StandardSchemaV1>,\n path: (string | number)[],\n entity: string,\n issues: ValidationIssue[],\n): void {\n if (!isRecord(value) || !Array.isArray(value.content)) {\n return;\n }\n value.content.forEach((node, index) => {\n if (!isRecord(node)) {\n return;\n }\n if (node.type === 'blok' && isRecord(node.attrs) && Array.isArray(node.attrs.body)) {\n node.attrs.body.forEach((blok, blokIndex) => {\n const blokPath = [...path, 'content', index, 'attrs', 'body', blokIndex];\n checkComponentAllowed(field, blok, blokPath, blocksByName, entity, issues);\n validateBlokContent(blok, blocksByName, fieldPluginsByType, blokPath, issues);\n });\n }\n else if (Array.isArray(node.content)) {\n // Recurse into nested marks/nodes that may themselves embed bloks.\n validateRichtextBloks(node, field, blocksByName, fieldPluginsByType, [...path, 'content', index], entity, issues);\n }\n });\n}\n\n/** Validates a single blok content object against its component definition. */\nfunction validateBlokContent(\n content: unknown,\n blocksByName: Map<string, SchemaBlockLike>,\n fieldPluginsByType: Map<string, StandardSchemaV1>,\n path: (string | number)[],\n issues: ValidationIssue[],\n): void {\n if (!isRecord(content)) {\n issues.push({\n severity: 'error',\n code: 'invalid_content',\n path,\n entity: 'story',\n message: 'Expected a block content object.',\n });\n return;\n }\n\n const component = content.component;\n const block = typeof component === 'string' ? blocksByName.get(component) : undefined;\n if (!block) {\n issues.push({\n severity: 'error',\n code: 'unknown_component',\n path: [...path, 'component'],\n entity: 'story',\n message: `Unknown component \"${String(component)}\".`,\n });\n return;\n }\n\n const entity = `block:${block.name}`;\n const fields = block.fields ?? [];\n const fieldsByName = new Map(fields.map(field => [field.name, field]));\n\n for (const key of Object.keys(content)) {\n if (!RESERVED_KEYS.has(key) && !fieldsByName.has(key)) {\n issues.push({\n severity: 'warning',\n code: 'unknown_field',\n path: [...path, key],\n entity,\n message: `Unknown field \"${key}\" on component \"${block.name}\".`,\n });\n }\n }\n\n for (const field of fields) {\n const value = content[field.name];\n if (value === undefined || value === null) {\n if (field.required) {\n issues.push({\n severity: 'error',\n code: 'missing_required_field',\n path: [...path, field.name],\n entity,\n message: `Missing required field \"${field.name}\" on component \"${block.name}\".`,\n });\n }\n continue;\n }\n validateFieldValue(field, value, blocksByName, fieldPluginsByType, [...path, field.name], entity, issues);\n }\n}\n\n/**\n * Validates a story's content against a schema without throwing. Reports unknown\n * components (error), unknown fields (warning), missing required fields (error),\n * and invalid field-value shapes (error), recursing into nested `bloks` and\n * richtext-embedded bloks.\n *\n * @example\n * const result = validateStory(story, { blocks: { page, hero } });\n */\nexport function validateStory(story: unknown, schema: SchemaLike): ValidationResult {\n const issues: ValidationIssue[] = [];\n const blocksByName = new Map(toValues(schema.blocks).map(block => [block.name, block]));\n const fieldPluginsByType = new Map(\n toValues(schema.fieldPlugins).map(plugin => [plugin.fieldType, plugin.value]),\n );\n const content = isRecord(story) ? story.content : undefined;\n validateBlokContent(content, blocksByName, fieldPluginsByType, ['content'], issues);\n return { ok: issues.every(issue => issue.severity !== 'error'), issues };\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,gBAAgB,IAAI,IAAI;CAAC;CAAQ;CAAa;CAAY,CAAC;;;;;;;AAQjE,MAAM,kBAAkB,EAAE,OAAO;CAAE,QAAQ,EAAE,QAAQ;CAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC;CAAE,CAAC;;AAGtF,SAAS,WACP,QACA,OACA,MACA,QACA,QACM;CACN,MAAM,SAAS,OAAO,aAAa,SAAS,MAAM;AAKlD,KAAI,kBAAkB,SAAS;AAC7B,SAAO,KAAK;GACV,UAAU;GACV,MAAM;GACN;GACA;GACA,SAAS;GACV,CAAC;AACF;;AAEF,KAAI,OAAO,OACT,MAAK,MAAM,SAAS,OAAO,QAAQ;EACjC,MAAM,aAAa,MAAM,QAAQ,EAAE,EAAE,KAAI,YACtC,OAAO,YAAY,YAAY,YAAY,OAAO,OAAO,QAAQ,IAAI,GAAI,QAC3E;AACD,SAAO,KAAK;GACV,UAAU;GACV,MAAM;GACN,MAAM,CAAC,GAAG,MAAM,GAAG,UAAU;GAC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M,UAAS,MAAM,aAAa,QAAQ;EAAE;EAAQ"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storyblok/schema",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.1.0
|
|
4
|
+
"version": "0.1.0",
|
|
5
5
|
"description": "Storyblok schema types and helpers",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"homepage": "https://github.com/storyblok/monoblok/tree/main/packages/schema#readme",
|