@cms-93/core 0.0.0-stage → 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 93GRADOS STUDIO
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # @cms-93/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Preview release (0.0.x).** cms-93 is in early development: the API and the content format may change in any release, without notice. Pin the exact version in your `package.json` and read the changelog before updating.
4
+
5
+ The cms-93 protocol: HTML attributes, content format, collections and validation. Shared by every other package. No dependencies; it runs in the browser and in Node, except `@cms-93/core/node`.
6
+
7
+ The protocol itself is described in [`docs/PROTOCOL.md`](../../docs/PROTOCOL.md).
8
+
9
+ ## Marking
10
+
11
+ - `readEditable(element)`: the key, type, maximum and ratio of an element marked with `data-editable`. Throws a `ProtocolError` if the marking is wrong.
12
+ - `isValidKey(key)` and `parseRatio(text)`.
13
+ - The attribute names: `EDITABLE_ATTRIBUTE`, `MAX_ATTRIBUTE`, `RATIO_ATTRIBUTE` and `EDITABLE_SELECTOR`.
14
+
15
+ ## Content
16
+
17
+ - `normalizeContentDocument(document)`: checks a content document and writes every value in its canonical form.
18
+ - `resolveContent(document, locale)`: the content of one locale, with the default locale filling the gaps.
19
+ - `normalizeValue(value)`, `sanitizeText(html)` and `normalizeImage(value)`: one value at a time.
20
+ - `toPlainText(html)` and `textLength(html)`: the text of a value and its length as people see it.
21
+ - `toObjectPosition(focus)`: the CSS `object-position` of a focal point.
22
+ - `normalizeLocale(tag)` and `matchLocale(tag, locales, defaultLocale)`.
23
+
24
+ ## Collections
25
+
26
+ - `defineCollection(definition)`: the definition of a collection, in its file `cms/<collection>.js`. It only gives autocompletion.
27
+ - `normalizeCollections(definitions)`: checks the collections of a website and completes them with their defaults.
28
+ - `normalizeCollectionDocument(document, collections)` and `normalizeEntry(entry, collection, locales)`: check the entries of a collection against its fields.
29
+ - `resolveCollection(document, collection, locale)`: the entries of one locale, with the default locale filling the gaps.
30
+ - `normalizeFieldValue(field, value, locales, path)`: one field value at a time.
31
+ - `sanitizeRichText(html)`: the value of a long text, with paragraphs, headings, lists and links.
32
+ - `parseVideoLink(url)` and `normalizeVideo(value)`: YouTube and Vimeo links.
33
+ - `isValidName(name)`, `isValidId(id)` and `isValidSlug(slug)`, `FIELD_TYPE_NAMES` and `TRANSLATED_TYPES`.
34
+
35
+ In Node only, `@cms-93/core/node` has `loadCollections(folder)`, which reads the `cms/` folder of a website.
36
+
37
+ ## Edit mode
38
+
39
+ - `isEditing()`: whether the website is shown inside the editor. Ask it before starting any animation.
40
+ - `EDITOR_FRAME_ATTRIBUTE` and `EDITING_ATTRIBUTE`.
41
+
42
+ License: MIT (see `LICENSE`).
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "@cms-93/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1",
4
+ "description": "The cms-93 protocol: HTML attributes, content format, collections and validation. Shared by every other package.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./node": "./src/node/index.js"
10
+ },
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "sideEffects": false,
18
+ "scripts": {
19
+ "test": "node --test"
20
+ }
6
21
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Thrown when something breaks the cms-93 protocol: an invalid key, attribute or value.
3
+ */
4
+ export class ProtocolError extends Error {
5
+ /**
6
+ * @param {string} message What is wrong, in a sentence a developer can act on.
7
+ * @param {string} [path] Where it is wrong, such as `content["home.title"].en`.
8
+ */
9
+ constructor(message, path) {
10
+ super(path ? `${path}: ${message}` : message)
11
+ this.name = 'ProtocolError'
12
+ this.path = path
13
+ }
14
+ }
@@ -0,0 +1,17 @@
1
+ /** Marks an editable element. Its value is the content key. */
2
+ export const EDITABLE_ATTRIBUTE = 'data-editable'
3
+
4
+ /** Maximum number of characters of an editable text. */
5
+ export const MAX_ATTRIBUTE = 'data-editable-max'
6
+
7
+ /** Proportion an editable image is cropped to, with the syntax of CSS `aspect-ratio`. */
8
+ export const RATIO_ATTRIBUTE = 'data-editable-ratio'
9
+
10
+ /** Marks the editor's iframe: the website inside it is in edit mode. */
11
+ export const EDITOR_FRAME_ATTRIBUTE = 'data-cms-editor'
12
+
13
+ /** Added to `<html>` in edit mode, so the website's CSS can stop its animations. */
14
+ export const EDITING_ATTRIBUTE = 'data-cms-editing'
15
+
16
+ /** Selects every editable element of a page. */
17
+ export const EDITABLE_SELECTOR = `[${EDITABLE_ATTRIBUTE}]`
@@ -0,0 +1,74 @@
1
+ import { ProtocolError } from '../ProtocolError.js'
2
+ import { isPlainObject } from '../values.js'
3
+ import { isValidName } from './identifiers.js'
4
+ import { normalizeField, readLabel, readFlag } from './fields.js'
5
+
6
+ /** @typedef {import('./types.js').CollectionDefinition} CollectionDefinition */
7
+ /** @typedef {import('./types.js').Collection} Collection */
8
+
9
+ const COLLECTION_OPTIONS = ['label', 'slug', 'fields']
10
+
11
+ /**
12
+ * Defines a collection in its file, `cms/<collection>.js`. It returns the definition as it
13
+ * is: it only gives the editor of the developer autocompletion and type checking.
14
+ * @param {CollectionDefinition} definition
15
+ * @returns {CollectionDefinition}
16
+ */
17
+ export function defineCollection(definition) {
18
+ return definition
19
+ }
20
+
21
+ /**
22
+ * Checks the collections of a website and completes them with their defaults.
23
+ * They are checked together, because a relation needs the collection it points to.
24
+ * @param {unknown} definitions Collection name → definition.
25
+ * @returns {Record<string, Collection>}
26
+ */
27
+ export function normalizeCollections(definitions) {
28
+ if (!isPlainObject(definitions)) throw new ProtocolError('Collections must be an object: collection name → definition.')
29
+ const names = Object.keys(definitions)
30
+ const invalid = names.find((name) => !isValidName(name))
31
+ if (invalid !== undefined) {
32
+ throw new ProtocolError(`"${invalid}" is not a valid collection name. Start with a letter and use letters, digits, - and _, up to 64 characters.`)
33
+ }
34
+ return Object.fromEntries(names.map((name) => [name, normalizeCollection(name, definitions[name], names)]))
35
+ }
36
+
37
+ /**
38
+ * @param {string} name
39
+ * @param {unknown} definition
40
+ * @param {string[]} names
41
+ * @returns {Collection}
42
+ */
43
+ function normalizeCollection(name, definition, names) {
44
+ if (!isPlainObject(definition)) throw new ProtocolError('A collection must be an object with its fields.', name)
45
+ const unknown = Object.keys(definition).find((option) => !COLLECTION_OPTIONS.includes(option))
46
+ if (unknown) throw new ProtocolError(`${unknown} does not apply to collections. Use label, slug and fields.`, name)
47
+ return {
48
+ name,
49
+ label: readLabel(definition.label, name, name),
50
+ slug: readFlag(definition.slug, 'slug', name),
51
+ fields: normalizeFields(definition.fields, `${name}.fields`, names),
52
+ }
53
+ }
54
+
55
+ /**
56
+ * @param {unknown} fields
57
+ * @param {string} path
58
+ * @param {string[]} names
59
+ * @returns {Collection['fields']}
60
+ */
61
+ function normalizeFields(fields, path, names) {
62
+ if (!isPlainObject(fields) || Object.keys(fields).length === 0) {
63
+ throw new ProtocolError('A collection needs fields: an object with at least one field.', path)
64
+ }
65
+ return Object.fromEntries(
66
+ Object.entries(fields).map(([name, field]) => {
67
+ const fieldPath = `${path}.${name}`
68
+ if (!isValidName(name)) {
69
+ throw new ProtocolError(`"${name}" is not a valid field name. Start with a letter and use letters, digits, - and _.`, fieldPath)
70
+ }
71
+ return [name, normalizeField(name, field, fieldPath, names)]
72
+ }),
73
+ )
74
+ }
@@ -0,0 +1,125 @@
1
+ import { CONTENT_VERSION } from '../version.js'
2
+ import { ProtocolError } from '../ProtocolError.js'
3
+ import { normalizeLocale, normalizeLocaleSettings } from '../locale.js'
4
+ import { isPlainObject } from '../values.js'
5
+ import { isValidId, isValidSlug } from './identifiers.js'
6
+ import { normalizeFieldValue, isFilled, TRANSLATED_TYPES } from './values.js'
7
+
8
+ /** @typedef {import('./types.js').Collection} Collection */
9
+ /** @typedef {import('./types.js').CollectionDocument} CollectionDocument */
10
+ /** @typedef {import('./types.js').Entry} Entry */
11
+ /** @typedef {import('./types.js').Locales} Locales */
12
+
13
+ /**
14
+ * Checks an entry against its collection and writes it in its canonical form.
15
+ * Fields the collection doesn't define are dropped: they may come from an older definition.
16
+ * @param {unknown} entry
17
+ * @param {Collection} collection
18
+ * @param {Locales} locales The website's locales, normalized.
19
+ * @param {string} [path] Where the entry is, for error messages.
20
+ * @returns {Entry}
21
+ */
22
+ export function normalizeEntry(entry, collection, locales, path = 'entry') {
23
+ if (!isPlainObject(entry)) throw new ProtocolError('An entry must be an object with an id and its fields.', path)
24
+ if (!isValidId(entry.id)) {
25
+ throw new ProtocolError(`"${entry.id}" is not a valid id. Use letters, digits, - and _, up to 64 characters.`, `${path}.id`)
26
+ }
27
+ const slug = normalizeSlug(entry.slug, collection, locales, `${path}.slug`)
28
+ const fields = normalizeFields(entry.fields ?? {}, collection, locales, `${path}.fields`)
29
+ return slug ? { id: entry.id, slug, fields } : { id: entry.id, fields }
30
+ }
31
+
32
+ /**
33
+ * Checks all the entries of a collection, as the server stores them or as a JSON loads them.
34
+ * Ids are unique, and so are the slugs of each locale.
35
+ * @param {unknown} document
36
+ * @param {Record<string, Collection>} collections The website's collections, normalized.
37
+ * @returns {CollectionDocument}
38
+ */
39
+ export function normalizeCollectionDocument(document, collections) {
40
+ if (!isPlainObject(document)) throw new ProtocolError('A collection document must be an object.')
41
+ if (document.version !== CONTENT_VERSION) {
42
+ throw new ProtocolError(`Unsupported content version ${document.version}. This version of cms-93 reads version ${CONTENT_VERSION}.`)
43
+ }
44
+ const name = document.collection
45
+ if (typeof name !== 'string' || !Object.hasOwn(collections, name)) {
46
+ throw new ProtocolError(`"${name}" is not one of the collections: ${Object.keys(collections).join(', ')}.`, 'collection')
47
+ }
48
+ const { locales, defaultLocale } = normalizeLocaleSettings(document)
49
+ if (!Array.isArray(document.entries)) throw new ProtocolError('Entries must be a list.', 'entries')
50
+ const entries = document.entries.map((entry, index) => normalizeEntry(entry, collections[name], { locales, defaultLocale }, `entries[${index}]`))
51
+ checkUnique(entries.map((entry) => entry.id), 'Two entries have the id')
52
+ for (const locale of locales) checkUnique(entries.flatMap((entry) => entry.slug?.[locale] ?? []), `Two entries have the ${locale} slug`)
53
+ return { version: CONTENT_VERSION, collection: name, defaultLocale, locales, entries }
54
+ }
55
+
56
+ /**
57
+ * @param {unknown} slug
58
+ * @param {Collection} collection
59
+ * @param {Locales} locales
60
+ * @param {string} path
61
+ * @returns {Record<string, string> | undefined}
62
+ */
63
+ function normalizeSlug(slug, collection, locales, path) {
64
+ if (!collection.slug) {
65
+ if (slug !== undefined && slug !== null) {
66
+ throw new ProtocolError(`The entries of ${collection.name} have no page, so they have no slug. Add slug: true to the collection to give them one.`, path)
67
+ }
68
+ return undefined
69
+ }
70
+ if (!isPlainObject(slug)) throw new ProtocolError(`A slug has one address per locale, such as { "${locales.defaultLocale}": "my-entry" }.`, path)
71
+ const slugs = Object.fromEntries(Object.entries(slug).map(([tag, value]) => normalizeLocaleSlug(tag, value, locales, path)))
72
+ if (!Object.hasOwn(slugs, locales.defaultLocale)) throw new ProtocolError(`The slug needs a value in the default locale (${locales.defaultLocale}).`, path)
73
+ return slugs
74
+ }
75
+
76
+ /**
77
+ * @param {string} tag
78
+ * @param {unknown} value
79
+ * @param {Locales} locales
80
+ * @param {string} slugPath
81
+ * @returns {[string, string]}
82
+ */
83
+ function normalizeLocaleSlug(tag, value, locales, slugPath) {
84
+ const path = `${slugPath}.${tag}`
85
+ const locale = normalizeLocale(tag, path)
86
+ if (!locales.locales.includes(locale)) throw new ProtocolError(`"${tag}" is not one of the locales.`, path)
87
+ if (!isValidSlug(value)) throw new ProtocolError(`"${value}" is not a valid slug. Use lowercase letters and digits separated by hyphens, such as aroma-workshop.`, path)
88
+ return [locale, value]
89
+ }
90
+
91
+ /**
92
+ * @param {unknown} values
93
+ * @param {Collection} collection
94
+ * @param {Locales} locales
95
+ * @param {string} path
96
+ * @returns {Entry['fields']}
97
+ */
98
+ function normalizeFields(values, collection, locales, path) {
99
+ if (!isPlainObject(values)) throw new ProtocolError('Fields must be an object: field name → value.', path)
100
+ return Object.fromEntries(
101
+ Object.entries(collection.fields)
102
+ .map(([name, field]) => {
103
+ const fieldPath = `${path}.${name}`
104
+ const value = normalizeFieldValue(field, Object.hasOwn(values, name) ? values[name] : undefined, locales, fieldPath)
105
+ if (field.required && !isFilled(field, value, locales.defaultLocale)) {
106
+ const where = TRANSLATED_TYPES.has(field.type) ? ` in the default locale (${locales.defaultLocale})` : ''
107
+ throw new ProtocolError(`This field is required${where}.`, fieldPath)
108
+ }
109
+ return [name, value]
110
+ })
111
+ .filter(([, value]) => value !== undefined),
112
+ )
113
+ }
114
+
115
+ /**
116
+ * @param {string[]} values
117
+ * @param {string} message
118
+ */
119
+ function checkUnique(values, message) {
120
+ const seen = new Set()
121
+ for (const value of values) {
122
+ if (seen.has(value)) throw new ProtocolError(`${message} "${value}".`, 'entries')
123
+ seen.add(value)
124
+ }
125
+ }
@@ -0,0 +1,164 @@
1
+ import { ProtocolError } from '../ProtocolError.js'
2
+ import { parseRatio } from '../ratio.js'
3
+ import { isPlainObject } from '../values.js'
4
+
5
+ /** @typedef {import('./types.js').Field} Field */
6
+ /** @typedef {import('./types.js').FieldType} FieldType */
7
+ /** @typedef {import('./types.js').SelectOption} SelectOption */
8
+ /** @typedef {(definition: Record<string, unknown>, path: string, collections: string[]) => object} OptionsReader */
9
+
10
+ /** Options every field may have. */
11
+ const COMMON_OPTIONS = ['type', 'label', 'required']
12
+
13
+ /**
14
+ * The options of each type, besides the common ones, and how they are read.
15
+ * @type {Map<FieldType, { options: string[], read: OptionsReader }>}
16
+ */
17
+ const FIELD_TYPES = new Map([
18
+ ['text', { options: ['max'], read: (definition, path) => ({ max: readCount(definition.max, 'max', path) }) }],
19
+ ['richtext', { options: ['max'], read: (definition, path) => ({ max: readCount(definition.max, 'max', path) }) }],
20
+ ['image', { options: ['ratio'], read: (definition, path) => ({ ratio: readRatio(definition.ratio, path) }) }],
21
+ ['gallery', { options: ['ratio', 'max'], read: (definition, path) => ({ ratio: readRatio(definition.ratio, path), max: readCount(definition.max, 'max', path) }) }],
22
+ ['video', { options: [], read: () => ({}) }],
23
+ ['date', { options: [], read: () => ({}) }],
24
+ ['number', { options: ['min', 'max', 'integer'], read: readNumberOptions }],
25
+ ['select', { options: ['options', 'multiple'], read: (definition, path) => ({ options: readOptions(definition.options, path), multiple: readFlag(definition.multiple, 'multiple', path) }) }],
26
+ ['relation', { options: ['collection', 'multiple'], read: (definition, path, collections) => ({ collection: readTarget(definition.collection, collections, path), multiple: readFlag(definition.multiple, 'multiple', path) }) }],
27
+ ])
28
+
29
+ /** The field types, in the order the protocol lists them. */
30
+ export const FIELD_TYPE_NAMES = [...FIELD_TYPES.keys()]
31
+
32
+ /**
33
+ * Checks the definition of a field and completes it with its defaults.
34
+ * @param {string} name
35
+ * @param {unknown} definition
36
+ * @param {string} path Where the field is, for error messages.
37
+ * @param {string[]} collections The names of every collection, for relations.
38
+ * @returns {Field}
39
+ */
40
+ export function normalizeField(name, definition, path, collections) {
41
+ if (!isPlainObject(definition)) throw new ProtocolError('A field must be an object with a type, such as { type: "text" }.', path)
42
+ const type = /** @type {FieldType} */ (definition.type)
43
+ const fieldType = FIELD_TYPES.get(type)
44
+ if (!fieldType) throw new ProtocolError(`"${definition.type}" is not a field type. Use one of: ${FIELD_TYPE_NAMES.join(', ')}.`, path)
45
+ const unknown = Object.keys(definition).find((option) => !COMMON_OPTIONS.includes(option) && !fieldType.options.includes(option))
46
+ if (unknown) throw new ProtocolError(`${unknown} does not apply to ${type} fields.`, path)
47
+ const label = readLabel(definition.label, name, path)
48
+ const required = readFlag(definition.required, 'required', path)
49
+ return /** @type {Field} */ ({ type, label, required, ...fieldType.read(definition, path, collections) })
50
+ }
51
+
52
+ /**
53
+ * A label for the editor: a text that isn't empty, or the name.
54
+ * @param {unknown} label
55
+ * @param {string} name
56
+ * @param {string} path
57
+ * @returns {string}
58
+ */
59
+ export function readLabel(label, name, path) {
60
+ if (label === undefined) return name
61
+ if (typeof label !== 'string' || !label.trim()) throw new ProtocolError('A label must be a text that isn\'t empty.', path)
62
+ return label.trim()
63
+ }
64
+
65
+ /**
66
+ * @param {unknown} flag
67
+ * @param {string} option
68
+ * @param {string} path
69
+ * @returns {boolean}
70
+ */
71
+ export function readFlag(flag, option, path) {
72
+ if (flag === undefined) return false
73
+ if (typeof flag !== 'boolean') throw new ProtocolError(`${option} must be true or false.`, path)
74
+ return flag
75
+ }
76
+
77
+ /**
78
+ * @param {unknown} count
79
+ * @param {string} option
80
+ * @param {string} path
81
+ * @returns {number | null}
82
+ */
83
+ function readCount(count, option, path) {
84
+ if (count === undefined) return null
85
+ if (!Number.isInteger(count) || /** @type {number} */ (count) < 1) throw new ProtocolError(`${option} must be a whole number greater than 0.`, path)
86
+ return /** @type {number} */ (count)
87
+ }
88
+
89
+ /**
90
+ * @param {unknown} ratio
91
+ * @param {string} path
92
+ * @returns {number | null}
93
+ */
94
+ function readRatio(ratio, path) {
95
+ if (ratio === undefined) return null
96
+ if (typeof ratio !== 'string' && typeof ratio !== 'number') throw new ProtocolError('ratio must be like CSS aspect-ratio, such as "4/5" or 1.5.', path)
97
+ try {
98
+ return parseRatio(String(ratio))
99
+ } catch (error) {
100
+ throw new ProtocolError(/** @type {Error} */ (error).message, path)
101
+ }
102
+ }
103
+
104
+ /**
105
+ * @param {Record<string, unknown>} definition
106
+ * @param {string} path
107
+ * @returns {{ min: number | null, max: number | null, integer: boolean }}
108
+ */
109
+ function readNumberOptions(definition, path) {
110
+ const min = readBound(definition.min, 'min', path)
111
+ const max = readBound(definition.max, 'max', path)
112
+ if (min !== null && max !== null && min > max) throw new ProtocolError('min cannot be greater than max.', path)
113
+ return { min, max, integer: readFlag(definition.integer, 'integer', path) }
114
+ }
115
+
116
+ /**
117
+ * @param {unknown} bound
118
+ * @param {string} option
119
+ * @param {string} path
120
+ * @returns {number | null}
121
+ */
122
+ function readBound(bound, option, path) {
123
+ if (bound === undefined) return null
124
+ if (typeof bound !== 'number' || !Number.isFinite(bound)) throw new ProtocolError(`${option} must be a number.`, path)
125
+ return bound
126
+ }
127
+
128
+ /**
129
+ * @param {unknown} options
130
+ * @param {string} path
131
+ * @returns {Required<SelectOption>[]}
132
+ */
133
+ function readOptions(options, path) {
134
+ if (!Array.isArray(options) || options.length === 0) {
135
+ throw new ProtocolError('A select field needs options: a list of values, or of { value, label }.', path)
136
+ }
137
+ const read = options.map((option, index) => readOption(option, `${path}.options[${index}]`))
138
+ if (new Set(read.map((option) => option.value)).size !== read.length) throw new ProtocolError('Option values cannot repeat.', path)
139
+ return read
140
+ }
141
+
142
+ /**
143
+ * @param {unknown} option
144
+ * @param {string} path
145
+ * @returns {Required<SelectOption>}
146
+ */
147
+ function readOption(option, path) {
148
+ const value = isPlainObject(option) ? option.value : option
149
+ if (typeof value !== 'string' || !value) throw new ProtocolError('An option must be a value (a text that isn\'t empty) or { value, label }.', path)
150
+ return { value, label: isPlainObject(option) ? readLabel(option.label, value, path) : value }
151
+ }
152
+
153
+ /**
154
+ * @param {unknown} collection
155
+ * @param {string[]} collections
156
+ * @param {string} path
157
+ * @returns {string}
158
+ */
159
+ function readTarget(collection, collections, path) {
160
+ if (typeof collection !== 'string' || !collections.includes(collection)) {
161
+ throw new ProtocolError(`A relation needs the name of one of the collections (${collections.join(', ')}), not "${collection}".`, path)
162
+ }
163
+ return collection
164
+ }
@@ -0,0 +1,35 @@
1
+ const NAME = /^[A-Za-z][A-Za-z0-9_-]*$/
2
+ const MAX_NAME_LENGTH = 64
3
+
4
+ const ID = /^[A-Za-z0-9_-]+$/
5
+ const MAX_ID_LENGTH = 64
6
+
7
+ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
8
+ const MAX_SLUG_LENGTH = 200
9
+
10
+ /**
11
+ * Whether a string is a valid name for a collection or a field, such as `courses` or `coverImage`.
12
+ * @param {unknown} name
13
+ * @returns {name is string}
14
+ */
15
+ export function isValidName(name) {
16
+ return typeof name === 'string' && name.length <= MAX_NAME_LENGTH && NAME.test(name)
17
+ }
18
+
19
+ /**
20
+ * Whether a string is a valid entry id, such as `8f1c2d` or `aroma-workshop`.
21
+ * @param {unknown} id
22
+ * @returns {id is string}
23
+ */
24
+ export function isValidId(id) {
25
+ return typeof id === 'string' && id.length <= MAX_ID_LENGTH && ID.test(id)
26
+ }
27
+
28
+ /**
29
+ * Whether a string is a valid slug: lowercase letters and digits separated by hyphens, such as `aroma-workshop`.
30
+ * @param {unknown} slug
31
+ * @returns {slug is string}
32
+ */
33
+ export function isValidSlug(slug) {
34
+ return typeof slug === 'string' && slug.length <= MAX_SLUG_LENGTH && SLUG.test(slug)
35
+ }
@@ -0,0 +1,6 @@
1
+ export { defineCollection, normalizeCollections } from './collections.js'
2
+ export { FIELD_TYPE_NAMES } from './fields.js'
3
+ export { normalizeFieldValue, TRANSLATED_TYPES } from './values.js'
4
+ export { normalizeEntry, normalizeCollectionDocument } from './entries.js'
5
+ export { resolveCollection } from './resolve.js'
6
+ export { isValidName, isValidId, isValidSlug } from './identifiers.js'
@@ -0,0 +1,71 @@
1
+ import { CONTENT_VERSION } from '../version.js'
2
+ import { TRANSLATED_TYPES } from './values.js'
3
+
4
+ /** @typedef {import('./types.js').Collection} Collection */
5
+ /** @typedef {import('./types.js').CollectionDocument} CollectionDocument */
6
+ /** @typedef {import('./types.js').Entry} Entry */
7
+ /** @typedef {import('./types.js').Field} Field */
8
+ /** @typedef {import('./types.js').FieldValue} FieldValue */
9
+ /** @typedef {import('./types.js').ResolvedCollection} ResolvedCollection */
10
+ /** @typedef {import('./types.js').ResolvedEntry} ResolvedEntry */
11
+ /** @typedef {import('../types.js').ImageValue} ImageValue */
12
+
13
+ /**
14
+ * The entries of a collection as a page in one locale shows them: each translated field
15
+ * with its own value or, where it is missing, the default locale's. Images are merged field
16
+ * by field, and galleries image by image: the default locale decides the images and their order.
17
+ * @param {CollectionDocument} document A normalized document.
18
+ * @param {Collection} collection Its collection, normalized.
19
+ * @param {string} locale One of the document's locales.
20
+ * @returns {ResolvedCollection}
21
+ */
22
+ export function resolveCollection(document, collection, locale) {
23
+ return {
24
+ version: CONTENT_VERSION,
25
+ collection: document.collection,
26
+ locale,
27
+ entries: document.entries.map((entry) => resolveEntry(entry, collection, locale, document.defaultLocale)),
28
+ }
29
+ }
30
+
31
+ /**
32
+ * @param {Entry} entry
33
+ * @param {Collection} collection
34
+ * @param {string} locale
35
+ * @param {string} defaultLocale
36
+ * @returns {ResolvedEntry}
37
+ */
38
+ function resolveEntry(entry, collection, locale, defaultLocale) {
39
+ const fields = Object.fromEntries(
40
+ Object.entries(collection.fields)
41
+ .map(([name, field]) => [name, resolveField(field, Object.hasOwn(entry.fields, name) ? entry.fields[name] : undefined, locale, defaultLocale)])
42
+ .filter(([, value]) => value !== undefined),
43
+ )
44
+ const slug = entry.slug && (entry.slug[locale] ?? entry.slug[defaultLocale])
45
+ return slug ? { id: entry.id, slug, fields } : { id: entry.id, fields }
46
+ }
47
+
48
+ /**
49
+ * @param {Field} field
50
+ * @param {any} value
51
+ * @param {string} locale
52
+ * @param {string} defaultLocale
53
+ * @returns {FieldValue | undefined}
54
+ */
55
+ function resolveField(field, value, locale, defaultLocale) {
56
+ if (value === undefined || !TRANSLATED_TYPES.has(field.type)) return value
57
+ const own = value[locale]
58
+ const fallback = value[defaultLocale]
59
+ if (field.type === 'image') return mergeImage(own, fallback)
60
+ if (field.type === 'gallery') return fallback ? fallback.map((/** @type {ImageValue} */ image, /** @type {number} */ index) => mergeImage(own?.[index], image)) : own
61
+ return own ?? fallback
62
+ }
63
+
64
+ /**
65
+ * @param {ImageValue | undefined} own
66
+ * @param {ImageValue | undefined} fallback
67
+ * @returns {ImageValue | undefined}
68
+ */
69
+ function mergeImage(own, fallback) {
70
+ return own && fallback ? { ...fallback, ...own } : (own ?? fallback)
71
+ }