@panneau/protocol 5.0.0-alpha.27 → 5.0.0-alpha.28
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/conformance/index.d.ts.map +1 -1
- package/dist/conformance/index.js +30 -4
- package/dist/conformance/index.js.map +1 -1
- package/dist/mock/index.d.ts.map +1 -1
- package/dist/mock/index.js +9 -2
- package/dist/mock/index.js.map +1 -1
- package/dist/rules.d.ts +2 -1
- package/dist/rules.d.ts.map +1 -1
- package/dist/rules.js +3 -2
- package/dist/rules.js.map +1 -1
- package/dist/schemas/action.d.ts +1 -0
- package/dist/schemas/action.d.ts.map +1 -1
- package/dist/schemas/definition.d.ts +2 -0
- package/dist/schemas/definition.d.ts.map +1 -1
- package/dist/schemas/field.d.ts +1 -0
- package/dist/schemas/field.d.ts.map +1 -1
- package/dist/schemas/field.js +1 -0
- package/dist/schemas/field.js.map +1 -1
- package/dist/schemas/index.d.ts +6 -0
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/resource.d.ts +2 -0
- package/dist/schemas/resource.d.ts.map +1 -1
- package/package.json +1 -1
- package/schema/boot.schema.json +3 -0
- package/schema/definition.schema.json +3 -0
- package/schema/openapi.json +4 -0
package/dist/mock/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/mock/index.ts"],"sourcesContent":["import {\n CONTEXT_HEADER,\n CONTEXT_PROBLEM_TYPE,\n IDS_FILTER,\n IDS_FILTER_LIMIT,\n ITEM_ACTION_ABILITIES,\n UNDO_LIMIT,\n isBuiltInItemAction,\n} from '../constants';\nimport { type ContextValues, contextBefore, parseContextHeader } from '../context';\nimport { getMediaLibraries } from '../libraries';\nimport { type ListQuery, fromSearchParams, isFilterRange, matchesFilterRange } from '../query';\nimport { type RuleFailure, checkValues } from '../rules';\nimport type { ContextOption, DefinitionInput, ResourceInput } from '../schemas';\nimport type {\n ActionResult,\n EmbedValue,\n FieldCheckResponse,\n Item,\n MediaInfo,\n MediaReference,\n PreviewResponse,\n Problem,\n SearchResponse,\n Selection,\n StoredFile,\n Upload,\n UploadSignResponse,\n} from '../schemas/api';\nimport { SEARCH_MAX_LIMIT, readSearchQuery } from '../search';\nimport { isRecord } from '../values';\nimport { PROBLEM_CONTENT_TYPE } from '../version';\nimport { checkWidgetData, getWidgetResource } from '../widgets';\nimport { type MockAuthOptions, createMockAuth } from './auth';\n\nexport type { MockAuthOptions, MockMail, MockUser } from './auth';\n\ntype Values = Record<string, unknown>;\n\nexport interface MockBackendOptions {\n /** The definition served by `GET /definition`. Its `api.baseUrl` is the prefix of every route. */\n definition: DefinitionInput;\n /** Initial values of the items, per resource id. Items without an `id` get one. */\n items?: Record<string, Values[]>;\n /**\n * The URL that `POST /resources/{resource}/{id}/preview` returns, for the item with the posted\n * values. Defaults to a `data:` URL of a plain page with the item's values.\n */\n previewUrl?: (context: { resource: string; item: Item }) => string;\n /**\n * The value of `GET /embeds?url=` for a URL, or `null` to refuse it with a `422`. Defaults to\n * a video for YouTube and Vimeo URLs, and a link for other web pages.\n */\n embed?: (url: string) => EmbedValue | null;\n /**\n * The current context, when the definition has `context` (decision 0045). The values of the\n * `Panneau-Context` header are checked against the choices of each param: a value that isn't\n * one is a `403` problem.\n */\n context?: MockContextOptions;\n /**\n * Users and a session, for the `panneau` auth mode: the auth routes answer, guests get a `401`\n * on the other routes, and with `auth.emailVerification`, users whose address isn't verified\n * get its `403` problem (decision 0048). Without it, every request is the user's.\n */\n auth?: MockAuthOptions;\n /**\n * The data of `GET /dashboard/widgets/{widget}`, per widget id (decision 0064): the data, a\n * function that returns it for the current context, or a `Response` to answer as is (a `403`,\n * a slow or failing widget). Data that doesn't have the shape of a built-in type is a `500`\n * problem that names the wrong keys, as a backend answers it. Widgets of the dashboard without\n * data, and built-in `stat` and `list` on a resource, are a `404`.\n */\n widgets?: Record<string, MockWidget>;\n /**\n * Whether something else uses an item, so that it can't be deleted: `delete` skips it with\n * the reason `in_use`, and its `undo` leaves it out. Without it, no item is in use.\n */\n inUse?: (context: { resource: string; item: Item }) => boolean;\n}\n\n/** The data of a widget in the mock backend: its data, or what answers it. */\nexport type MockWidget =\n | Response\n | Record<string, unknown>\n | ((\n context: MockWidgetContext,\n ) => Response | Record<string, unknown> | Promise<Response | Record<string, unknown>>);\n\n/** What the function of a widget of the mock backend gets. */\nexport interface MockWidgetContext {\n /** The values of the context of the request. */\n context: ContextValues;\n /** The current items of a resource, in the context. */\n items: (resource: string) => Item[];\n}\n\n/** How the mock backend answers the context of its definition (decision 0045). */\nexport interface MockContextOptions {\n /**\n * Every choice of a param without inline `options`, for the values of the params before it.\n * `GET /context/{name}/options?q=` gives the first 20 whose label matches `q`.\n */\n options?: (name: string, before: ContextValues) => ContextOption[];\n /** Whether an item of a resource is in the context, for lists, items, actions and search. */\n scope?: (resource: string, item: Item, values: ContextValues) => boolean;\n}\n\nexport interface MockBackend {\n /** A `fetch`-compatible function that answers protocol requests. */\n fetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n /** The current items of a resource. */\n items: (resource: string) => Item[];\n}\n\nconst RESERVED_KEYS = new Set(['id', 'version', 'abilities']);\n\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (character) => `&#${character.charCodeAt(0)};`);\n}\n\n/** A plain page with the values of an item, as a `data:` URL, for iframe previews. */\nfunction defaultPreviewUrl(item: Item): string {\n const rows = Object.entries(item)\n .filter(([key]) => !RESERVED_KEYS.has(key))\n .map(\n ([key, value]) =>\n `<dt>${escapeHtml(key)}</dt><dd>${escapeHtml(typeof value === 'string' ? value : JSON.stringify(value))}</dd>`,\n )\n .join('');\n const html = `<!doctype html><meta charset=\"utf-8\"><title>Preview</title><body style=\"font-family:system-ui;margin:2rem\"><h1>Item ${escapeHtml(item.id)}</h1><dl>${rows}</dl></body>`;\n return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;\n}\n\n/** What the mock knows of a URL to embed: a video of YouTube or Vimeo, or a web page. */\nfunction defaultEmbed(url: string): EmbedValue | null {\n if (!URL.canParse(url)) {\n return null;\n }\n const parsed = new URL(url);\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {\n return null;\n }\n const host = parsed.hostname.replace(/^www\\./, '');\n const youtube =\n host === 'youtu.be'\n ? parsed.pathname.slice(1)\n : host.endsWith('youtube.com')\n ? parsed.searchParams.get('v')\n : null;\n if (youtube !== null && youtube !== '') {\n return {\n url,\n type: 'video',\n provider: 'YouTube',\n title: `YouTube video ${youtube}`,\n thumbnailUrl: `https://i.ytimg.com/vi/${youtube}/hqdefault.jpg`,\n html: `<iframe src=\"https://www.youtube.com/embed/${youtube}\" width=\"560\" height=\"315\" allowfullscreen></iframe>`,\n width: 560,\n height: 315,\n };\n }\n if (host === 'vimeo.com') {\n const id = parsed.pathname.split('/').filter(Boolean)[0] ?? '';\n return {\n url,\n type: 'video',\n provider: 'Vimeo',\n title: `Vimeo video ${id}`,\n html: `<iframe src=\"https://player.vimeo.com/video/${id}\" width=\"640\" height=\"360\" allowfullscreen></iframe>`,\n width: 640,\n height: 360,\n };\n }\n return { url, type: 'link', provider: host, title: host };\n}\n\nconst DEFAULT_MESSAGES: Record<string, (failure: RuleFailure) => string> = {\n required: () => 'This field is required.',\n min: (failure) => `This value must be at least ${String(failure.value)}.`,\n max: (failure) => `This value must be at most ${String(failure.value)}.`,\n pattern: () => 'This value has an invalid format.',\n email: () => 'This value must be an email address.',\n url: () => 'This value must be a URL.',\n json: () => 'This value must be valid JSON: an object or an array.',\n in: () => 'This value is not one of the choices.',\n accept: () => 'This file type is not accepted.',\n maxSize: () => 'This file is too large.',\n before: () => 'This date is too late.',\n after: () => 'This date is too early.',\n providers: (failure) =>\n `This embed must come from ${Array.isArray(failure.value) ? failure.value.join(' or ') : 'another provider'}.`,\n crop: (failure) => {\n const ratios = isRecord(failure.value) ? failure.value.ratios : undefined;\n return Array.isArray(ratios) && ratios.length > 0\n ? `Crop this image to ${ratios.join(' or ')}.`\n : 'Crop this image.';\n },\n};\n\nfunction message(failure: RuleFailure): string {\n return failure.message ?? DEFAULT_MESSAGES[failure.rule]?.(failure) ?? 'This value is invalid.';\n}\n\nfunction json(status: number, body: unknown, headers: Record<string, string> = {}): Response {\n return new Response(status === 204 ? null : JSON.stringify(body), {\n status,\n headers: status === 204 ? headers : { 'Content-Type': 'application/json', ...headers },\n });\n}\n\nfunction problem(status: number, title: string, extra: Partial<Problem> = {}): Response {\n const body: Problem = { type: 'about:blank', title, status, ...extra };\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': PROBLEM_CONTENT_TYPE },\n });\n}\n\nfunction etag(item: Item): Record<string, string> {\n return item.version === null ? {} : { ETag: `\"${item.version}\"` };\n}\n\nfunction parseEtag(value: string): string {\n return value.replace(/^W\\//, '').replace(/^\"(.*)\"$/, '$1');\n}\n\nfunction searchableText(value: unknown): string {\n if (typeof value === 'string') {\n return value;\n }\n if (isRecord(value)) {\n return Object.values(value).map(searchableText).join(' ');\n }\n return '';\n}\n\n/** What a value sorts by: the start of a `daterange`, the amount of `money`, or its text. */\nfunction sortValue(value: unknown): unknown {\n if (!isRecord(value)) {\n return value;\n }\n if ('start' in value && 'end' in value) {\n return value.start ?? value.end;\n }\n if ('currency' in value && typeof value.amount === 'number') {\n return value.amount;\n }\n return searchableText(value);\n}\n\nfunction compare(a: unknown, b: unknown): number {\n const left = sortValue(a);\n const right = sortValue(b);\n if (left === right) {\n return 0;\n }\n if (left === undefined || left === null) {\n return 1;\n }\n if (right === undefined || right === null) {\n return -1;\n }\n if (typeof left === 'number' && typeof right === 'number') {\n return left - right;\n }\n return String(left).localeCompare(String(right), undefined, { numeric: true });\n}\n\nfunction applyQuery(items: Item[], query: Pick<ListQuery, 'filter' | 'q' | 'sort'>): Item[] {\n let result = items;\n Object.entries(query.filter ?? {}).forEach(([key, expected]) => {\n // Every list filters on the ids of its items (decision 0069).\n if (key === IDS_FILTER) {\n const ids = (Array.isArray(expected) ? expected : [expected])\n .map(String)\n .slice(0, IDS_FILTER_LIMIT);\n result = result.filter((item) => ids.includes(item.id));\n return;\n }\n if (isFilterRange(expected)) {\n result = result.filter((item) => matchesFilterRange(item[key], expected));\n return;\n }\n const accepted = (Array.isArray(expected) ? expected : [expected]).map(String);\n result = result.filter((item) => {\n // A filter that isn't a value of the item reads its `media`: `filter[type]=image`.\n const value =\n key in item ? item[key] : isRecord(item.media) ? item.media[key] : undefined;\n const values = Array.isArray(value) ? value : [value];\n return values.some((candidate) => accepted.includes(String(candidate)));\n });\n });\n if (query.q !== undefined && query.q !== '') {\n const terms = query.q.toLowerCase();\n result = result.filter((item) =>\n Object.entries(item)\n .filter(([key]) => !RESERVED_KEYS.has(key))\n .some(([, value]) => searchableText(value).toLowerCase().includes(terms)),\n );\n }\n const sort = query.sort ?? [];\n if (sort.length > 0) {\n result = [...result].sort((a, b) => {\n for (const part of sort) {\n const descending = part.startsWith('-');\n const key = descending ? part.slice(1) : part;\n const order = compare(a[key], b[key]);\n if (order !== 0) {\n return descending ? -order : order;\n }\n }\n return 0;\n });\n }\n return result;\n}\n\n/** The type of a media, from its MIME type. */\nfunction mediaType(mime: string | null | undefined): string {\n const family = (mime ?? '').split('/')[0] ?? '';\n if (family === 'image' || family === 'video' || family === 'audio') {\n return family;\n }\n return mime === 'application/pdf' || family === 'text' ? 'document' : 'other';\n}\n\n/** What the mock computes about a stored file: no renditions, ready at once. */\nfunction mediaOf(file: StoredFile): MediaInfo {\n const type = mediaType(file.mime);\n return {\n type,\n mime: file.mime ?? null,\n size: file.size ?? null,\n url: file.url ?? null,\n thumbnailUrl: type === 'image' ? (file.url ?? null) : null,\n status: 'ready',\n };\n}\n\n/**\n * A media item with its own transform (its `transform` field) in its `media`, where references\n * give it to clients (decision 0031).\n */\nfunction withOwnTransform(resource: ResourceInput, item: Item): Item {\n if (resource.kind !== 'media' || !isRecord(item.media)) {\n return item;\n }\n const { transform: _previous, ...media } = item.media;\n return {\n ...item,\n media: isRecord(item.transform) ? { ...media, transform: item.transform } : media,\n };\n}\n\n/**\n * Whether an item allows an action, as clients read its abilities (decision 0040): a built-in item\n * action needs its ability (`delete`, `duplicate`…), and another action its id.\n */\nfunction allows(item: Item, actionId: string): boolean {\n const ability = isBuiltInItemAction(actionId) ? ITEM_ACTION_ABILITIES[actionId] : actionId;\n return item.abilities[ability] === true && item.abilities[actionId] !== false;\n}\n\n/** The names of the fields of a resource whose ability is `false` (decision 0046). */\nfunction fieldsWithout(resource: ResourceInput, ability: 'view' | 'update'): Set<string> {\n return new Set(\n resource.fields\n .filter((field) => field.abilities?.[ability] === false)\n .map((field) => field.name),\n );\n}\n\n/** A body without the values of the fields the user can't see or update, which are ignored. */\nfunction writableValues(resource: ResourceInput, body: Values): Values {\n const ignored = new Set([\n ...fieldsWithout(resource, 'view'),\n ...fieldsWithout(resource, 'update'),\n ]);\n return Object.fromEntries(Object.entries(body).filter(([key]) => !ignored.has(key)));\n}\n\n/**\n * An in-memory backend that implements the protocol's resource routes: definition, list, show,\n * create, update (with `If-Match`), delete, duplicate and the built-in `delete` action. A resource\n * that declares its `delete` `undoable` has a trash: the result of `delete` says how to undo it,\n * and the built-in `restore` puts the items back (decision 0063). Its items\n * allow every built-in item action (`view`, `update`, `duplicate`, `delete`), unless an item of\n * `items` gives its own `abilities`. It reads abilities as clients do (decision 0046): a resource\n * without `viewAny` answers `403` on its list, one without `create` on creates, an item without\n * `view`, `update` or `delete` on those requests; items leave out the values of fields with\n * `view: false`, and writes ignore those of fields with `update: false`. Values are checked with\n * the portable rules. Used to test the conformance kit, and to develop frontends without a real\n * backend.\n */\nexport function createMockBackend(options: MockBackendOptions): MockBackend {\n const { definition, items = {} } = options;\n const auth = options.auth !== undefined ? createMockAuth(options.auth, definition.auth) : null;\n const store = new Map<string, Item[]>();\n // The deleted items of the resources whose `delete` is undoable: their trash (decision 0063).\n const trash = new Map<string, Item[]>();\n let nextId = 1;\n\n const abilitiesFor = (resource: ResourceInput) =>\n Object.fromEntries([\n ['view', true],\n ['update', true],\n ['duplicate', true],\n ['delete', true],\n ...(resource.actions ?? []).map((action) => [action.id, true]),\n ]);\n\n // An id that no item of the resource has, also among the items it started with\n const freshId = (resource: ResourceInput): string => {\n const items = store.get(resource.id) ?? [];\n let id = String(nextId++);\n while (items.some((item) => item.id === id)) {\n id = String(nextId++);\n }\n return id;\n };\n\n const makeItem = (resource: ResourceInput, values: Values): Item => {\n const id =\n typeof values.id === 'string' || typeof values.id === 'number'\n ? String(values.id)\n : freshId(resource);\n const rest = Object.fromEntries(\n Object.entries(values).filter(([key]) => !RESERVED_KEYS.has(key)),\n );\n const own = isRecord(values.abilities) ? (values.abilities as Record<string, boolean>) : {};\n return { ...rest, id, version: '1', abilities: { ...abilitiesFor(resource), ...own } };\n };\n\n // What the user gets of an item: without the values of the fields they can't see.\n const present = (resource: ResourceInput, item: Item): Item => {\n const hidden = fieldsWithout(resource, 'view');\n return hidden.size === 0\n ? item\n : (Object.fromEntries(\n Object.entries(item).filter(([key]) => !hidden.has(key)),\n ) as Item);\n };\n\n definition.resources.forEach((resource) => {\n store.set(\n resource.id,\n (items[resource.id] ?? []).map((values) => makeItem(resource, values)),\n );\n });\n\n const basePath = new URL(definition.api.baseUrl, 'http://panneau.test').pathname.replace(\n /\\/$/,\n '',\n );\n\n const validationProblem = (\n resource: ResourceInput,\n values: Values,\n mode: 'create' | 'update',\n item?: Item,\n ) => {\n // A partial update reads the conditions with the item's values (decision 0043).\n const failures = checkValues(resource.fields, values, {\n mode,\n partial: mode === 'update',\n locales: definition.locales,\n ...(item !== undefined ? { item } : {}),\n });\n const paths = Object.keys(failures);\n if (paths.length === 0) {\n return null;\n }\n return problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: Object.fromEntries(\n paths.map((path) => [path, (failures[path] ?? []).map(message)]),\n ),\n });\n };\n\n const selectItems = (list: Item[], selection: Selection | undefined): Item[] => {\n if (selection === undefined) {\n return [];\n }\n if ('ids' in selection) {\n const ids = selection.ids as string[];\n return list.filter((item) => ids.includes(item.id));\n }\n const except = selection.except ?? [];\n const { filter, q } = selection.query;\n const query: Pick<ListQuery, 'filter' | 'q'> = {};\n if (filter !== undefined) {\n query.filter = filter as NonNullable<ListQuery['filter']>;\n }\n if (q !== undefined) {\n query.q = q;\n }\n return applyQuery(list, query).filter((item) => !except.includes(item.id));\n };\n\n // Direct uploads: the open uploads by id, with their key. The mock signs fake URLs, and\n // trusts the client when it completes an upload.\n const uploads = new Map<string, Upload>();\n let nextUpload = 1;\n\n const handleUploads = async (\n segments: string[],\n method: string,\n readBody: () => Promise<Values>,\n ): Promise<Response> => {\n if (definition.uploads?.mode !== 'presigned') {\n return problem(404, 'Not found.');\n }\n if (method !== 'POST') {\n return problem(405, 'Method not allowed.');\n }\n if (segments.length === 2 && segments[1] === 'sign') {\n const body = await readBody();\n const opens =\n body.uploadId === undefined && (body.method === 'POST' || body.method === 'PUT');\n if (opens) {\n const id = `upl_${nextUpload++}`;\n const upload: Upload = { id, key: `uploads/${id}` };\n uploads.set(id, upload);\n const response: UploadSignResponse = {\n url: `https://storage.test/${upload.key}?signature=mock`,\n key: upload.key,\n upload: id,\n };\n return json(200, response);\n }\n const upload = [...uploads.values()].find((candidate) => candidate.key === body.key);\n if (upload === undefined) {\n return problem(404, 'Upload not found.');\n }\n return json(200, { url: `https://storage.test/${upload.key}?signature=mock` });\n }\n if (segments.length === 3 && segments[2] === 'complete' && segments[1] !== undefined) {\n const upload = uploads.get(segments[1]);\n if (upload === undefined) {\n return problem(404, 'Upload not found.');\n }\n const { name } = await readBody();\n if (typeof name === 'string') {\n upload.name = name;\n }\n return json(200, { data: upload });\n }\n return problem(404, 'Not found.');\n };\n\n // The values of `file` fields at the top of a resource: an upload becomes a stored file, and\n // a stored file or null is kept. Returns the paths of uploads that don't exist.\n const resolveFiles = (\n resource: ResourceInput,\n values: Values,\n ): { values: Values; missing: string[] } => {\n const missing: string[] = [];\n const resolved = { ...values };\n const toFile = (value: unknown, path: string): unknown => {\n if (!isRecord(value) || typeof value.upload !== 'string') {\n return value;\n }\n const upload = uploads.get(value.upload);\n if (upload === undefined) {\n missing.push(path);\n return value;\n }\n const file: StoredFile = {\n name: upload.name ?? (typeof value.name === 'string' ? value.name : upload.id),\n url: `https://storage.test/${upload.key ?? upload.id}`,\n mime: upload.mime ?? (typeof value.mime === 'string' ? value.mime : null),\n size: upload.size ?? (typeof value.size === 'number' ? value.size : null),\n };\n return file;\n };\n resource.fields\n .filter((field) => field.type === 'file' && field.name in values)\n .forEach((field) => {\n const value = values[field.name];\n resolved[field.name] = Array.isArray(value)\n ? value.map((entry, index) => toFile(entry, `${field.name}.${String(index)}`))\n : toFile(value, field.name);\n });\n return { values: resolved, missing };\n };\n\n const missingMedia = (paths: Record<string, string>) =>\n problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: Object.fromEntries(\n Object.entries(paths).map(([path, message]) => [path, [message]]),\n ),\n });\n\n const missingUploads = (paths: string[]) =>\n problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: Object.fromEntries(\n paths.map((path) => [path, ['This upload does not exist.']]),\n ),\n });\n\n // The values of `media` and `image` fields at the top of a resource: an id, or\n // `{ id, resource, transform }`, becomes a reference to a media of one of its libraries. A\n // field that allows several libraries needs the library of each media (decision 0027).\n // Returns the problems by path.\n const resolveMedia = (\n resource: ResourceInput,\n values: Values,\n ): { values: Values; missing: Record<string, string> } => {\n const missing: Record<string, string> = {};\n const resolved = { ...values };\n resource.fields\n .filter(\n (field) =>\n (field.type === 'media' || field.type === 'image') && field.name in values,\n )\n .forEach((field) => {\n const allowed = getMediaLibraries(definition, field);\n const toReference = (value: unknown, path: string): unknown => {\n const id = isRecord(value) ? value.id : value;\n if (typeof id !== 'string' && typeof id !== 'number') {\n return value;\n }\n const named =\n isRecord(value) && typeof value.resource === 'string'\n ? value.resource\n : undefined;\n if (named === undefined && allowed.length > 1) {\n missing[path] = 'This field allows several libraries: name the library.';\n return value;\n }\n const libraryId = named ?? allowed[0];\n const library = definition.resources.find(\n (candidate) => candidate.id === libraryId && allowed.includes(candidate.id),\n );\n const media = (store.get(library?.id ?? '') ?? []).find(\n (candidate) => candidate.id === String(id),\n );\n if (media === undefined || library === undefined) {\n missing[path] = 'This media does not exist.';\n return value;\n }\n const title = media[library.itemTitle ?? 'name'];\n const reference: MediaReference = {\n id: media.id,\n ...(allowed.length > 1 ? { resource: library.id } : {}),\n ...(typeof title === 'string' ? { label: title } : {}),\n ...(isRecord(media.media) ? { media: media.media as MediaInfo } : {}),\n ...(isRecord(value) && isRecord(value.transform)\n ? { transform: value.transform }\n : {}),\n };\n return reference;\n };\n const value = values[field.name];\n resolved[field.name] = Array.isArray(value)\n ? value.map((entry, index) =>\n toReference(entry, `${field.name}.${String(index)}`),\n )\n : toReference(value, field.name);\n });\n return { values: resolved, missing };\n };\n\n // Resolves the files and media of the values, and computes the `media` of a media item from\n // its file. The client never sets `media`.\n const resolveValues = (\n resource: ResourceInput,\n body: Values,\n ): { values: Values; problem: Response | null } => {\n const sent = { ...body };\n if (resource.kind === 'media') {\n delete sent.media;\n }\n const files = resolveFiles(resource, sent);\n if (files.missing.length > 0) {\n return { values: body, problem: missingUploads(files.missing) };\n }\n const media = resolveMedia(resource, files.values);\n if (Object.keys(media.missing).length > 0) {\n return { values: body, problem: missingMedia(media.missing) };\n }\n const values = media.values;\n if (resource.kind === 'media' && isRecord(values.file)) {\n values.media = mediaOf(values.file as StoredFile);\n }\n return { values, problem: null };\n };\n\n // The global search (decision 0029): the searchable resources asked for, `limit` items each\n // (5 by default), 20 in all, from 2 characters.\n const search = (\n params: URLSearchParams,\n inScope: (resource: string, list: Item[]) => Item[],\n ): Response => {\n const read = readSearchQuery(params, definition);\n if (read.errors !== undefined) {\n return problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: read.errors,\n });\n }\n const { q, limit, resources } = read.query;\n let left = SEARCH_MAX_LIMIT;\n const data: SearchResponse['data'] = resources.flatMap((id) => {\n if (left === 0) {\n return [];\n }\n const searched = definition.resources.find((candidate) => candidate.id === id);\n if (searched === undefined || searched.abilities?.viewAny === false) {\n return [];\n }\n const found = applyQuery(inScope(id, store.get(id) ?? []), { q });\n const items = found\n .slice(0, Math.min(limit, left))\n .map((item) => present(searched, item));\n left -= items.length;\n return items.length > 0 ? [{ resource: id, items, total: found.length }] : [];\n });\n return json(200, { data } satisfies SearchResponse);\n };\n\n const params = definition.context?.params ?? [];\n const names = params.map(({ name }) => name);\n const choicesOf = (name: string, values: ContextValues): ContextOption[] => {\n const param = params.find((candidate) => candidate.name === name);\n return (\n param?.options ??\n options.context?.options?.(name, contextBefore(values, names, name)) ??\n []\n );\n };\n const refused = (name: string) =>\n problem(403, 'This value of the context can’t be used.', {\n type: CONTEXT_PROBLEM_TYPE,\n param: name,\n });\n /**\n * The values of the header that the definition declares, each one checked against its\n * choices, in order: a value that isn't one is a `403` problem with its `param`. A `fixed`\n * param has the value of the definition, as a backend would take it from the request: another\n * value in the header is refused.\n */\n const readContext = (header: string | null): ContextValues | Response => {\n const sent = parseContextHeader(header);\n const values: Record<string, string> = {};\n for (const param of params) {\n const { name } = param;\n const value = sent[name];\n if (param.fixed === true && typeof param.value === 'string') {\n if (value !== undefined && value !== param.value) {\n return refused(name);\n }\n values[name] = param.value;\n continue;\n }\n if (value === undefined) {\n continue;\n }\n if (!choicesOf(name, values).some((choice) => choice.value === value)) {\n return refused(name);\n }\n values[name] = value;\n }\n return values;\n };\n /** The definition for the values of the context: the `value` and `valueLabel` of each param. */\n // A widget of the dashboard with data of its own (decision 0064)\n const answerWidget = async (\n id: string,\n values: ContextValues,\n inScope: (resource: string, list: Item[]) => Item[],\n ): Promise<Response> => {\n const widget = definitionFor(values).dashboard?.widgets.find(\n (candidate) => candidate.id === id,\n );\n const data = options.widgets?.[id];\n if (widget === undefined || getWidgetResource(widget) !== null || data === undefined) {\n return problem(404, 'Widget not found.');\n }\n const answer =\n typeof data === 'function'\n ? await data({\n context: values,\n items: (resource) => inScope(resource, store.get(resource) ?? []),\n })\n : data;\n if (answer instanceof Response) {\n return answer;\n }\n const wrong = checkWidgetData(widget.type, answer);\n return wrong.length === 0\n ? json(200, answer)\n : problem(500, `The data of the widget doesn't have the shape of \\`${widget.type}\\`.`, {\n detail: `Wrong keys: ${wrong.map((key) => (key === '' ? '(the data)' : key)).join(', ')}.`,\n });\n };\n\n const definitionFor = (values: ContextValues): DefinitionInput =>\n definition.context === undefined\n ? definition\n : {\n ...definition,\n context: {\n ...definition.context,\n params: params.map((param) => {\n if (param.fixed === true) {\n return param;\n }\n const value = values[param.name] ?? null;\n const label =\n value !== null\n ? choicesOf(param.name, values).find(\n (choice) => choice.value === value,\n )?.label\n : undefined;\n return { ...param, value, valueLabel: label ?? null };\n }),\n },\n };\n\n const handle = async (request: Request): Promise<Response> => {\n const response = await answer(request);\n if (definition.context !== undefined) {\n response.headers.set('Vary', CONTEXT_HEADER);\n }\n return response;\n };\n\n const answer = async (request: Request): Promise<Response> => {\n const url = new URL(request.url, 'http://panneau.test');\n if (!url.pathname.startsWith(basePath)) {\n return problem(404, 'Not found.');\n }\n const segments = url.pathname\n .slice(basePath.length)\n .split('/')\n .filter((segment) => segment !== '')\n .map(decodeURIComponent);\n const method = request.method.toUpperCase();\n const readBody = async (): Promise<Values> => {\n const body: unknown = await request.json().catch(() => null);\n return isRecord(body) ? body : {};\n };\n\n if (auth !== null) {\n if (segments[0] === 'auth') {\n return auth.answer(segments.slice(1), method, readBody, url);\n }\n const account =\n segments[0] === 'account'\n ? auth.account(segments.slice(1), method, readBody)\n : null;\n if (account !== null) {\n return account;\n }\n const refused = auth.refuse();\n if (refused !== null) {\n return refused;\n }\n }\n\n const context = readContext(request.headers.get(CONTEXT_HEADER));\n if (context instanceof Response) {\n return context;\n }\n const inScope = (resource: string, list: Item[]): Item[] => {\n const scope = options.context?.scope;\n return scope !== undefined\n ? list.filter((item) => scope(resource, item, context))\n : list;\n };\n\n if (segments.length === 1 && segments[0] === 'definition' && method === 'GET') {\n const built = definitionFor(context);\n return json(200, auth !== null ? { ...built, user: auth.user() } : built);\n }\n if (\n segments.length === 3 &&\n segments[0] === 'context' &&\n segments[2] === 'options' &&\n method === 'GET'\n ) {\n const name = segments[1] ?? '';\n if (!names.includes(name)) {\n return problem(404, 'The context has no such param.');\n }\n const q = (url.searchParams.get('q') ?? '').trim().toLocaleLowerCase();\n const data = choicesOf(name, context)\n .filter((choice) => choice.label.toLocaleLowerCase().includes(q))\n .slice(0, 20);\n return json(200, { data });\n }\n if (segments.length === 1 && segments[0] === 'embeds' && method === 'GET') {\n const url = new URL(request.url, 'http://panneau.test').searchParams.get('url') ?? '';\n const embed = url === '' ? null : (options.embed ?? defaultEmbed)(url);\n return embed !== null\n ? json(200, { data: embed })\n : problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: { url: ['This URL can’t be embedded.'] },\n });\n }\n if (\n segments.length === 3 &&\n segments[0] === 'dashboard' &&\n segments[1] === 'widgets' &&\n method === 'GET'\n ) {\n return answerWidget(segments[2] ?? '', context, inScope);\n }\n if (segments.length === 1 && segments[0] === 'search' && method === 'GET') {\n return search(url.searchParams, inScope);\n }\n if (segments[0] === 'uploads') {\n return handleUploads(segments, method, readBody);\n }\n if (segments[0] !== 'resources' || segments[1] === undefined) {\n return problem(404, 'Not found.');\n }\n\n const resource = definition.resources.find((candidate) => candidate.id === segments[1]);\n const list = resource !== undefined ? store.get(resource.id) : undefined;\n if (resource === undefined || list === undefined) {\n return problem(404, 'Resource not found.');\n }\n // The items in the context: those that requests read and act on\n const scoped = inScope(resource.id, list);\n\n if (segments.length === 2) {\n if (method === 'GET') {\n if (resource.abilities?.viewAny === false) {\n return problem(403, 'This resource can’t be listed.');\n }\n const query = fromSearchParams(url.searchParams);\n const perPage = query.perPage ?? resource.list?.perPage ?? 20;\n const page = query.page ?? 1;\n const sort = query.sort ?? resource.list?.defaultSort?.split(',');\n const matching = applyQuery(scoped, {\n ...query,\n ...(sort !== undefined ? { sort } : {}),\n });\n if (resource.list?.pagination === 'cursor') {\n // Cursors are opaque to clients: here, the offset of the page.\n const cursor = query.cursor ?? 'o0';\n if (!/^o\\d+$/.test(cursor)) {\n return problem(422, 'The cursor is invalid.', {\n errors: { cursor: ['The cursor is invalid.'] },\n });\n }\n const offset = Number(cursor.slice(1));\n const end = offset + perPage;\n return json(200, {\n data: matching.slice(offset, end).map((item) => present(resource, item)),\n meta: {\n perPage,\n nextCursor: end < matching.length ? `o${String(end)}` : null,\n previousCursor:\n offset - perPage > 0 ? `o${String(offset - perPage)}` : null,\n },\n });\n }\n return json(200, {\n data: matching\n .slice((page - 1) * perPage, page * perPage)\n .map((item) => present(resource, item)),\n meta: {\n page,\n perPage,\n total: matching.length,\n lastPage: Math.max(1, Math.ceil(matching.length / perPage)),\n },\n });\n }\n if (method === 'POST') {\n if (resource.abilities?.create === false) {\n return problem(403, 'Items of this resource can’t be created.');\n }\n const body = writableValues(resource, await readBody());\n const invalid = validationProblem(resource, body, 'create');\n if (invalid !== null) {\n return invalid;\n }\n const { values, problem: unresolved } = resolveValues(resource, body);\n if (unresolved !== null) {\n return unresolved;\n }\n const item = withOwnTransform(\n resource,\n makeItem(resource, { ...values, id: undefined }),\n );\n list.push(item);\n return json(201, { data: present(resource, item) }, etag(item));\n }\n return problem(405, 'Method not allowed.');\n }\n\n if (segments[2] === 'fields' && segments[4] === 'check' && segments.length === 5) {\n if (method !== 'POST') {\n return problem(405, 'Method not allowed.');\n }\n const field = resource.fields.find(\n (candidate) => candidate.name === segments[3] && candidate.check === true,\n );\n if (field === undefined) {\n return problem(404, 'Field not found.');\n }\n const body = await readBody();\n if (typeof body.value !== 'string') {\n return problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: { value: ['The value is required.'] },\n });\n }\n const locale = typeof body.locale === 'string' ? body.locale : null;\n const id =\n typeof body.id === 'string' || typeof body.id === 'number' ? String(body.id) : null;\n const valueOf = (item: Item): unknown => {\n const value = item[field.name];\n return locale !== null && isRecord(value) ? value[locale] : value;\n };\n const taken = (candidate: string) =>\n list.some((item) => item.id !== id && valueOf(item) === candidate);\n const available = !taken(body.value);\n let suggestion: string | null = null;\n for (let index = 2; !available && suggestion === null; index += 1) {\n const candidate = `${body.value}-${String(index)}`;\n suggestion = taken(candidate) ? null : candidate;\n }\n // The mock gives a URL when the field has a fixed prefix\n const prefix =\n typeof field.settings?.prefix === 'string' ? field.settings.prefix : null;\n const response: FieldCheckResponse = {\n available,\n suggestion,\n prefix,\n url: prefix !== null ? `${prefix}${body.value}` : null,\n };\n return json(200, response);\n }\n\n if (segments[2] === 'actions' && segments[3] !== undefined && segments.length === 4) {\n if (method !== 'POST') {\n return problem(405, 'Method not allowed.');\n }\n const actionId = segments[3];\n const action = (resource.actions ?? []).find((candidate) => candidate.id === actionId);\n const body = await readBody();\n if (body.dryRun === true) {\n // A dry run counts what the action would do, and changes nothing.\n // The built-in `delete` answers dry runs, declared or not\n if (action?.dryRun !== true && actionId !== 'delete') {\n return problem(400, 'This action does not support dry runs.');\n }\n const selected = selectItems(scoped, body.selection as Selection | undefined);\n const allowed = selected.filter((item) => allows(item, actionId));\n const result: ActionResult = {\n summary: {\n succeeded: allowed.length,\n failed: 0,\n skipped: selected.length - allowed.length,\n },\n results: selected\n .filter((item) => !allowed.includes(item))\n .slice(0, 20)\n .map((item) => ({ id: item.id, status: 'skipped', reason: 'forbidden' })),\n };\n return json(200, result);\n }\n // A resource with a trash declares its delete undoable, and restores what it deleted.\n const hasTrash = (resource.actions ?? []).some(\n (candidate) => candidate.id === 'delete' && candidate.undoable === true,\n );\n if (actionId === 'restore' && hasTrash) {\n const selection = body.selection as Selection | undefined;\n const ids =\n selection !== undefined && 'ids' in selection && Array.isArray(selection.ids)\n ? selection.ids.map(String)\n : null;\n if (ids === null) {\n return problem(422, 'The selection needs ids.', {\n type: 'urn:panneau:problem:validation',\n errors: { selection: ['The selection needs ids.'] },\n });\n }\n const deleted = trash.get(resource.id) ?? [];\n const restored = deleted.filter((item) => ids.includes(item.id));\n const missing = ids.filter((id) => !restored.some((item) => item.id === id));\n if (ids.length === 1 && missing.length === 1) {\n return problem(404, 'Item not found.');\n }\n trash.set(\n resource.id,\n deleted.filter((item) => !restored.includes(item)),\n );\n store.set(resource.id, [...list, ...restored]);\n const result: ActionResult = {\n summary: { succeeded: restored.length, failed: 0, skipped: missing.length },\n ...(missing.length > 0\n ? {\n results: missing.map((id) => ({\n id,\n status: 'skipped' as const,\n reason: 'not_found',\n })),\n }\n : {}),\n refresh: 'list',\n };\n return json(200, result);\n }\n if (actionId !== 'delete') {\n return problem(404, 'Action not found.');\n }\n const selection = body.selection as Selection | undefined;\n const selected = selectItems(scoped, selection);\n const allowed = selected.filter((item) => allows(item, 'delete'));\n const skipped = selected.filter((item) => !allowed.includes(item));\n // An item that something else uses is skipped, even alone: it isn't an error.\n const inUse = allowed.filter(\n (item) => options.inUse?.({ resource: resource.id, item }) === true,\n );\n const deleted = allowed.filter((item) => !inUse.includes(item));\n // The only item of an item action is an error, not a skipped result\n const ids =\n selection !== undefined && 'ids' in selection && Array.isArray(selection.ids)\n ? selection.ids\n : null;\n if (ids?.length === 1 && skipped.length > 0) {\n return problem(403, 'This item can’t be deleted.');\n }\n store.set(\n resource.id,\n list.filter((item) => !deleted.includes(item)),\n );\n if (hasTrash) {\n trash.set(resource.id, [...(trash.get(resource.id) ?? []), ...deleted]);\n }\n const result: ActionResult = {\n message: `${deleted.length} deleted.`,\n // What was deleted can be put back, up to the limit of the protocol.\n ...(hasTrash && deleted.length > 0 && deleted.length <= UNDO_LIMIT\n ? { undo: { action: 'restore', items: deleted.map((item) => item.id) } }\n : {}),\n summary: {\n succeeded: deleted.length,\n failed: 0,\n skipped: skipped.length + inUse.length,\n },\n ...(skipped.length + inUse.length > 0\n ? {\n results: [\n ...skipped.map((item) => ({\n id: item.id,\n status: 'skipped' as const,\n reason: 'forbidden',\n })),\n ...inUse.map((item) => ({\n id: item.id,\n status: 'skipped' as const,\n reason: 'in_use',\n })),\n ].slice(0, 20),\n }\n : {}),\n refresh: 'list',\n };\n return json(200, result);\n }\n\n if (segments.length === 4 && segments[3] === 'duplicate' && segments[2] !== undefined) {\n const current = scoped.find((item) => item.id === segments[2]);\n if (current === undefined) {\n return problem(404, 'Item not found.');\n }\n if (method !== 'POST') {\n return problem(405, 'Method not allowed.');\n }\n if (!allows(current, 'duplicate')) {\n return problem(403, 'This item can’t be duplicated.');\n }\n // A copy of its values, under an id no item has\n const { id: _id, version: _version, abilities: _abilities, ...values } = current;\n const copy = makeItem(resource, { ...values, id: freshId(resource) });\n list.push(copy);\n return json(201, { data: present(resource, copy) }, etag(copy));\n }\n\n if (segments.length === 4 && segments[3] === 'preview' && segments[2] !== undefined) {\n const current = scoped.find((item) => item.id === segments[2]);\n if (current === undefined) {\n return problem(404, 'Item not found.');\n }\n if (method !== 'POST') {\n return problem(405, 'Method not allowed.');\n }\n const body = await readBody();\n const item: Item = { ...current, ...(isRecord(body) ? body : {}) };\n const url =\n options.previewUrl?.({ resource: resource.id, item }) ?? defaultPreviewUrl(item);\n return json(200, {\n url,\n expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(),\n } satisfies PreviewResponse);\n }\n\n if (segments.length !== 3 || segments[2] === undefined) {\n return problem(404, 'Not found.');\n }\n const id = segments[2];\n const index = scoped.some((item) => item.id === id)\n ? list.findIndex((item) => item.id === id)\n : -1;\n const current = list[index];\n if (current === undefined) {\n return problem(404, 'Item not found.');\n }\n\n if (method === 'GET') {\n if (current.abilities.view !== true) {\n return problem(403, 'This item can’t be viewed.');\n }\n return json(200, { data: present(resource, current) }, etag(current));\n }\n if (method === 'PATCH') {\n if (current.abilities.update !== true) {\n return problem(403, 'This item can’t be updated.');\n }\n const ifMatch = request.headers.get('If-Match');\n if (\n ifMatch !== null &&\n current.version !== null &&\n parseEtag(ifMatch) !== current.version\n ) {\n return problem(412, 'The item was changed by someone else.', {\n type: 'urn:panneau:problem:version-conflict',\n current: present(resource, current),\n });\n }\n const body = writableValues(resource, await readBody());\n const invalid = validationProblem(resource, body, 'update', current);\n if (invalid !== null) {\n return invalid;\n }\n const { values, problem: unresolved } = resolveValues(resource, body);\n if (unresolved !== null) {\n return unresolved;\n }\n const updates = Object.fromEntries(\n Object.entries(values).filter(([key]) => !RESERVED_KEYS.has(key)),\n );\n const updated = withOwnTransform(resource, {\n ...current,\n ...updates,\n version: current.version === null ? null : String(Number(current.version) + 1),\n });\n list[index] = updated;\n return json(200, { data: present(resource, updated) }, etag(updated));\n }\n if (method === 'DELETE') {\n if (current.abilities.delete !== true) {\n return problem(403, 'This item can’t be deleted.');\n }\n list.splice(index, 1);\n return json(204, null);\n }\n return problem(405, 'Method not allowed.');\n };\n\n return {\n fetch: (input, init) => {\n if (input instanceof Request) {\n return handle(input);\n }\n // Relative URLs are accepted, as a browser would resolve them.\n return handle(new Request(new URL(input, 'http://panneau.test'), init));\n },\n items: (resource) => [...(store.get(resource) ?? [])],\n };\n}\n\nexport { createExampleDefinition } from './example';\n"],"mappings":";;;;;;;;;;;;AAmHA,IAAM,gCAAgB,IAAI,IAAI;CAAC;CAAM;CAAW;AAAW,CAAC;AAE5D,SAAS,WAAW,MAAsB;CACtC,OAAO,KAAK,QAAQ,aAAa,cAAc,KAAK,UAAU,WAAW,CAAC,EAAE,EAAE;AAClF;;AAGA,SAAS,kBAAkB,MAAoB;CAC3C,MAAM,OAAO,OAAO,QAAQ,IAAI,CAAC,CAC5B,QAAQ,CAAC,SAAS,CAAC,cAAc,IAAI,GAAG,CAAC,CAAC,CAC1C,KACI,CAAC,KAAK,WACH,OAAO,WAAW,GAAG,EAAE,WAAW,WAAW,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK,CAAC,EAAE,MAChH,CAAC,CACA,KAAK,EAAE;CACZ,MAAM,OAAO,uHAAuH,WAAW,KAAK,EAAE,EAAE,WAAW,KAAK;CACxK,OAAO,gCAAgC,mBAAmB,IAAI;AAClE;;AAGA,S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"sourcesContent":["import {\n CONTEXT_HEADER,\n CONTEXT_PROBLEM_TYPE,\n IDS_FILTER,\n IDS_FILTER_LIMIT,\n ITEM_ACTION_ABILITIES,\n UNDO_LIMIT,\n isBuiltInItemAction,\n} from '../constants';\nimport { type ContextValues, contextBefore, parseContextHeader } from '../context';\nimport { getMediaLibraries } from '../libraries';\nimport { type ListQuery, fromSearchParams, isFilterRange, matchesFilterRange } from '../query';\nimport { type RuleFailure, checkValues } from '../rules';\nimport type { ContextOption, DefinitionInput, ResourceInput } from '../schemas';\nimport type {\n ActionResult,\n EmbedValue,\n FieldCheckResponse,\n Item,\n MediaInfo,\n MediaReference,\n PreviewResponse,\n Problem,\n SearchResponse,\n Selection,\n StoredFile,\n Upload,\n UploadSignResponse,\n} from '../schemas/api';\nimport { SEARCH_MAX_LIMIT, readSearchQuery } from '../search';\nimport { isRecord } from '../values';\nimport { PROBLEM_CONTENT_TYPE } from '../version';\nimport { checkWidgetData, getWidgetResource } from '../widgets';\nimport { type MockAuthOptions, createMockAuth } from './auth';\n\nexport type { MockAuthOptions, MockMail, MockUser } from './auth';\n\ntype Values = Record<string, unknown>;\n\nexport interface MockBackendOptions {\n /** The definition served by `GET /definition`. Its `api.baseUrl` is the prefix of every route. */\n definition: DefinitionInput;\n /** Initial values of the items, per resource id. Items without an `id` get one. */\n items?: Record<string, Values[]>;\n /**\n * The URL that `POST /resources/{resource}/{id}/preview` returns, for the item with the posted\n * values. Defaults to a `data:` URL of a plain page with the item's values.\n */\n previewUrl?: (context: { resource: string; item: Item }) => string;\n /**\n * The value of `GET /embeds?url=` for a URL, or `null` to refuse it with a `422`. Defaults to\n * a video for YouTube and Vimeo URLs, and a link for other web pages.\n */\n embed?: (url: string) => EmbedValue | null;\n /**\n * The current context, when the definition has `context` (decision 0045). The values of the\n * `Panneau-Context` header are checked against the choices of each param: a value that isn't\n * one is a `403` problem.\n */\n context?: MockContextOptions;\n /**\n * Users and a session, for the `panneau` auth mode: the auth routes answer, guests get a `401`\n * on the other routes, and with `auth.emailVerification`, users whose address isn't verified\n * get its `403` problem (decision 0048). Without it, every request is the user's.\n */\n auth?: MockAuthOptions;\n /**\n * The data of `GET /dashboard/widgets/{widget}`, per widget id (decision 0064): the data, a\n * function that returns it for the current context, or a `Response` to answer as is (a `403`,\n * a slow or failing widget). Data that doesn't have the shape of a built-in type is a `500`\n * problem that names the wrong keys, as a backend answers it. Widgets of the dashboard without\n * data, and built-in `stat` and `list` on a resource, are a `404`.\n */\n widgets?: Record<string, MockWidget>;\n /**\n * Whether something else uses an item, so that it can't be deleted: `delete` skips it with\n * the reason `in_use`, and its `undo` leaves it out. Without it, no item is in use.\n */\n inUse?: (context: { resource: string; item: Item }) => boolean;\n}\n\n/** The data of a widget in the mock backend: its data, or what answers it. */\nexport type MockWidget =\n | Response\n | Record<string, unknown>\n | ((\n context: MockWidgetContext,\n ) => Response | Record<string, unknown> | Promise<Response | Record<string, unknown>>);\n\n/** What the function of a widget of the mock backend gets. */\nexport interface MockWidgetContext {\n /** The values of the context of the request. */\n context: ContextValues;\n /** The current items of a resource, in the context. */\n items: (resource: string) => Item[];\n}\n\n/** How the mock backend answers the context of its definition (decision 0045). */\nexport interface MockContextOptions {\n /**\n * Every choice of a param without inline `options`, for the values of the params before it.\n * `GET /context/{name}/options?q=` gives the first 20 whose label matches `q`.\n */\n options?: (name: string, before: ContextValues) => ContextOption[];\n /** Whether an item of a resource is in the context, for lists, items, actions and search. */\n scope?: (resource: string, item: Item, values: ContextValues) => boolean;\n}\n\nexport interface MockBackend {\n /** A `fetch`-compatible function that answers protocol requests. */\n fetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n /** The current items of a resource. */\n items: (resource: string) => Item[];\n}\n\nconst RESERVED_KEYS = new Set(['id', 'version', 'abilities']);\n\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (character) => `&#${character.charCodeAt(0)};`);\n}\n\n/** A plain page with the values of an item, as a `data:` URL, for iframe previews. */\nfunction defaultPreviewUrl(item: Item): string {\n const rows = Object.entries(item)\n .filter(([key]) => !RESERVED_KEYS.has(key))\n .map(\n ([key, value]) =>\n `<dt>${escapeHtml(key)}</dt><dd>${escapeHtml(typeof value === 'string' ? value : JSON.stringify(value))}</dd>`,\n )\n .join('');\n const html = `<!doctype html><meta charset=\"utf-8\"><title>Preview</title><body style=\"font-family:system-ui;margin:2rem\"><h1>Item ${escapeHtml(item.id)}</h1><dl>${rows}</dl></body>`;\n return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;\n}\n\n/** What the mock knows of a URL to embed: a video of YouTube or Vimeo, or a web page. */\nfunction defaultEmbed(url: string): EmbedValue | null {\n if (!URL.canParse(url)) {\n return null;\n }\n const parsed = new URL(url);\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {\n return null;\n }\n const host = parsed.hostname.replace(/^www\\./, '');\n const youtube =\n host === 'youtu.be'\n ? parsed.pathname.slice(1)\n : host.endsWith('youtube.com')\n ? parsed.searchParams.get('v')\n : null;\n if (youtube !== null && youtube !== '') {\n return {\n url,\n type: 'video',\n provider: 'YouTube',\n title: `YouTube video ${youtube}`,\n thumbnailUrl: `https://i.ytimg.com/vi/${youtube}/hqdefault.jpg`,\n html: `<iframe src=\"https://www.youtube.com/embed/${youtube}\" width=\"560\" height=\"315\" allowfullscreen></iframe>`,\n width: 560,\n height: 315,\n };\n }\n if (host === 'vimeo.com') {\n const id = parsed.pathname.split('/').filter(Boolean)[0] ?? '';\n return {\n url,\n type: 'video',\n provider: 'Vimeo',\n title: `Vimeo video ${id}`,\n html: `<iframe src=\"https://player.vimeo.com/video/${id}\" width=\"640\" height=\"360\" allowfullscreen></iframe>`,\n width: 640,\n height: 360,\n };\n }\n return { url, type: 'link', provider: host, title: host };\n}\n\nconst DEFAULT_MESSAGES: Record<string, (failure: RuleFailure) => string> = {\n required: () => 'This field is required.',\n min: (failure) => `This value must be at least ${String(failure.value)}.`,\n max: (failure) => `This value must be at most ${String(failure.value)}.`,\n pattern: () => 'This value has an invalid format.',\n email: () => 'This value must be an email address.',\n url: () => 'This value must be a URL.',\n json: () => 'This value must be valid JSON: an object or an array.',\n in: () => 'This value is not one of the choices.',\n accept: () => 'This file type is not accepted.',\n maxSize: () => 'This file is too large.',\n before: () => 'This date is too late.',\n after: () => 'This date is too early.',\n providers: (failure) =>\n `This embed must come from ${Array.isArray(failure.value) ? failure.value.join(' or ') : 'another provider'}.`,\n crop: (failure) => {\n const ratios = isRecord(failure.value) ? failure.value.ratios : undefined;\n return Array.isArray(ratios) && ratios.length > 0\n ? `Crop this image to ${ratios.join(' or ')}.`\n : 'Crop this image.';\n },\n};\n\nfunction message(failure: RuleFailure): string {\n return failure.message ?? DEFAULT_MESSAGES[failure.rule]?.(failure) ?? 'This value is invalid.';\n}\n\nfunction json(status: number, body: unknown, headers: Record<string, string> = {}): Response {\n return new Response(status === 204 ? null : JSON.stringify(body), {\n status,\n headers: status === 204 ? headers : { 'Content-Type': 'application/json', ...headers },\n });\n}\n\nfunction problem(status: number, title: string, extra: Partial<Problem> = {}): Response {\n const body: Problem = { type: 'about:blank', title, status, ...extra };\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': PROBLEM_CONTENT_TYPE },\n });\n}\n\nfunction etag(item: Item): Record<string, string> {\n return item.version === null ? {} : { ETag: `\"${item.version}\"` };\n}\n\nfunction parseEtag(value: string): string {\n return value.replace(/^W\\//, '').replace(/^\"(.*)\"$/, '$1');\n}\n\nfunction searchableText(value: unknown): string {\n if (typeof value === 'string') {\n return value;\n }\n if (isRecord(value)) {\n return Object.values(value).map(searchableText).join(' ');\n }\n return '';\n}\n\n/** What a value sorts by: the start of a `daterange`, the amount of `money`, or its text. */\nfunction sortValue(value: unknown): unknown {\n if (!isRecord(value)) {\n return value;\n }\n if ('start' in value && 'end' in value) {\n return value.start ?? value.end;\n }\n if ('currency' in value && typeof value.amount === 'number') {\n return value.amount;\n }\n return searchableText(value);\n}\n\nfunction compare(a: unknown, b: unknown): number {\n const left = sortValue(a);\n const right = sortValue(b);\n if (left === right) {\n return 0;\n }\n if (left === undefined || left === null) {\n return 1;\n }\n if (right === undefined || right === null) {\n return -1;\n }\n if (typeof left === 'number' && typeof right === 'number') {\n return left - right;\n }\n return String(left).localeCompare(String(right), undefined, { numeric: true });\n}\n\nfunction applyQuery(items: Item[], query: Pick<ListQuery, 'filter' | 'q' | 'sort'>): Item[] {\n let result = items;\n Object.entries(query.filter ?? {}).forEach(([key, expected]) => {\n // Every list filters on the ids of its items (decision 0069).\n if (key === IDS_FILTER) {\n const ids = (Array.isArray(expected) ? expected : [expected])\n .map(String)\n .slice(0, IDS_FILTER_LIMIT);\n result = result.filter((item) => ids.includes(item.id));\n return;\n }\n if (isFilterRange(expected)) {\n result = result.filter((item) => matchesFilterRange(item[key], expected));\n return;\n }\n const accepted = (Array.isArray(expected) ? expected : [expected]).map(String);\n result = result.filter((item) => {\n // A filter that isn't a value of the item reads its `media`: `filter[type]=image`.\n const value =\n key in item ? item[key] : isRecord(item.media) ? item.media[key] : undefined;\n const values = Array.isArray(value) ? value : [value];\n return values.some((candidate) => accepted.includes(String(candidate)));\n });\n });\n if (query.q !== undefined && query.q !== '') {\n const terms = query.q.toLowerCase();\n result = result.filter((item) =>\n Object.entries(item)\n .filter(([key]) => !RESERVED_KEYS.has(key))\n .some(([, value]) => searchableText(value).toLowerCase().includes(terms)),\n );\n }\n const sort = query.sort ?? [];\n if (sort.length > 0) {\n result = [...result].sort((a, b) => {\n for (const part of sort) {\n const descending = part.startsWith('-');\n const key = descending ? part.slice(1) : part;\n const order = compare(a[key], b[key]);\n if (order !== 0) {\n return descending ? -order : order;\n }\n }\n return 0;\n });\n }\n return result;\n}\n\n/** The type of a media, from its MIME type. */\nfunction mediaType(mime: string | null | undefined): string {\n const family = (mime ?? '').split('/')[0] ?? '';\n if (family === 'image' || family === 'video' || family === 'audio') {\n return family;\n }\n return mime === 'application/pdf' || family === 'text' ? 'document' : 'other';\n}\n\n/** What the mock computes about a stored file: no renditions, ready at once. */\nfunction mediaOf(file: StoredFile): MediaInfo {\n const type = mediaType(file.mime);\n return {\n type,\n mime: file.mime ?? null,\n size: file.size ?? null,\n url: file.url ?? null,\n thumbnailUrl: type === 'image' ? (file.url ?? null) : null,\n status: 'ready',\n };\n}\n\n/**\n * A media item with its own transform (its `transform` field) in its `media`, where references\n * give it to clients (decision 0031).\n */\nfunction withOwnTransform(resource: ResourceInput, item: Item): Item {\n if (resource.kind !== 'media' || !isRecord(item.media)) {\n return item;\n }\n const { transform: _previous, ...media } = item.media;\n return {\n ...item,\n media: isRecord(item.transform) ? { ...media, transform: item.transform } : media,\n };\n}\n\n/**\n * Whether an item allows an action, as clients read its abilities (decision 0040): a built-in item\n * action needs its ability (`delete`, `duplicate`…), and another action its id.\n */\nfunction allows(item: Item, actionId: string): boolean {\n const ability = isBuiltInItemAction(actionId) ? ITEM_ACTION_ABILITIES[actionId] : actionId;\n return item.abilities[ability] === true && item.abilities[actionId] !== false;\n}\n\n/** The names of the fields of a resource whose ability is `false` (decision 0046). */\nfunction fieldsWithout(resource: ResourceInput, ability: 'view' | 'update'): Set<string> {\n return new Set(\n resource.fields\n .filter((field) => field.abilities?.[ability] === false)\n .map((field) => field.name),\n );\n}\n\n/**\n * A body without the values of the fields the user can't see or update, and of the fields that\n * forms leave out (`notInForm`, decision 0071), which are ignored.\n */\nfunction writableValues(resource: ResourceInput, body: Values): Values {\n const ignored = new Set([\n ...fieldsWithout(resource, 'view'),\n ...fieldsWithout(resource, 'update'),\n ...resource.fields.filter((field) => field.notInForm === true).map((field) => field.name),\n ]);\n return Object.fromEntries(Object.entries(body).filter(([key]) => !ignored.has(key)));\n}\n\n/**\n * An in-memory backend that implements the protocol's resource routes: definition, list, show,\n * create, update (with `If-Match`), delete, duplicate and the built-in `delete` action. A resource\n * that declares its `delete` `undoable` has a trash: the result of `delete` says how to undo it,\n * and the built-in `restore` puts the items back (decision 0063). Its items\n * allow every built-in item action (`view`, `update`, `duplicate`, `delete`), unless an item of\n * `items` gives its own `abilities`. It reads abilities as clients do (decision 0046): a resource\n * without `viewAny` answers `403` on its list, one without `create` on creates, an item without\n * `view`, `update` or `delete` on those requests; items leave out the values of fields with\n * `view: false`, and writes ignore those of fields with `update: false`. Values are checked with\n * the portable rules. Used to test the conformance kit, and to develop frontends without a real\n * backend.\n */\nexport function createMockBackend(options: MockBackendOptions): MockBackend {\n const { definition, items = {} } = options;\n const auth = options.auth !== undefined ? createMockAuth(options.auth, definition.auth) : null;\n const store = new Map<string, Item[]>();\n // The deleted items of the resources whose `delete` is undoable: their trash (decision 0063).\n const trash = new Map<string, Item[]>();\n let nextId = 1;\n\n const abilitiesFor = (resource: ResourceInput) =>\n Object.fromEntries([\n ['view', true],\n ['update', true],\n ['duplicate', true],\n ['delete', true],\n ...(resource.actions ?? []).map((action) => [action.id, true]),\n ]);\n\n // An id that no item of the resource has, also among the items it started with\n const freshId = (resource: ResourceInput): string => {\n const items = store.get(resource.id) ?? [];\n let id = String(nextId++);\n while (items.some((item) => item.id === id)) {\n id = String(nextId++);\n }\n return id;\n };\n\n const makeItem = (resource: ResourceInput, values: Values): Item => {\n const id =\n typeof values.id === 'string' || typeof values.id === 'number'\n ? String(values.id)\n : freshId(resource);\n const rest = Object.fromEntries(\n Object.entries(values).filter(([key]) => !RESERVED_KEYS.has(key)),\n );\n const own = isRecord(values.abilities) ? (values.abilities as Record<string, boolean>) : {};\n return { ...rest, id, version: '1', abilities: { ...abilitiesFor(resource), ...own } };\n };\n\n // What the user gets of an item: without the values of the fields they can't see.\n const present = (resource: ResourceInput, item: Item): Item => {\n const hidden = fieldsWithout(resource, 'view');\n return hidden.size === 0\n ? item\n : (Object.fromEntries(\n Object.entries(item).filter(([key]) => !hidden.has(key)),\n ) as Item);\n };\n\n definition.resources.forEach((resource) => {\n store.set(\n resource.id,\n (items[resource.id] ?? []).map((values) => makeItem(resource, values)),\n );\n });\n\n const basePath = new URL(definition.api.baseUrl, 'http://panneau.test').pathname.replace(\n /\\/$/,\n '',\n );\n\n const validationProblem = (\n resource: ResourceInput,\n values: Values,\n mode: 'create' | 'update',\n item?: Item,\n ) => {\n // A partial update reads the conditions with the item's values (decision 0043).\n const failures = checkValues(resource.fields, values, {\n mode,\n partial: mode === 'update',\n locales: definition.locales,\n ...(item !== undefined ? { item } : {}),\n });\n const paths = Object.keys(failures);\n if (paths.length === 0) {\n return null;\n }\n return problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: Object.fromEntries(\n paths.map((path) => [path, (failures[path] ?? []).map(message)]),\n ),\n });\n };\n\n const selectItems = (list: Item[], selection: Selection | undefined): Item[] => {\n if (selection === undefined) {\n return [];\n }\n if ('ids' in selection) {\n const ids = selection.ids as string[];\n return list.filter((item) => ids.includes(item.id));\n }\n const except = selection.except ?? [];\n const { filter, q } = selection.query;\n const query: Pick<ListQuery, 'filter' | 'q'> = {};\n if (filter !== undefined) {\n query.filter = filter as NonNullable<ListQuery['filter']>;\n }\n if (q !== undefined) {\n query.q = q;\n }\n return applyQuery(list, query).filter((item) => !except.includes(item.id));\n };\n\n // Direct uploads: the open uploads by id, with their key. The mock signs fake URLs, and\n // trusts the client when it completes an upload.\n const uploads = new Map<string, Upload>();\n let nextUpload = 1;\n\n const handleUploads = async (\n segments: string[],\n method: string,\n readBody: () => Promise<Values>,\n ): Promise<Response> => {\n if (definition.uploads?.mode !== 'presigned') {\n return problem(404, 'Not found.');\n }\n if (method !== 'POST') {\n return problem(405, 'Method not allowed.');\n }\n if (segments.length === 2 && segments[1] === 'sign') {\n const body = await readBody();\n const opens =\n body.uploadId === undefined && (body.method === 'POST' || body.method === 'PUT');\n if (opens) {\n const id = `upl_${nextUpload++}`;\n const upload: Upload = { id, key: `uploads/${id}` };\n uploads.set(id, upload);\n const response: UploadSignResponse = {\n url: `https://storage.test/${upload.key}?signature=mock`,\n key: upload.key,\n upload: id,\n };\n return json(200, response);\n }\n const upload = [...uploads.values()].find((candidate) => candidate.key === body.key);\n if (upload === undefined) {\n return problem(404, 'Upload not found.');\n }\n return json(200, { url: `https://storage.test/${upload.key}?signature=mock` });\n }\n if (segments.length === 3 && segments[2] === 'complete' && segments[1] !== undefined) {\n const upload = uploads.get(segments[1]);\n if (upload === undefined) {\n return problem(404, 'Upload not found.');\n }\n const { name } = await readBody();\n if (typeof name === 'string') {\n upload.name = name;\n }\n return json(200, { data: upload });\n }\n return problem(404, 'Not found.');\n };\n\n // The values of `file` fields at the top of a resource: an upload becomes a stored file, and\n // a stored file or null is kept. Returns the paths of uploads that don't exist.\n const resolveFiles = (\n resource: ResourceInput,\n values: Values,\n ): { values: Values; missing: string[] } => {\n const missing: string[] = [];\n const resolved = { ...values };\n const toFile = (value: unknown, path: string): unknown => {\n if (!isRecord(value) || typeof value.upload !== 'string') {\n return value;\n }\n const upload = uploads.get(value.upload);\n if (upload === undefined) {\n missing.push(path);\n return value;\n }\n const file: StoredFile = {\n name: upload.name ?? (typeof value.name === 'string' ? value.name : upload.id),\n url: `https://storage.test/${upload.key ?? upload.id}`,\n mime: upload.mime ?? (typeof value.mime === 'string' ? value.mime : null),\n size: upload.size ?? (typeof value.size === 'number' ? value.size : null),\n };\n return file;\n };\n resource.fields\n .filter((field) => field.type === 'file' && field.name in values)\n .forEach((field) => {\n const value = values[field.name];\n resolved[field.name] = Array.isArray(value)\n ? value.map((entry, index) => toFile(entry, `${field.name}.${String(index)}`))\n : toFile(value, field.name);\n });\n return { values: resolved, missing };\n };\n\n const missingMedia = (paths: Record<string, string>) =>\n problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: Object.fromEntries(\n Object.entries(paths).map(([path, message]) => [path, [message]]),\n ),\n });\n\n const missingUploads = (paths: string[]) =>\n problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: Object.fromEntries(\n paths.map((path) => [path, ['This upload does not exist.']]),\n ),\n });\n\n // The values of `media` and `image` fields at the top of a resource: an id, or\n // `{ id, resource, transform }`, becomes a reference to a media of one of its libraries. A\n // field that allows several libraries needs the library of each media (decision 0027).\n // Returns the problems by path.\n const resolveMedia = (\n resource: ResourceInput,\n values: Values,\n ): { values: Values; missing: Record<string, string> } => {\n const missing: Record<string, string> = {};\n const resolved = { ...values };\n resource.fields\n .filter(\n (field) =>\n (field.type === 'media' || field.type === 'image') && field.name in values,\n )\n .forEach((field) => {\n const allowed = getMediaLibraries(definition, field);\n const toReference = (value: unknown, path: string): unknown => {\n const id = isRecord(value) ? value.id : value;\n if (typeof id !== 'string' && typeof id !== 'number') {\n return value;\n }\n const named =\n isRecord(value) && typeof value.resource === 'string'\n ? value.resource\n : undefined;\n if (named === undefined && allowed.length > 1) {\n missing[path] = 'This field allows several libraries: name the library.';\n return value;\n }\n const libraryId = named ?? allowed[0];\n const library = definition.resources.find(\n (candidate) => candidate.id === libraryId && allowed.includes(candidate.id),\n );\n const media = (store.get(library?.id ?? '') ?? []).find(\n (candidate) => candidate.id === String(id),\n );\n if (media === undefined || library === undefined) {\n missing[path] = 'This media does not exist.';\n return value;\n }\n const title = media[library.itemTitle ?? 'name'];\n const reference: MediaReference = {\n id: media.id,\n ...(allowed.length > 1 ? { resource: library.id } : {}),\n ...(typeof title === 'string' ? { label: title } : {}),\n ...(isRecord(media.media) ? { media: media.media as MediaInfo } : {}),\n ...(isRecord(value) && isRecord(value.transform)\n ? { transform: value.transform }\n : {}),\n };\n return reference;\n };\n const value = values[field.name];\n resolved[field.name] = Array.isArray(value)\n ? value.map((entry, index) =>\n toReference(entry, `${field.name}.${String(index)}`),\n )\n : toReference(value, field.name);\n });\n return { values: resolved, missing };\n };\n\n // Resolves the files and media of the values, and computes the `media` of a media item from\n // its file. The client never sets `media`.\n const resolveValues = (\n resource: ResourceInput,\n body: Values,\n ): { values: Values; problem: Response | null } => {\n const sent = { ...body };\n if (resource.kind === 'media') {\n delete sent.media;\n }\n const files = resolveFiles(resource, sent);\n if (files.missing.length > 0) {\n return { values: body, problem: missingUploads(files.missing) };\n }\n const media = resolveMedia(resource, files.values);\n if (Object.keys(media.missing).length > 0) {\n return { values: body, problem: missingMedia(media.missing) };\n }\n const values = media.values;\n if (resource.kind === 'media' && isRecord(values.file)) {\n values.media = mediaOf(values.file as StoredFile);\n }\n return { values, problem: null };\n };\n\n // The global search (decision 0029): the searchable resources asked for, `limit` items each\n // (5 by default), 20 in all, from 2 characters.\n const search = (\n params: URLSearchParams,\n inScope: (resource: string, list: Item[]) => Item[],\n ): Response => {\n const read = readSearchQuery(params, definition);\n if (read.errors !== undefined) {\n return problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: read.errors,\n });\n }\n const { q, limit, resources } = read.query;\n let left = SEARCH_MAX_LIMIT;\n const data: SearchResponse['data'] = resources.flatMap((id) => {\n if (left === 0) {\n return [];\n }\n const searched = definition.resources.find((candidate) => candidate.id === id);\n if (searched === undefined || searched.abilities?.viewAny === false) {\n return [];\n }\n const found = applyQuery(inScope(id, store.get(id) ?? []), { q });\n const items = found\n .slice(0, Math.min(limit, left))\n .map((item) => present(searched, item));\n left -= items.length;\n return items.length > 0 ? [{ resource: id, items, total: found.length }] : [];\n });\n return json(200, { data } satisfies SearchResponse);\n };\n\n const params = definition.context?.params ?? [];\n const names = params.map(({ name }) => name);\n const choicesOf = (name: string, values: ContextValues): ContextOption[] => {\n const param = params.find((candidate) => candidate.name === name);\n return (\n param?.options ??\n options.context?.options?.(name, contextBefore(values, names, name)) ??\n []\n );\n };\n const refused = (name: string) =>\n problem(403, 'This value of the context can’t be used.', {\n type: CONTEXT_PROBLEM_TYPE,\n param: name,\n });\n /**\n * The values of the header that the definition declares, each one checked against its\n * choices, in order: a value that isn't one is a `403` problem with its `param`. A `fixed`\n * param has the value of the definition, as a backend would take it from the request: another\n * value in the header is refused.\n */\n const readContext = (header: string | null): ContextValues | Response => {\n const sent = parseContextHeader(header);\n const values: Record<string, string> = {};\n for (const param of params) {\n const { name } = param;\n const value = sent[name];\n if (param.fixed === true && typeof param.value === 'string') {\n if (value !== undefined && value !== param.value) {\n return refused(name);\n }\n values[name] = param.value;\n continue;\n }\n if (value === undefined) {\n continue;\n }\n if (!choicesOf(name, values).some((choice) => choice.value === value)) {\n return refused(name);\n }\n values[name] = value;\n }\n return values;\n };\n /** The definition for the values of the context: the `value` and `valueLabel` of each param. */\n // A widget of the dashboard with data of its own (decision 0064)\n const answerWidget = async (\n id: string,\n values: ContextValues,\n inScope: (resource: string, list: Item[]) => Item[],\n ): Promise<Response> => {\n const widget = definitionFor(values).dashboard?.widgets.find(\n (candidate) => candidate.id === id,\n );\n const data = options.widgets?.[id];\n if (widget === undefined || getWidgetResource(widget) !== null || data === undefined) {\n return problem(404, 'Widget not found.');\n }\n const answer =\n typeof data === 'function'\n ? await data({\n context: values,\n items: (resource) => inScope(resource, store.get(resource) ?? []),\n })\n : data;\n if (answer instanceof Response) {\n return answer;\n }\n const wrong = checkWidgetData(widget.type, answer);\n return wrong.length === 0\n ? json(200, answer)\n : problem(500, `The data of the widget doesn't have the shape of \\`${widget.type}\\`.`, {\n detail: `Wrong keys: ${wrong.map((key) => (key === '' ? '(the data)' : key)).join(', ')}.`,\n });\n };\n\n const definitionFor = (values: ContextValues): DefinitionInput =>\n definition.context === undefined\n ? definition\n : {\n ...definition,\n context: {\n ...definition.context,\n params: params.map((param) => {\n if (param.fixed === true) {\n return param;\n }\n const value = values[param.name] ?? null;\n const label =\n value !== null\n ? choicesOf(param.name, values).find(\n (choice) => choice.value === value,\n )?.label\n : undefined;\n return { ...param, value, valueLabel: label ?? null };\n }),\n },\n };\n\n const handle = async (request: Request): Promise<Response> => {\n const response = await answer(request);\n if (definition.context !== undefined) {\n response.headers.set('Vary', CONTEXT_HEADER);\n }\n return response;\n };\n\n const answer = async (request: Request): Promise<Response> => {\n const url = new URL(request.url, 'http://panneau.test');\n if (!url.pathname.startsWith(basePath)) {\n return problem(404, 'Not found.');\n }\n const segments = url.pathname\n .slice(basePath.length)\n .split('/')\n .filter((segment) => segment !== '')\n .map(decodeURIComponent);\n const method = request.method.toUpperCase();\n const readBody = async (): Promise<Values> => {\n const body: unknown = await request.json().catch(() => null);\n return isRecord(body) ? body : {};\n };\n\n if (auth !== null) {\n if (segments[0] === 'auth') {\n return auth.answer(segments.slice(1), method, readBody, url);\n }\n const account =\n segments[0] === 'account'\n ? auth.account(segments.slice(1), method, readBody)\n : null;\n if (account !== null) {\n return account;\n }\n const refused = auth.refuse();\n if (refused !== null) {\n return refused;\n }\n }\n\n const context = readContext(request.headers.get(CONTEXT_HEADER));\n if (context instanceof Response) {\n return context;\n }\n const inScope = (resource: string, list: Item[]): Item[] => {\n const scope = options.context?.scope;\n return scope !== undefined\n ? list.filter((item) => scope(resource, item, context))\n : list;\n };\n\n if (segments.length === 1 && segments[0] === 'definition' && method === 'GET') {\n const built = definitionFor(context);\n return json(200, auth !== null ? { ...built, user: auth.user() } : built);\n }\n if (\n segments.length === 3 &&\n segments[0] === 'context' &&\n segments[2] === 'options' &&\n method === 'GET'\n ) {\n const name = segments[1] ?? '';\n if (!names.includes(name)) {\n return problem(404, 'The context has no such param.');\n }\n const q = (url.searchParams.get('q') ?? '').trim().toLocaleLowerCase();\n const data = choicesOf(name, context)\n .filter((choice) => choice.label.toLocaleLowerCase().includes(q))\n .slice(0, 20);\n return json(200, { data });\n }\n if (segments.length === 1 && segments[0] === 'embeds' && method === 'GET') {\n const url = new URL(request.url, 'http://panneau.test').searchParams.get('url') ?? '';\n const embed = url === '' ? null : (options.embed ?? defaultEmbed)(url);\n return embed !== null\n ? json(200, { data: embed })\n : problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: { url: ['This URL can’t be embedded.'] },\n });\n }\n if (\n segments.length === 3 &&\n segments[0] === 'dashboard' &&\n segments[1] === 'widgets' &&\n method === 'GET'\n ) {\n return answerWidget(segments[2] ?? '', context, inScope);\n }\n if (segments.length === 1 && segments[0] === 'search' && method === 'GET') {\n return search(url.searchParams, inScope);\n }\n if (segments[0] === 'uploads') {\n return handleUploads(segments, method, readBody);\n }\n if (segments[0] !== 'resources' || segments[1] === undefined) {\n return problem(404, 'Not found.');\n }\n\n const resource = definition.resources.find((candidate) => candidate.id === segments[1]);\n const list = resource !== undefined ? store.get(resource.id) : undefined;\n if (resource === undefined || list === undefined) {\n return problem(404, 'Resource not found.');\n }\n // The items in the context: those that requests read and act on\n const scoped = inScope(resource.id, list);\n\n if (segments.length === 2) {\n if (method === 'GET') {\n if (resource.abilities?.viewAny === false) {\n return problem(403, 'This resource can’t be listed.');\n }\n const query = fromSearchParams(url.searchParams);\n const perPage = query.perPage ?? resource.list?.perPage ?? 20;\n const page = query.page ?? 1;\n const sort = query.sort ?? resource.list?.defaultSort?.split(',');\n const matching = applyQuery(scoped, {\n ...query,\n ...(sort !== undefined ? { sort } : {}),\n });\n if (resource.list?.pagination === 'cursor') {\n // Cursors are opaque to clients: here, the offset of the page.\n const cursor = query.cursor ?? 'o0';\n if (!/^o\\d+$/.test(cursor)) {\n return problem(422, 'The cursor is invalid.', {\n errors: { cursor: ['The cursor is invalid.'] },\n });\n }\n const offset = Number(cursor.slice(1));\n const end = offset + perPage;\n return json(200, {\n data: matching.slice(offset, end).map((item) => present(resource, item)),\n meta: {\n perPage,\n nextCursor: end < matching.length ? `o${String(end)}` : null,\n previousCursor:\n offset - perPage > 0 ? `o${String(offset - perPage)}` : null,\n },\n });\n }\n return json(200, {\n data: matching\n .slice((page - 1) * perPage, page * perPage)\n .map((item) => present(resource, item)),\n meta: {\n page,\n perPage,\n total: matching.length,\n lastPage: Math.max(1, Math.ceil(matching.length / perPage)),\n },\n });\n }\n if (method === 'POST') {\n if (resource.abilities?.create === false) {\n return problem(403, 'Items of this resource can’t be created.');\n }\n const body = writableValues(resource, await readBody());\n const invalid = validationProblem(resource, body, 'create');\n if (invalid !== null) {\n return invalid;\n }\n const { values, problem: unresolved } = resolveValues(resource, body);\n if (unresolved !== null) {\n return unresolved;\n }\n const item = withOwnTransform(\n resource,\n makeItem(resource, { ...values, id: undefined }),\n );\n list.push(item);\n return json(201, { data: present(resource, item) }, etag(item));\n }\n return problem(405, 'Method not allowed.');\n }\n\n if (segments[2] === 'fields' && segments[4] === 'check' && segments.length === 5) {\n if (method !== 'POST') {\n return problem(405, 'Method not allowed.');\n }\n const field = resource.fields.find(\n (candidate) => candidate.name === segments[3] && candidate.check === true,\n );\n if (field === undefined) {\n return problem(404, 'Field not found.');\n }\n const body = await readBody();\n if (typeof body.value !== 'string') {\n return problem(422, 'The given data was invalid.', {\n type: 'urn:panneau:problem:validation',\n errors: { value: ['The value is required.'] },\n });\n }\n const locale = typeof body.locale === 'string' ? body.locale : null;\n const id =\n typeof body.id === 'string' || typeof body.id === 'number' ? String(body.id) : null;\n const valueOf = (item: Item): unknown => {\n const value = item[field.name];\n return locale !== null && isRecord(value) ? value[locale] : value;\n };\n const taken = (candidate: string) =>\n list.some((item) => item.id !== id && valueOf(item) === candidate);\n const available = !taken(body.value);\n let suggestion: string | null = null;\n for (let index = 2; !available && suggestion === null; index += 1) {\n const candidate = `${body.value}-${String(index)}`;\n suggestion = taken(candidate) ? null : candidate;\n }\n // The mock gives a URL when the field has a fixed prefix\n const prefix =\n typeof field.settings?.prefix === 'string' ? field.settings.prefix : null;\n const response: FieldCheckResponse = {\n available,\n suggestion,\n prefix,\n url: prefix !== null ? `${prefix}${body.value}` : null,\n };\n return json(200, response);\n }\n\n if (segments[2] === 'actions' && segments[3] !== undefined && segments.length === 4) {\n if (method !== 'POST') {\n return problem(405, 'Method not allowed.');\n }\n const actionId = segments[3];\n const action = (resource.actions ?? []).find((candidate) => candidate.id === actionId);\n const body = await readBody();\n if (body.dryRun === true) {\n // A dry run counts what the action would do, and changes nothing.\n // The built-in `delete` answers dry runs, declared or not\n if (action?.dryRun !== true && actionId !== 'delete') {\n return problem(400, 'This action does not support dry runs.');\n }\n const selected = selectItems(scoped, body.selection as Selection | undefined);\n const allowed = selected.filter((item) => allows(item, actionId));\n const result: ActionResult = {\n summary: {\n succeeded: allowed.length,\n failed: 0,\n skipped: selected.length - allowed.length,\n },\n results: selected\n .filter((item) => !allowed.includes(item))\n .slice(0, 20)\n .map((item) => ({ id: item.id, status: 'skipped', reason: 'forbidden' })),\n };\n return json(200, result);\n }\n // A resource with a trash declares its delete undoable, and restores what it deleted.\n const hasTrash = (resource.actions ?? []).some(\n (candidate) => candidate.id === 'delete' && candidate.undoable === true,\n );\n if (actionId === 'restore' && hasTrash) {\n const selection = body.selection as Selection | undefined;\n const ids =\n selection !== undefined && 'ids' in selection && Array.isArray(selection.ids)\n ? selection.ids.map(String)\n : null;\n if (ids === null) {\n return problem(422, 'The selection needs ids.', {\n type: 'urn:panneau:problem:validation',\n errors: { selection: ['The selection needs ids.'] },\n });\n }\n const deleted = trash.get(resource.id) ?? [];\n const restored = deleted.filter((item) => ids.includes(item.id));\n const missing = ids.filter((id) => !restored.some((item) => item.id === id));\n if (ids.length === 1 && missing.length === 1) {\n return problem(404, 'Item not found.');\n }\n trash.set(\n resource.id,\n deleted.filter((item) => !restored.includes(item)),\n );\n store.set(resource.id, [...list, ...restored]);\n const result: ActionResult = {\n summary: { succeeded: restored.length, failed: 0, skipped: missing.length },\n ...(missing.length > 0\n ? {\n results: missing.map((id) => ({\n id,\n status: 'skipped' as const,\n reason: 'not_found',\n })),\n }\n : {}),\n refresh: 'list',\n };\n return json(200, result);\n }\n if (actionId !== 'delete') {\n return problem(404, 'Action not found.');\n }\n const selection = body.selection as Selection | undefined;\n const selected = selectItems(scoped, selection);\n const allowed = selected.filter((item) => allows(item, 'delete'));\n const skipped = selected.filter((item) => !allowed.includes(item));\n // An item that something else uses is skipped, even alone: it isn't an error.\n const inUse = allowed.filter(\n (item) => options.inUse?.({ resource: resource.id, item }) === true,\n );\n const deleted = allowed.filter((item) => !inUse.includes(item));\n // The only item of an item action is an error, not a skipped result\n const ids =\n selection !== undefined && 'ids' in selection && Array.isArray(selection.ids)\n ? selection.ids\n : null;\n if (ids?.length === 1 && skipped.length > 0) {\n return problem(403, 'This item can’t be deleted.');\n }\n store.set(\n resource.id,\n list.filter((item) => !deleted.includes(item)),\n );\n if (hasTrash) {\n trash.set(resource.id, [...(trash.get(resource.id) ?? []), ...deleted]);\n }\n const result: ActionResult = {\n message: `${deleted.length} deleted.`,\n // What was deleted can be put back, up to the limit of the protocol.\n ...(hasTrash && deleted.length > 0 && deleted.length <= UNDO_LIMIT\n ? { undo: { action: 'restore', items: deleted.map((item) => item.id) } }\n : {}),\n summary: {\n succeeded: deleted.length,\n failed: 0,\n skipped: skipped.length + inUse.length,\n },\n ...(skipped.length + inUse.length > 0\n ? {\n results: [\n ...skipped.map((item) => ({\n id: item.id,\n status: 'skipped' as const,\n reason: 'forbidden',\n })),\n ...inUse.map((item) => ({\n id: item.id,\n status: 'skipped' as const,\n reason: 'in_use',\n })),\n ].slice(0, 20),\n }\n : {}),\n refresh: 'list',\n };\n return json(200, result);\n }\n\n if (segments.length === 4 && segments[3] === 'duplicate' && segments[2] !== undefined) {\n const current = scoped.find((item) => item.id === segments[2]);\n if (current === undefined) {\n return problem(404, 'Item not found.');\n }\n if (method !== 'POST') {\n return problem(405, 'Method not allowed.');\n }\n if (!allows(current, 'duplicate')) {\n return problem(403, 'This item can’t be duplicated.');\n }\n // A copy of its values, under an id no item has\n const { id: _id, version: _version, abilities: _abilities, ...values } = current;\n const copy = makeItem(resource, { ...values, id: freshId(resource) });\n list.push(copy);\n return json(201, { data: present(resource, copy) }, etag(copy));\n }\n\n if (segments.length === 4 && segments[3] === 'preview' && segments[2] !== undefined) {\n const current = scoped.find((item) => item.id === segments[2]);\n if (current === undefined) {\n return problem(404, 'Item not found.');\n }\n if (method !== 'POST') {\n return problem(405, 'Method not allowed.');\n }\n const body = await readBody();\n const item: Item = { ...current, ...(isRecord(body) ? body : {}) };\n const url =\n options.previewUrl?.({ resource: resource.id, item }) ?? defaultPreviewUrl(item);\n return json(200, {\n url,\n expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(),\n } satisfies PreviewResponse);\n }\n\n if (segments.length !== 3 || segments[2] === undefined) {\n return problem(404, 'Not found.');\n }\n const id = segments[2];\n const index = scoped.some((item) => item.id === id)\n ? list.findIndex((item) => item.id === id)\n : -1;\n const current = list[index];\n if (current === undefined) {\n return problem(404, 'Item not found.');\n }\n\n if (method === 'GET') {\n if (current.abilities.view !== true) {\n return problem(403, 'This item can’t be viewed.');\n }\n return json(200, { data: present(resource, current) }, etag(current));\n }\n if (method === 'PATCH') {\n if (current.abilities.update !== true) {\n return problem(403, 'This item can’t be updated.');\n }\n const ifMatch = request.headers.get('If-Match');\n if (\n ifMatch !== null &&\n current.version !== null &&\n parseEtag(ifMatch) !== current.version\n ) {\n return problem(412, 'The item was changed by someone else.', {\n type: 'urn:panneau:problem:version-conflict',\n current: present(resource, current),\n });\n }\n const body = writableValues(resource, await readBody());\n const invalid = validationProblem(resource, body, 'update', current);\n if (invalid !== null) {\n return invalid;\n }\n const { values, problem: unresolved } = resolveValues(resource, body);\n if (unresolved !== null) {\n return unresolved;\n }\n const updates = Object.fromEntries(\n Object.entries(values).filter(([key]) => !RESERVED_KEYS.has(key)),\n );\n const updated = withOwnTransform(resource, {\n ...current,\n ...updates,\n version: current.version === null ? null : String(Number(current.version) + 1),\n });\n list[index] = updated;\n return json(200, { data: present(resource, updated) }, etag(updated));\n }\n if (method === 'DELETE') {\n if (current.abilities.delete !== true) {\n return problem(403, 'This item can’t be deleted.');\n }\n list.splice(index, 1);\n return json(204, null);\n }\n return problem(405, 'Method not allowed.');\n };\n\n return {\n fetch: (input, init) => {\n if (input instanceof Request) {\n return handle(input);\n }\n // Relative URLs are accepted, as a browser would resolve them.\n return handle(new Request(new URL(input, 'http://panneau.test'), init));\n },\n items: (resource) => [...(store.get(resource) ?? [])],\n };\n}\n\nexport { createExampleDefinition } from './example';\n"],"mappings":";;;;;;;;;;;;AAmHA,IAAM,gCAAgB,IAAI,IAAI;CAAC;CAAM;CAAW;AAAW,CAAC;AAE5D,SAAS,WAAW,MAAsB;CACtC,OAAO,KAAK,QAAQ,aAAa,cAAc,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O,EAAE,GAAG,KAAK,OAAO,CAAC;EACxE;EACA,IAAI,WAAW,UAAU;GACrB,IAAI,QAAQ,UAAU,WAAW,MAC7B,OAAO,QAAQ,KAAK,6BAA6B;GAErD,KAAK,OAAO,OAAO,CAAC;GACpB,OAAO,KAAK,KAAK,IAAI;EACzB;EACA,OAAO,QAAQ,KAAK,qBAAqB;CAC7C;CAEA,OAAO;EACH,QAAQ,OAAO,SAAS;GACpB,IAAI,iBAAiB,SACjB,OAAO,OAAO,KAAK;GAGvB,OAAO,OAAO,IAAI,QAAQ,IAAI,IAAI,OAAO,qBAAqB,GAAG,IAAI,CAAC;EAC1E;EACA,QAAQ,aAAa,CAAC,GAAI,MAAM,IAAI,QAAQ,KAAK,CAAC,CAAE;CACxD;AACJ"}
|
package/dist/rules.d.ts
CHANGED
|
@@ -35,7 +35,8 @@ export declare function checkRules(rules: Rule[], value: unknown, root?: Record<
|
|
|
35
35
|
/**
|
|
36
36
|
* Checks form values against the portable rules of their fields. Returns the failures keyed by
|
|
37
37
|
* the dot path of the value (`title.fr`, `blocks.2.image`), the same keys as validation errors.
|
|
38
|
-
* Hidden and read-only fields
|
|
38
|
+
* Hidden and read-only fields, and fields that forms leave out (`notInForm`), are skipped. Rules
|
|
39
|
+
* this version doesn't know are ignored.
|
|
39
40
|
*/
|
|
40
41
|
export declare function checkValues(fields: Field[], values: Record<string, unknown>, options?: CheckOptions): Record<string, RuleFailure[]>;
|
|
41
42
|
//# sourceMappingURL=rules.d.ts.map
|
package/dist/rules.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../src/rules.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAInD,2CAA2C;AAC3C,MAAM,WAAW,WAAW;IACxB,IAAI,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAA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,EACb,KAAK,EAAE,OAAO,EACd,IAAI,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,EAClC,IAAI,CAAC,EAAE,YAAY,CAAC,MAAM,CAAC,GAC5B,WAAW,EAAE,CA8Gf;AAuOD;;;;;GAKG;AACH,wBAAgB,WAAW,CACvB,MAAM,EAAE,KAAK,EAAE,EACf,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,OAAO,GAAE,YAAiB,GAC3B,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,CAAC,CAQ/B"}
|
package/dist/rules.js
CHANGED
|
@@ -328,7 +328,7 @@ function checkFieldValue(field, value, path, context) {
|
|
|
328
328
|
}
|
|
329
329
|
function checkFields(fields, values, prefix, context) {
|
|
330
330
|
fields.forEach((field) => {
|
|
331
|
-
if (field.readOnly === true) return;
|
|
331
|
+
if (field.readOnly === true || field.notInForm === true) return;
|
|
332
332
|
if (context.mode === "create" && field.updateOnly === true) return;
|
|
333
333
|
if (context.mode === "update" && field.createOnly === true) return;
|
|
334
334
|
if (field.visibleWhen !== void 0 && !evaluateCondition(field.visibleWhen, prefix === "" ? context.root : values)) return;
|
|
@@ -339,7 +339,8 @@ function checkFields(fields, values, prefix, context) {
|
|
|
339
339
|
/**
|
|
340
340
|
* Checks form values against the portable rules of their fields. Returns the failures keyed by
|
|
341
341
|
* the dot path of the value (`title.fr`, `blocks.2.image`), the same keys as validation errors.
|
|
342
|
-
* Hidden and read-only fields
|
|
342
|
+
* Hidden and read-only fields, and fields that forms leave out (`notInForm`), are skipped. Rules
|
|
343
|
+
* this version doesn't know are ignored.
|
|
343
344
|
*/
|
|
344
345
|
function checkValues(fields, values, options = {}) {
|
|
345
346
|
const root = options.partial === true && options.item !== void 0 ? {
|
package/dist/rules.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.js","names":[],"sources":["../src/rules.ts"],"sourcesContent":["import { getAddressRequiredParts, isPostalCode } from './addresses';\nimport { getNestedShape } from './compound';\nimport { evaluateCondition } from './conditions';\nimport { PORTABLE_RULES } from './constants';\nimport { isCurrencyCode } from './currencies';\nimport { getLinkTypes } from './links';\nimport type { Field, Rule } from './schemas/field';\nimport { matchesRatio, renderedCropSize } from './transforms';\nimport { getValue, isFilled, isRecord } from './values';\n\n/** A rule that a value doesn't satisfy. */\nexport interface RuleFailure {\n rule: string;\n /**\n * The rule's parameter (`max: 120` gives `120`). For `daterange`, what fails: `start` or `end`\n * (a bound missing where the range isn't open), or `order` (the end is before the start).\n */\n value?: unknown;\n /** The message set on the rule, if any. */\n message?: string;\n}\n\nexport interface CheckOptions {\n /**\n * Locales a `required` localized field must be filled in. Without it, one filled locale is\n * enough.\n */\n locales?: string[];\n /** `create` skips `updateOnly` fields; `update` skips `createOnly` fields. */\n mode?: 'create' | 'update';\n /** Only check the fields present in the values (partial updates). */\n partial?: boolean;\n /**\n * The values of the item being updated. With `partial`, conditions (`visibleWhen`) and rules\n * that read other fields read them for the fields that aren't in the values: a field shown\n * when `status` is `published`, sent alone, is checked on a published item (decision 0043).\n */\n item?: Record<string, unknown>;\n}\n\ninterface Context extends CheckOptions {\n /** The whole form, for `visibleWhen` and date rules that reference other fields. */\n root: Record<string, unknown>;\n failures: Record<string, RuleFailure[]>;\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n/** An international phone number in E.164: `+`, then 7 to 15 digits, without a leading zero. */\nconst TEL = /^\\+[1-9]\\d{6,14}$/;\n/** The same number, with an optional extension after `;ext=` (RFC 3966): `+15145550199;ext=123`. */\nconst TEL_EXTENSION = /^\\+[1-9]\\d{6,14}(?:;ext=\\d{1,10})?$/;\n\nfunction isKnownRule(rule: Rule): boolean {\n return (PORTABLE_RULES as readonly string[]).includes(rule.rule);\n}\n\n/**\n * Whether a rule applies in a mode: a rule with a `mode` applies only in that mode, and not when the\n * mode isn't known.\n */\nfunction appliesIn(rule: Rule, mode: CheckOptions['mode']): boolean {\n return rule.mode === undefined || rule.mode === mode;\n}\n\nfunction failure(rule: Rule): RuleFailure {\n const result: RuleFailure = { rule: rule.rule };\n if ('value' in rule && rule.value !== undefined) {\n result.value = rule.value;\n }\n if (rule.message !== undefined) {\n result.message = rule.message;\n }\n return result;\n}\n\nfunction sizeOf(value: unknown): number | null {\n if (typeof value === 'number') {\n return value;\n }\n // A `money` value: `min` and `max` apply to its amount, in minor units (decision 0053).\n if (isRecord(value) && 'currency' in value && typeof value.amount === 'number') {\n return value.amount;\n }\n if (typeof value === 'string' || Array.isArray(value)) {\n return value.length;\n }\n return null;\n}\n\nfunction matchesMime(mime: string, patterns: string[]): boolean {\n return patterns.some((pattern) => {\n if (pattern.endsWith('/*')) {\n return mime.startsWith(pattern.slice(0, -1));\n }\n return mime === pattern;\n });\n}\n\n/** The files of a value, with their MIME type and size: stored files, or chosen ones (`File`). */\nfunction mediaList(value: unknown): Record<string, unknown>[] {\n const list = Array.isArray(value) ? value : [value];\n return list\n .filter(isRecord)\n .map((media) =>\n typeof Blob !== 'undefined' && media instanceof Blob\n ? { mime: media.type === '' ? undefined : media.type, size: media.size }\n : media,\n );\n}\n\n/**\n * Whether each image of a value has the crop the `crop` rule asks for (decision 0031): a crop when\n * it is required, and one of the ratios once rendered. An id alone has no crop.\n */\nfunction hasCrop(value: unknown, rule: { ratios?: string[]; required?: boolean }): boolean {\n const entries = Array.isArray(value) ? value : [value];\n return entries.every((entry) => {\n const transform = isRecord(entry) && isRecord(entry.transform) ? entry.transform : {};\n const size = renderedCropSize(transform);\n if (size === null) {\n return rule.required !== true;\n }\n const ratios = rule.ratios ?? [];\n return (\n ratios.length === 0 ||\n ratios.some((ratio) => matchesRatio(size.width, size.height, ratio))\n );\n });\n}\n\n/**\n * Whether an `embed` value comes from one of the providers, compared without case (decision 0058).\n * A value without a `provider` (an app without `GET /embeds`) is left to the backend.\n */\nfunction hasProvider(value: unknown, providers: readonly string[]): boolean {\n if (!isRecord(value) || typeof value.provider !== 'string') {\n return true;\n }\n const provider = value.provider.toLowerCase();\n return providers.some(\n (allowed) => typeof allowed === 'string' && allowed.toLowerCase() === provider,\n );\n}\n\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst DATE_TIME = /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}/;\n\n/** A bound of a `daterange`: a day or a date-time, `null` when empty, `undefined` when invalid. */\nfunction rangeBound(value: unknown): string | null | undefined {\n if (value === null || value === undefined || value === '') {\n return null;\n }\n if (typeof value !== 'string' || !(DAY.test(value) || DATE_TIME.test(value))) {\n return undefined;\n }\n return toTime(value) !== null ? value : undefined;\n}\n\n/**\n * What a `daterange` value fails (decision 0053): a bound that is missing or invalid where the range\n * isn't open (`start`, `end`), or an end before the start (`order`). `null` when it is valid.\n */\nfunction checkDateRange(value: unknown, open: unknown): 'start' | 'end' | 'order' | null {\n if (!isRecord(value)) {\n return 'start';\n }\n const start = rangeBound(value.start);\n const end = rangeBound(value.end);\n const openStart = open === 'start' || open === 'both';\n const openEnd = open === 'end' || open === 'both';\n if (start === undefined || (start === null && !openStart)) {\n return 'start';\n }\n if (end === undefined || (end === null && !openEnd)) {\n return 'end';\n }\n if (start === null || end === null) {\n return null;\n }\n // Days compare as days; a date-time compares as its instant.\n const before =\n DAY.test(start) && DAY.test(end)\n ? end < start\n : (toTime(end) as number) < (toTime(start) as number);\n return before ? 'order' : null;\n}\n\n/** Whether a `money` value has an integer amount, and a currency that the rule allows. */\nfunction isMoney(value: unknown, currencies: unknown): boolean {\n if (!isRecord(value) || !Number.isSafeInteger(value.amount)) {\n return false;\n }\n return Array.isArray(currencies) && currencies.length > 0\n ? currencies.includes(value.currency)\n : isCurrencyCode(value.currency);\n}\n\nfunction toTime(value: unknown): number | null {\n if (typeof value !== 'string' && typeof value !== 'number') {\n return null;\n }\n const time = new Date(value).getTime();\n return Number.isNaN(time) ? null : time;\n}\n\n/**\n * Checks one value against a field's rules. Returns the rules that fail. Rules limited to a `mode`\n * only apply when it is given.\n */\nexport function checkRules(\n rules: Rule[],\n value: unknown,\n root: Record<string, unknown> = {},\n mode?: CheckOptions['mode'],\n): RuleFailure[] {\n const failures: RuleFailure[] = [];\n const filled = isFilled(value);\n const applying = rules.filter((rule) => isKnownRule(rule) && appliesIn(rule, mode));\n applying.forEach((rule) => {\n if (rule.rule === 'required') {\n if (!filled) {\n failures.push(failure(rule));\n }\n return;\n }\n if (!filled) {\n return;\n }\n let valid = true;\n // What fails, when the rule says more than its parameter (`daterange`).\n let detail: string | null = null;\n switch (rule.rule) {\n case 'min':\n case 'max': {\n const size = sizeOf(value);\n const limit = rule.value as number;\n valid = size === null || (rule.rule === 'min' ? size >= limit : size <= limit);\n break;\n }\n case 'pattern':\n valid =\n typeof value !== 'string' ||\n new RegExp(rule.value as string, (rule as { flags?: string }).flags).test(\n value,\n );\n break;\n case 'email':\n valid = typeof value !== 'string' || EMAIL.test(value);\n break;\n case 'url':\n valid = typeof value !== 'string' || URL.canParse(value);\n break;\n case 'json':\n // Text that doesn't parse stays a string in the form: only objects and arrays pass\n valid = isRecord(value) || Array.isArray(value);\n break;\n case 'tel':\n valid =\n typeof value !== 'string' ||\n ((rule as { extension?: boolean }).extension === true\n ? TEL_EXTENSION\n : TEL\n ).test(value);\n break;\n case 'postalCode': {\n // The country is a code, or another field of the form (decision 0054)\n const country = isRecord(rule.value)\n ? getValue(root, String(rule.value.field))\n : rule.value;\n valid =\n typeof value !== 'string' ||\n isPostalCode(value, typeof country === 'string' ? country : null);\n break;\n }\n case 'daterange':\n detail = checkDateRange(value, (rule as { open?: unknown }).open);\n valid = detail === null;\n break;\n case 'money':\n valid = isMoney(value, (rule as { currencies?: unknown }).currencies);\n break;\n case 'in': {\n const allowed = rule.value as unknown[];\n const values = Array.isArray(value) ? value : [value];\n valid = values.every((item) => allowed.includes(item));\n break;\n }\n case 'accept':\n valid = mediaList(value).every(\n (media) =>\n typeof media.mime !== 'string' ||\n matchesMime(media.mime, rule.value as string[]),\n );\n break;\n case 'maxSize':\n valid = mediaList(value).every(\n (media) =>\n typeof media.size !== 'number' || media.size <= (rule.value as number),\n );\n break;\n case 'crop':\n valid = !isRecord(rule.value) || hasCrop(value, rule.value);\n break;\n case 'providers':\n valid = hasProvider(value, rule.value as string[]);\n break;\n case 'before':\n case 'after': {\n const bound = rule.value as string | { field: string };\n const boundTime = toTime(\n typeof bound === 'string' ? bound : getValue(root, bound.field),\n );\n const time = toTime(value);\n if (boundTime !== null && time !== null) {\n valid = rule.rule === 'before' ? time < boundTime : time > boundTime;\n }\n break;\n }\n }\n if (!valid) {\n failures.push(detail !== null ? { ...failure(rule), value: detail } : failure(rule));\n }\n });\n return failures;\n}\n\nfunction addFailures(context: Context, path: string, failures: RuleFailure[]) {\n if (failures.length > 0) {\n context.failures[path] = [...(context.failures[path] ?? []), ...failures];\n }\n}\n\n/** A string setting of a field. */\nfunction stringSetting(field: Field, key: string): string | undefined {\n const value = field.settings?.[key];\n return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\n/**\n * The rule each type implies: its values are checked whatever rules the field lists. `tel`,\n * `daterange` and `money` carry settings of their field: the extension, the open bounds, the\n * allowed currencies.\n */\nconst IMPLIED_RULES: Readonly<Record<string, (field: Field) => Rule>> = {\n json: () => ({ rule: 'json' }),\n tel: (field) =>\n field.settings?.extension === true ? { rule: 'tel', extension: true } : { rule: 'tel' },\n daterange: (field) => {\n const open = stringSetting(field, 'open');\n return { rule: 'daterange', ...(open !== undefined ? { open } : {}) } as Rule;\n },\n money: (field) => {\n const currency = stringSetting(field, 'currency');\n const listed = field.settings?.currencies;\n const currencies =\n currency !== undefined\n ? [currency]\n : Array.isArray(listed)\n ? listed.filter((code): code is string => typeof code === 'string')\n : [];\n return { rule: 'money', ...(currencies.length > 0 ? { currencies } : {}) } as Rule;\n },\n};\n\n/**\n * The rules of a field that apply in the mode, with the one its type implies: `json` for the\n * `json` type, `tel` for `tel`, `daterange` for `daterange` and `money` for `money`. A rule of\n * the same name on the field wins.\n */\nfunction rulesOf(field: Field, mode: CheckOptions['mode']): Rule[] {\n const rules = (field.rules ?? []).filter((rule) => appliesIn(rule, mode));\n const implied = IMPLIED_RULES[field.type]?.(field);\n return implied !== undefined && !rules.some((rule) => rule.rule === implied.rule)\n ? [...rules, implied]\n : rules;\n}\n\n/** The parts that make an address filled: a country or a point alone don't. */\nconst ADDRESS_TEXT_PARTS = ['street', 'unit', 'city', 'region', 'postalCode'] as const;\n\n/**\n * The checks of the parts of an `address` (decision 0054): a filled address, with a part other\n * than its country, has its required parts, and a postal code of its country.\n */\nfunction checkAddress(field: Field, value: unknown, path: string, context: Context) {\n if (!isRecord(value) || !ADDRESS_TEXT_PARTS.some((part) => isFilled(value[part]))) {\n return;\n }\n getAddressRequiredParts(field).forEach((part) => {\n if (!isFilled(value[part])) {\n addFailures(context, `${path}.${part}`, [{ rule: 'required' }]);\n }\n });\n const { postalCode, country } = value;\n if (\n typeof postalCode === 'string' &&\n isFilled(postalCode) &&\n !isPostalCode(postalCode, typeof country === 'string' ? country : null)\n ) {\n addFailures(context, `${path}.postalCode`, [{ rule: 'postalCode' }]);\n }\n}\n\n/** Whether a string is an email address. */\nconst isEmail = (text: string) => EMAIL.test(text);\n\n/** Whether the `url` of a link of a type is valid: the `rule` it fails, or `null`. */\nfunction checkLinkUrl(type: string, url: string, pattern: string | undefined): string | null {\n switch (type) {\n case 'url':\n return /^https?:\\/\\//i.test(url) && URL.canParse(url) ? null : 'url';\n case 'email':\n // `mailto:` and an address, with a query (`?subject=`) if any\n return /^mailto:/i.test(url) && isEmail(url.slice(7).split('?')[0] ?? '')\n ? null\n : 'email';\n case 'tel':\n return /^tel:/i.test(url) && TEL.test(url.slice(4)) ? null : 'tel';\n default:\n return pattern === undefined || new RegExp(pattern).test(url) ? null : 'pattern';\n }\n}\n\n/**\n * The checks of the parts of a `link` (decision 0055): a type of the field, the URL of its type,\n * its page or its file, and its label when the field requires one.\n */\nfunction checkLink(field: Field, value: unknown, path: string, context: Context) {\n if (!isRecord(value)) {\n return;\n }\n const types = getLinkTypes(field);\n const type = types.find((candidate) => candidate.id === value.type);\n if (type === undefined) {\n addFailures(context, `${path}.type`, [\n { rule: 'in', value: types.map((candidate) => candidate.id) },\n ]);\n return;\n }\n if (type.id === 'page' || type.id === 'file') {\n if (!isFilled(value[type.id])) {\n addFailures(context, `${path}.${type.id}`, [{ rule: 'required' }]);\n }\n } else if (typeof value.url !== 'string' || !isFilled(value.url)) {\n addFailures(context, `${path}.url`, [{ rule: 'required' }]);\n } else {\n const failed = checkLinkUrl(type.id, value.url.trim(), type.pattern);\n if (failed !== null) {\n addFailures(context, `${path}.url`, [\n failed === 'pattern' ? { rule: 'pattern', value: type.pattern } : { rule: failed },\n ]);\n }\n }\n const label = value.label;\n const hasLabel = isRecord(label) ? Object.values(label).some(isFilled) : isFilled(label);\n if (field.settings?.label === 'required' && !hasLabel) {\n addFailures(context, `${path}.label`, [{ rule: 'required' }]);\n }\n}\n\n/** The checks of the parts of a value that the field's type implies. */\nfunction checkParts(field: Field, value: unknown, path: string, context: Context) {\n if (field.type === 'address') {\n checkAddress(field, value, path, context);\n } else if (field.type === 'link') {\n checkLink(field, value, path, context);\n }\n}\n\nfunction checkFieldValue(field: Field, value: unknown, path: string, context: Context) {\n const rules = rulesOf(field, context.mode);\n if (field.localized === true) {\n const localized = isRecord(value) ? value : {};\n const required = rules.filter((rule) => rule.rule === 'required');\n const others = rules.filter((rule) => rule.rule !== 'required');\n if (required.length > 0) {\n const locales = context.locales;\n if (locales === undefined || locales.length === 0) {\n if (!Object.values(localized).some(isFilled)) {\n addFailures(context, path, required.map(failure));\n }\n } else {\n locales.forEach((locale) => {\n addFailures(\n context,\n `${path}.${locale}`,\n checkRules(required, localized[locale], context.root, context.mode),\n );\n });\n }\n }\n Object.entries(localized).forEach(([locale, localeValue]) => {\n addFailures(\n context,\n `${path}.${locale}`,\n checkRules(others, localeValue, context.root, context.mode),\n );\n checkParts(field, localeValue, `${path}.${locale}`, context);\n });\n return;\n }\n\n addFailures(context, path, checkRules(rules, value, context.root, context.mode));\n checkParts(field, value, path, context);\n\n // Compound fields of plugins check their `fields` as groups and repeaters do (decision 0065).\n const shape = getNestedShape(field);\n if (shape === 'group' && field.fields !== undefined && isRecord(value)) {\n checkFields(field.fields, value, `${path}.`, context);\n }\n if (shape === 'repeater' && Array.isArray(value)) {\n value.forEach((item, index) => {\n if (!isRecord(item)) {\n return;\n }\n const blockFields =\n field.types !== undefined\n ? field.types.find((type) => type.id === item.type)?.fields\n : field.fields;\n if (blockFields !== undefined) {\n checkFields(blockFields, item, `${path}.${index}.`, context);\n }\n });\n }\n}\n\nfunction checkFields(\n fields: Field[],\n values: Record<string, unknown>,\n prefix: string,\n context: Context,\n) {\n fields.forEach((field) => {\n if (field.readOnly === true) {\n return;\n }\n if (context.mode === 'create' && field.updateOnly === true) {\n return;\n }\n if (context.mode === 'update' && field.createOnly === true) {\n return;\n }\n if (\n field.visibleWhen !== undefined &&\n !evaluateCondition(field.visibleWhen, prefix === '' ? context.root : values)\n ) {\n return;\n }\n if (context.partial === true && prefix === '' && !(field.name in values)) {\n return;\n }\n checkFieldValue(field, values[field.name], `${prefix}${field.name}`, context);\n });\n}\n\n/**\n * Checks form values against the portable rules of their fields. Returns the failures keyed by\n * the dot path of the value (`title.fr`, `blocks.2.image`), the same keys as validation errors.\n * Hidden and read-only fields are skipped. Rules this version doesn't know are ignored.\n */\nexport function checkValues(\n fields: Field[],\n values: Record<string, unknown>,\n options: CheckOptions = {},\n): Record<string, RuleFailure[]> {\n const root =\n options.partial === true && options.item !== undefined\n ? { ...options.item, ...values }\n : values;\n const context: Context = { ...options, root, failures: {} };\n checkFields(fields, values, '', context);\n return context.failures;\n}\n"],"mappings":";;;;;;;;;AA8CA,IAAM,QAAQ;;AAEd,IAAM,MAAM;;AAEZ,IAAM,gBAAgB;AAEtB,SAAS,YAAY,MAAqB;CACtC,OAAQ,eAAqC,SAAS,KAAK,IAAI;AACnE;;;;;AAMA,SAAS,UAAU,MAA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MAAM,MAAM,MAAM,SAAS,KAAK,OAAO,KAAK,IAAI,CAAC,EAAE,SACnD,MAAM;EAChB,IAAI,gBAAgB,KAAA,GAChB,YAAY,aAAa,MAAM,GAAG,KAAK,GAAG,MAAM,IAAI,OAAO;CAEnE,CAAC;AAET;AAEA,SAAS,YACL,QACA,QACA,QACA,SACF;CACE,OAAO,SAAS,UAAU;EACtB,IAAI,MAAM,aAAa,MACnB;EAEJ,IAAI,QAAQ,SAAS,YAAY,MAAM,eAAe,MAClD;EAEJ,IAAI,QAAQ,SAAS,YAAY,MAAM,eAAe,MAClD;EAEJ,IACI,MAAM,gBAAgB,KAAA,KACtB,CAAC,kBAAkB,MAAM,aAAa,WAAW,KAAK,QAAQ,OAAO,MAAM,GAE3E;EAEJ,IAAI,QAAQ,YAAY,QAAQ,WAAW,MAAM,EAAE,MAAM,QAAQ,SAC7D;EAEJ,gBAAgB,OAAO,OAAO,MAAM,OAAO,GAAG,SAAS,MAAM,QAAQ,OAAO;CAChF,CAAC;AACL;;;;;;AAOA,SAAgB,YACZ,QACA,QACA,UAAwB,CAAC,GACI;CAC7B,MAAM,OACF,QAAQ,YAAY,QAAQ,QAAQ,SAAS,KAAA,IACvC;EAAE,GAAG,QAAQ;EAAM,GAAG;CAAO,IAC7B;CACV,MAAM,UAAmB;EAAE,GAAG;EAAS;EAAM,UAAU,CAAC;CAAE;CAC1D,YAAY,QAAQ,QAAQ,IAAI,OAAO;CACvC,OAAO,QAAQ;AACnB"}
|
|
1
|
+
{"version":3,"file":"rules.js","names":[],"sources":["../src/rules.ts"],"sourcesContent":["import { getAddressRequiredParts, isPostalCode } from './addresses';\nimport { getNestedShape } from './compound';\nimport { evaluateCondition } from './conditions';\nimport { PORTABLE_RULES } from './constants';\nimport { isCurrencyCode } from './currencies';\nimport { getLinkTypes } from './links';\nimport type { Field, Rule } from './schemas/field';\nimport { matchesRatio, renderedCropSize } from './transforms';\nimport { getValue, isFilled, isRecord } from './values';\n\n/** A rule that a value doesn't satisfy. */\nexport interface RuleFailure {\n rule: string;\n /**\n * The rule's parameter (`max: 120` gives `120`). For `daterange`, what fails: `start` or `end`\n * (a bound missing where the range isn't open), or `order` (the end is before the start).\n */\n value?: unknown;\n /** The message set on the rule, if any. */\n message?: string;\n}\n\nexport interface CheckOptions {\n /**\n * Locales a `required` localized field must be filled in. Without it, one filled locale is\n * enough.\n */\n locales?: string[];\n /** `create` skips `updateOnly` fields; `update` skips `createOnly` fields. */\n mode?: 'create' | 'update';\n /** Only check the fields present in the values (partial updates). */\n partial?: boolean;\n /**\n * The values of the item being updated. With `partial`, conditions (`visibleWhen`) and rules\n * that read other fields read them for the fields that aren't in the values: a field shown\n * when `status` is `published`, sent alone, is checked on a published item (decision 0043).\n */\n item?: Record<string, unknown>;\n}\n\ninterface Context extends CheckOptions {\n /** The whole form, for `visibleWhen` and date rules that reference other fields. */\n root: Record<string, unknown>;\n failures: Record<string, RuleFailure[]>;\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n/** An international phone number in E.164: `+`, then 7 to 15 digits, without a leading zero. */\nconst TEL = /^\\+[1-9]\\d{6,14}$/;\n/** The same number, with an optional extension after `;ext=` (RFC 3966): `+15145550199;ext=123`. */\nconst TEL_EXTENSION = /^\\+[1-9]\\d{6,14}(?:;ext=\\d{1,10})?$/;\n\nfunction isKnownRule(rule: Rule): boolean {\n return (PORTABLE_RULES as readonly string[]).includes(rule.rule);\n}\n\n/**\n * Whether a rule applies in a mode: a rule with a `mode` applies only in that mode, and not when the\n * mode isn't known.\n */\nfunction appliesIn(rule: Rule, mode: CheckOptions['mode']): boolean {\n return rule.mode === undefined || rule.mode === mode;\n}\n\nfunction failure(rule: Rule): RuleFailure {\n const result: RuleFailure = { rule: rule.rule };\n if ('value' in rule && rule.value !== undefined) {\n result.value = rule.value;\n }\n if (rule.message !== undefined) {\n result.message = rule.message;\n }\n return result;\n}\n\nfunction sizeOf(value: unknown): number | null {\n if (typeof value === 'number') {\n return value;\n }\n // A `money` value: `min` and `max` apply to its amount, in minor units (decision 0053).\n if (isRecord(value) && 'currency' in value && typeof value.amount === 'number') {\n return value.amount;\n }\n if (typeof value === 'string' || Array.isArray(value)) {\n return value.length;\n }\n return null;\n}\n\nfunction matchesMime(mime: string, patterns: string[]): boolean {\n return patterns.some((pattern) => {\n if (pattern.endsWith('/*')) {\n return mime.startsWith(pattern.slice(0, -1));\n }\n return mime === pattern;\n });\n}\n\n/** The files of a value, with their MIME type and size: stored files, or chosen ones (`File`). */\nfunction mediaList(value: unknown): Record<string, unknown>[] {\n const list = Array.isArray(value) ? value : [value];\n return list\n .filter(isRecord)\n .map((media) =>\n typeof Blob !== 'undefined' && media instanceof Blob\n ? { mime: media.type === '' ? undefined : media.type, size: media.size }\n : media,\n );\n}\n\n/**\n * Whether each image of a value has the crop the `crop` rule asks for (decision 0031): a crop when\n * it is required, and one of the ratios once rendered. An id alone has no crop.\n */\nfunction hasCrop(value: unknown, rule: { ratios?: string[]; required?: boolean }): boolean {\n const entries = Array.isArray(value) ? value : [value];\n return entries.every((entry) => {\n const transform = isRecord(entry) && isRecord(entry.transform) ? entry.transform : {};\n const size = renderedCropSize(transform);\n if (size === null) {\n return rule.required !== true;\n }\n const ratios = rule.ratios ?? [];\n return (\n ratios.length === 0 ||\n ratios.some((ratio) => matchesRatio(size.width, size.height, ratio))\n );\n });\n}\n\n/**\n * Whether an `embed` value comes from one of the providers, compared without case (decision 0058).\n * A value without a `provider` (an app without `GET /embeds`) is left to the backend.\n */\nfunction hasProvider(value: unknown, providers: readonly string[]): boolean {\n if (!isRecord(value) || typeof value.provider !== 'string') {\n return true;\n }\n const provider = value.provider.toLowerCase();\n return providers.some(\n (allowed) => typeof allowed === 'string' && allowed.toLowerCase() === provider,\n );\n}\n\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst DATE_TIME = /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}/;\n\n/** A bound of a `daterange`: a day or a date-time, `null` when empty, `undefined` when invalid. */\nfunction rangeBound(value: unknown): string | null | undefined {\n if (value === null || value === undefined || value === '') {\n return null;\n }\n if (typeof value !== 'string' || !(DAY.test(value) || DATE_TIME.test(value))) {\n return undefined;\n }\n return toTime(value) !== null ? value : undefined;\n}\n\n/**\n * What a `daterange` value fails (decision 0053): a bound that is missing or invalid where the range\n * isn't open (`start`, `end`), or an end before the start (`order`). `null` when it is valid.\n */\nfunction checkDateRange(value: unknown, open: unknown): 'start' | 'end' | 'order' | null {\n if (!isRecord(value)) {\n return 'start';\n }\n const start = rangeBound(value.start);\n const end = rangeBound(value.end);\n const openStart = open === 'start' || open === 'both';\n const openEnd = open === 'end' || open === 'both';\n if (start === undefined || (start === null && !openStart)) {\n return 'start';\n }\n if (end === undefined || (end === null && !openEnd)) {\n return 'end';\n }\n if (start === null || end === null) {\n return null;\n }\n // Days compare as days; a date-time compares as its instant.\n const before =\n DAY.test(start) && DAY.test(end)\n ? end < start\n : (toTime(end) as number) < (toTime(start) as number);\n return before ? 'order' : null;\n}\n\n/** Whether a `money` value has an integer amount, and a currency that the rule allows. */\nfunction isMoney(value: unknown, currencies: unknown): boolean {\n if (!isRecord(value) || !Number.isSafeInteger(value.amount)) {\n return false;\n }\n return Array.isArray(currencies) && currencies.length > 0\n ? currencies.includes(value.currency)\n : isCurrencyCode(value.currency);\n}\n\nfunction toTime(value: unknown): number | null {\n if (typeof value !== 'string' && typeof value !== 'number') {\n return null;\n }\n const time = new Date(value).getTime();\n return Number.isNaN(time) ? null : time;\n}\n\n/**\n * Checks one value against a field's rules. Returns the rules that fail. Rules limited to a `mode`\n * only apply when it is given.\n */\nexport function checkRules(\n rules: Rule[],\n value: unknown,\n root: Record<string, unknown> = {},\n mode?: CheckOptions['mode'],\n): RuleFailure[] {\n const failures: RuleFailure[] = [];\n const filled = isFilled(value);\n const applying = rules.filter((rule) => isKnownRule(rule) && appliesIn(rule, mode));\n applying.forEach((rule) => {\n if (rule.rule === 'required') {\n if (!filled) {\n failures.push(failure(rule));\n }\n return;\n }\n if (!filled) {\n return;\n }\n let valid = true;\n // What fails, when the rule says more than its parameter (`daterange`).\n let detail: string | null = null;\n switch (rule.rule) {\n case 'min':\n case 'max': {\n const size = sizeOf(value);\n const limit = rule.value as number;\n valid = size === null || (rule.rule === 'min' ? size >= limit : size <= limit);\n break;\n }\n case 'pattern':\n valid =\n typeof value !== 'string' ||\n new RegExp(rule.value as string, (rule as { flags?: string }).flags).test(\n value,\n );\n break;\n case 'email':\n valid = typeof value !== 'string' || EMAIL.test(value);\n break;\n case 'url':\n valid = typeof value !== 'string' || URL.canParse(value);\n break;\n case 'json':\n // Text that doesn't parse stays a string in the form: only objects and arrays pass\n valid = isRecord(value) || Array.isArray(value);\n break;\n case 'tel':\n valid =\n typeof value !== 'string' ||\n ((rule as { extension?: boolean }).extension === true\n ? TEL_EXTENSION\n : TEL\n ).test(value);\n break;\n case 'postalCode': {\n // The country is a code, or another field of the form (decision 0054)\n const country = isRecord(rule.value)\n ? getValue(root, String(rule.value.field))\n : rule.value;\n valid =\n typeof value !== 'string' ||\n isPostalCode(value, typeof country === 'string' ? country : null);\n break;\n }\n case 'daterange':\n detail = checkDateRange(value, (rule as { open?: unknown }).open);\n valid = detail === null;\n break;\n case 'money':\n valid = isMoney(value, (rule as { currencies?: unknown }).currencies);\n break;\n case 'in': {\n const allowed = rule.value as unknown[];\n const values = Array.isArray(value) ? value : [value];\n valid = values.every((item) => allowed.includes(item));\n break;\n }\n case 'accept':\n valid = mediaList(value).every(\n (media) =>\n typeof media.mime !== 'string' ||\n matchesMime(media.mime, rule.value as string[]),\n );\n break;\n case 'maxSize':\n valid = mediaList(value).every(\n (media) =>\n typeof media.size !== 'number' || media.size <= (rule.value as number),\n );\n break;\n case 'crop':\n valid = !isRecord(rule.value) || hasCrop(value, rule.value);\n break;\n case 'providers':\n valid = hasProvider(value, rule.value as string[]);\n break;\n case 'before':\n case 'after': {\n const bound = rule.value as string | { field: string };\n const boundTime = toTime(\n typeof bound === 'string' ? bound : getValue(root, bound.field),\n );\n const time = toTime(value);\n if (boundTime !== null && time !== null) {\n valid = rule.rule === 'before' ? time < boundTime : time > boundTime;\n }\n break;\n }\n }\n if (!valid) {\n failures.push(detail !== null ? { ...failure(rule), value: detail } : failure(rule));\n }\n });\n return failures;\n}\n\nfunction addFailures(context: Context, path: string, failures: RuleFailure[]) {\n if (failures.length > 0) {\n context.failures[path] = [...(context.failures[path] ?? []), ...failures];\n }\n}\n\n/** A string setting of a field. */\nfunction stringSetting(field: Field, key: string): string | undefined {\n const value = field.settings?.[key];\n return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\n/**\n * The rule each type implies: its values are checked whatever rules the field lists. `tel`,\n * `daterange` and `money` carry settings of their field: the extension, the open bounds, the\n * allowed currencies.\n */\nconst IMPLIED_RULES: Readonly<Record<string, (field: Field) => Rule>> = {\n json: () => ({ rule: 'json' }),\n tel: (field) =>\n field.settings?.extension === true ? { rule: 'tel', extension: true } : { rule: 'tel' },\n daterange: (field) => {\n const open = stringSetting(field, 'open');\n return { rule: 'daterange', ...(open !== undefined ? { open } : {}) } as Rule;\n },\n money: (field) => {\n const currency = stringSetting(field, 'currency');\n const listed = field.settings?.currencies;\n const currencies =\n currency !== undefined\n ? [currency]\n : Array.isArray(listed)\n ? listed.filter((code): code is string => typeof code === 'string')\n : [];\n return { rule: 'money', ...(currencies.length > 0 ? { currencies } : {}) } as Rule;\n },\n};\n\n/**\n * The rules of a field that apply in the mode, with the one its type implies: `json` for the\n * `json` type, `tel` for `tel`, `daterange` for `daterange` and `money` for `money`. A rule of\n * the same name on the field wins.\n */\nfunction rulesOf(field: Field, mode: CheckOptions['mode']): Rule[] {\n const rules = (field.rules ?? []).filter((rule) => appliesIn(rule, mode));\n const implied = IMPLIED_RULES[field.type]?.(field);\n return implied !== undefined && !rules.some((rule) => rule.rule === implied.rule)\n ? [...rules, implied]\n : rules;\n}\n\n/** The parts that make an address filled: a country or a point alone don't. */\nconst ADDRESS_TEXT_PARTS = ['street', 'unit', 'city', 'region', 'postalCode'] as const;\n\n/**\n * The checks of the parts of an `address` (decision 0054): a filled address, with a part other\n * than its country, has its required parts, and a postal code of its country.\n */\nfunction checkAddress(field: Field, value: unknown, path: string, context: Context) {\n if (!isRecord(value) || !ADDRESS_TEXT_PARTS.some((part) => isFilled(value[part]))) {\n return;\n }\n getAddressRequiredParts(field).forEach((part) => {\n if (!isFilled(value[part])) {\n addFailures(context, `${path}.${part}`, [{ rule: 'required' }]);\n }\n });\n const { postalCode, country } = value;\n if (\n typeof postalCode === 'string' &&\n isFilled(postalCode) &&\n !isPostalCode(postalCode, typeof country === 'string' ? country : null)\n ) {\n addFailures(context, `${path}.postalCode`, [{ rule: 'postalCode' }]);\n }\n}\n\n/** Whether a string is an email address. */\nconst isEmail = (text: string) => EMAIL.test(text);\n\n/** Whether the `url` of a link of a type is valid: the `rule` it fails, or `null`. */\nfunction checkLinkUrl(type: string, url: string, pattern: string | undefined): string | null {\n switch (type) {\n case 'url':\n return /^https?:\\/\\//i.test(url) && URL.canParse(url) ? null : 'url';\n case 'email':\n // `mailto:` and an address, with a query (`?subject=`) if any\n return /^mailto:/i.test(url) && isEmail(url.slice(7).split('?')[0] ?? '')\n ? null\n : 'email';\n case 'tel':\n return /^tel:/i.test(url) && TEL.test(url.slice(4)) ? null : 'tel';\n default:\n return pattern === undefined || new RegExp(pattern).test(url) ? null : 'pattern';\n }\n}\n\n/**\n * The checks of the parts of a `link` (decision 0055): a type of the field, the URL of its type,\n * its page or its file, and its label when the field requires one.\n */\nfunction checkLink(field: Field, value: unknown, path: string, context: Context) {\n if (!isRecord(value)) {\n return;\n }\n const types = getLinkTypes(field);\n const type = types.find((candidate) => candidate.id === value.type);\n if (type === undefined) {\n addFailures(context, `${path}.type`, [\n { rule: 'in', value: types.map((candidate) => candidate.id) },\n ]);\n return;\n }\n if (type.id === 'page' || type.id === 'file') {\n if (!isFilled(value[type.id])) {\n addFailures(context, `${path}.${type.id}`, [{ rule: 'required' }]);\n }\n } else if (typeof value.url !== 'string' || !isFilled(value.url)) {\n addFailures(context, `${path}.url`, [{ rule: 'required' }]);\n } else {\n const failed = checkLinkUrl(type.id, value.url.trim(), type.pattern);\n if (failed !== null) {\n addFailures(context, `${path}.url`, [\n failed === 'pattern' ? { rule: 'pattern', value: type.pattern } : { rule: failed },\n ]);\n }\n }\n const label = value.label;\n const hasLabel = isRecord(label) ? Object.values(label).some(isFilled) : isFilled(label);\n if (field.settings?.label === 'required' && !hasLabel) {\n addFailures(context, `${path}.label`, [{ rule: 'required' }]);\n }\n}\n\n/** The checks of the parts of a value that the field's type implies. */\nfunction checkParts(field: Field, value: unknown, path: string, context: Context) {\n if (field.type === 'address') {\n checkAddress(field, value, path, context);\n } else if (field.type === 'link') {\n checkLink(field, value, path, context);\n }\n}\n\nfunction checkFieldValue(field: Field, value: unknown, path: string, context: Context) {\n const rules = rulesOf(field, context.mode);\n if (field.localized === true) {\n const localized = isRecord(value) ? value : {};\n const required = rules.filter((rule) => rule.rule === 'required');\n const others = rules.filter((rule) => rule.rule !== 'required');\n if (required.length > 0) {\n const locales = context.locales;\n if (locales === undefined || locales.length === 0) {\n if (!Object.values(localized).some(isFilled)) {\n addFailures(context, path, required.map(failure));\n }\n } else {\n locales.forEach((locale) => {\n addFailures(\n context,\n `${path}.${locale}`,\n checkRules(required, localized[locale], context.root, context.mode),\n );\n });\n }\n }\n Object.entries(localized).forEach(([locale, localeValue]) => {\n addFailures(\n context,\n `${path}.${locale}`,\n checkRules(others, localeValue, context.root, context.mode),\n );\n checkParts(field, localeValue, `${path}.${locale}`, context);\n });\n return;\n }\n\n addFailures(context, path, checkRules(rules, value, context.root, context.mode));\n checkParts(field, value, path, context);\n\n // Compound fields of plugins check their `fields` as groups and repeaters do (decision 0065).\n const shape = getNestedShape(field);\n if (shape === 'group' && field.fields !== undefined && isRecord(value)) {\n checkFields(field.fields, value, `${path}.`, context);\n }\n if (shape === 'repeater' && Array.isArray(value)) {\n value.forEach((item, index) => {\n if (!isRecord(item)) {\n return;\n }\n const blockFields =\n field.types !== undefined\n ? field.types.find((type) => type.id === item.type)?.fields\n : field.fields;\n if (blockFields !== undefined) {\n checkFields(blockFields, item, `${path}.${index}.`, context);\n }\n });\n }\n}\n\nfunction checkFields(\n fields: Field[],\n values: Record<string, unknown>,\n prefix: string,\n context: Context,\n) {\n fields.forEach((field) => {\n if (field.readOnly === true || field.notInForm === true) {\n return;\n }\n if (context.mode === 'create' && field.updateOnly === true) {\n return;\n }\n if (context.mode === 'update' && field.createOnly === true) {\n return;\n }\n if (\n field.visibleWhen !== undefined &&\n !evaluateCondition(field.visibleWhen, prefix === '' ? context.root : values)\n ) {\n return;\n }\n if (context.partial === true && prefix === '' && !(field.name in values)) {\n return;\n }\n checkFieldValue(field, values[field.name], `${prefix}${field.name}`, context);\n });\n}\n\n/**\n * Checks form values against the portable rules of their fields. Returns the failures keyed by\n * the dot path of the value (`title.fr`, `blocks.2.image`), the same keys as validation errors.\n * Hidden and read-only fields, and fields that forms leave out (`notInForm`), are skipped. Rules\n * this version doesn't know are ignored.\n */\nexport function checkValues(\n fields: Field[],\n values: Record<string, unknown>,\n options: CheckOptions = {},\n): Record<string, RuleFailure[]> {\n const root =\n options.partial === true && options.item !== undefined\n ? { ...options.item, ...values }\n : values;\n const context: Context = { ...options, root, failures: {} };\n checkFields(fields, values, '', context);\n return context.failures;\n}\n"],"mappings":";;;;;;;;;AA8CA,IAAM,QAAQ;;AAEd,IAAM,MAAM;;AAEZ,IAAM,gBAAgB;AAEtB,SAAS,YAAY,MAAqB;CACtC,OAAQ,eAAqC,SAAS,KAAK,IAAI;AACnE;;;;;AAMA,SAAS,UAAU,MAAY,MAAqC;CAChE,OAAO,KAAK,SAAS,KAAA,KAAa,KAAK,SAAS;AACpD;AAEA,SAAS,QAAQ,MAAyB;CACtC,MAAM,SAAsB,EAAE,MAAM,KAAK,KAAK;CAC9C,IAAI,WAAW,QAAQ,KAAK,UAAU,KAAA,GAClC,OA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