@formancy/report-core 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["WORD","readsOf"],"sources":["../src/outcome.ts","../src/lists.ts","../src/tree.ts","../src/commands/components.ts","../src/commands/declarations.ts","../src/commands/document.ts","../src/commands/table.ts","../src/commands/registry.ts","../src/draft.ts","../src/snapshot.ts","../src/session.ts","../src/locations.ts","../src/diagnostics/codes.ts","../src/diagnostics/parts.ts","../src/expressions/reproducible.ts","../src/expressions/exactness.ts","../src/expressions/spans.ts","../src/expressions/compile-site.ts","../src/expressions/aggregates.ts","../src/expressions/members.ts","../src/expressions/compile-report.ts","../src/expressions/values.ts","../src/diagnostics/content.ts","../src/diagnostics/rounding.ts","../src/diagnostics/unused.ts","../src/diagnostics/diagnose.ts"],"sourcesContent":["/**\n * What a command gives back: the next report, or the reason there is none.\n *\n * A command is a pure function from a report to an outcome. It never writes\n * to the report it is given, and it refuses -- returns, never throws -- when\n * its own preconditions do not hold: the thing it names exists, the place it\n * names is a place, the kind it was told to expect is the kind there.\n * Whether the result is a valid report is not the command's question; the\n * session asks the validator, once, for every command alike\n * ([0008](../../../docs/decisions/0008-edits-are-commands-and-a-refused-edit-changes-nothing.md)).\n */\nimport type { ReportDefinition, ReportError } from '@formancy/report-spec'\n\n/**\n * Why an edit was refused, as stable codes. A code is for a program -- the\n * builder decides what to say and where -- and the message is for a person.\n * As with the validator's codes, a code is never reworded once released; a\n * new reason gets a new code. Each has a case in `outcome.test.ts` that is\n * refused with it, which does not compile while one is missing.\n */\nexport const REFUSAL_CODES = [\n /** The component, declaration, column, footer row or cell the command names does not exist. */\n 'not-found',\n /** The parent a location names holds no components: a text, a table, an image. */\n 'not-a-container',\n /** A location that contradicts itself: a column outside a columns block, none inside one, or a parent in another region. */\n 'invalid-location',\n /** An index that is not a whole number within the list it indexes. */\n 'index-out-of-range',\n /** A component moved into itself or into something it holds. */\n 'into-itself',\n /** The component a command names is not of the kind the command is for. */\n 'kind-mismatch',\n /** A patch that would change what identifies a thing: a component's id or kind, a column's id. */\n 'immutable-property',\n /** A command descriptor whose command is not one this package has. */\n 'unknown-command',\n /** A command descriptor whose arguments are too few, too many or of the wrong type -- one read from JSON was never type-checked. */\n 'invalid-arguments',\n /** The result is not a valid report; `errors` holds the validator's reasons. */\n 'invalid-document',\n /** An edit made against a document that is no longer the session's: its hash is not the one the edit expected. */\n 'stale-document',\n] as const\n\nexport type RefusalCode = (typeof REFUSAL_CODES)[number]\n\nexport interface Refusal {\n readonly ok: false\n readonly code: RefusalCode\n readonly message: string\n /** A JSON Pointer to what the refusal is about, when it is about one place. */\n readonly path?: string\n /** The component the refusal is about, when it is about one. */\n readonly componentId?: string\n /** The validator's errors, for `invalid-document`. */\n readonly errors?: readonly ReportError[]\n}\n\n/** The next report, and whatever else the command says about it (a duplicate's new id), or a refusal. */\nexport type CommandOutcome<E extends object = object> = ({ readonly ok: true; readonly report: ReportDefinition } & Readonly<E>) | Refusal\n\n/** An edit, bound to its arguments: what the session applies. */\nexport type Command<E extends object = object> = (report: ReportDefinition) => CommandOutcome<E>\n\n/** Where a refusal points. */\nexport interface Place {\n readonly path?: string | undefined\n readonly componentId?: string | undefined\n}\n\nexport function refuse(code: RefusalCode, message: string, place: Place = {}): Refusal {\n return {\n ok: false,\n code,\n message,\n ...(place.path === undefined ? {} : { path: place.path }),\n ...(place.componentId === undefined ? {} : { componentId: place.componentId }),\n }\n}\n\nexport function isRefusal(value: unknown): value is Refusal {\n return typeof value === 'object' && value !== null && (value as { ok?: unknown }).ok === false\n}\n\n/** A name as a message quotes it: at most 40 characters, so no message grows with what a caller passed. */\nexport function quote(text: string): string {\n return JSON.stringify(text.length > 40 ? `${text.slice(0, 40)}...` : text)\n}\n","/**\n * Copy-on-write edits to lists and objects: the vocabulary every command is\n * written in. Each returns a new list or object and leaves its input as it\n * was, so a command never writes to the report it was given.\n */\nimport { refuse } from './outcome.js'\nimport type { Place, Refusal } from './outcome.js'\n\n/**\n * A change to some of an object's properties. A value sets a property;\n * `null` removes one that is optional. A required property cannot be given\n * `null`, so a patch cannot remove one.\n *\n * `null`, not `undefined`, because a patch is also data: a proposal carries\n * it as JSON, which has no undefined and drops a key that holds one. A\n * removal written with undefined would arrive as no change at all.\n */\nexport type Patch<T> = { readonly [K in keyof T]?: undefined extends T[K] ? Exclude<T[K], undefined> | null : T[K] }\n\n/**\n * `target` with `patch` applied: the properties it names set, or removed\n * where it gives `null`. A property given `undefined` -- possible only for a\n * caller tsc never saw -- is left as it is, as it would be once the patch\n * had been through JSON.\n */\nexport function patched<T extends object>(target: T, patch: Patch<T>): T {\n const next = { ...target } as Record<string, unknown>\n for (const [key, value] of Object.entries(patch)) {\n if (value === null) delete next[key]\n else if (value !== undefined) next[key] = value\n }\n return next as T\n}\n\n/** A refusal unless `index` is a whole number from 0 to `last`, inclusive. */\nexport function checkIndex(index: number, last: number, what: string, place: Place = {}): Refusal | undefined {\n if (Number.isInteger(index) && index >= 0 && index <= last) return undefined\n const range = last < 0 ? 'there is nothing to index' : `it is a whole number from 0 to ${last}`\n return refuse('index-out-of-range', `${String(index)} is not a position in ${what}: ${range}`, place)\n}\n\nexport function insertedAt<T>(list: readonly T[], index: number, item: T): T[] {\n return [...list.slice(0, index), item, ...list.slice(index)]\n}\n\nexport function removedAt<T>(list: readonly T[], index: number): T[] {\n return [...list.slice(0, index), ...list.slice(index + 1)]\n}\n\nexport function replacedAt<T>(list: readonly T[], index: number, item: T): T[] {\n return list.map((existing, at) => (at === index ? item : existing))\n}\n\n/** The item at `from` moved so that it ends at `to`; the others keep their order. */\nexport function movedTo<T>(list: readonly T[], from: number, to: number): T[] {\n const item = list[from] as T\n return insertedAt(removedAt(list, from), to, item)\n}\n","/**\n * Places in a report: where a component stands or can be put, and how to\n * change one place without touching the rest.\n *\n * A place is named by the same JSON Pointers `walkComponents` and the\n * validator use, so a command, a diagnostic and a validation error about\n * one component all point at one path.\n */\nimport { componentAt } from '@formancy/report-spec'\nimport type { Component, ComponentKind, RegionName, ReportDefinition } from '@formancy/report-spec'\nimport { quote, refuse } from './outcome.js'\nimport type { Refusal } from './outcome.js'\n\n/**\n * Where a component goes: a position in a region's list, or in the list a\n * container holds -- a section's, a keep-together block's, or one column's\n * of a columns block. `index` is the position the component ends at.\n */\nexport interface Location {\n readonly region: RegionName\n /** The id of the container; absent for the region's own list. */\n readonly parent?: string\n /** Which column, for a columns block, and only for one. */\n readonly column?: number\n readonly index: number\n}\n\ntype Lists = (list: readonly Component[]) => readonly Component[]\n\n/** A list of components a container holds, and for a columns block which column it is. */\nexport interface HeldList {\n readonly column?: number\n readonly list: readonly Component[]\n}\n\n/** How a kind holds components: the lists it holds, and itself rebuilt with every one of them changed. */\ninterface Holding<C extends Component> {\n readonly lists: (component: C) => readonly HeldList[]\n readonly rebuild: (component: C, change: Lists) => C\n}\n\n/** The one shape every container but a columns block has: one list, under `components`. */\nfunction oneList<C extends Extract<Component, { readonly components: readonly Component[] }>>(): Holding<C> {\n return { lists: (component) => [{ list: component.components }], rebuild: (component, change) => ({ ...component, components: change(component.components) }) }\n}\n\n/**\n * How each kind holds components, or undefined for a kind that holds none.\n * A table over every kind, so a container added to the format without\n * saying where it keeps its children does not compile.\n */\nconst CONTAINERS: { readonly [K in ComponentKind]: Holding<Extract<Component, { kind: K }>> | undefined } = {\n text: undefined,\n image: undefined,\n line: undefined,\n rectangle: undefined,\n spacer: undefined,\n columns: {\n lists: (component) => component.columns.map((slot, column) => ({ column, list: slot.components })),\n rebuild: (component, change) => ({ ...component, columns: component.columns.map((slot) => ({ ...slot, components: change(slot.components) })) }),\n },\n section: oneList(),\n table: undefined,\n pageBreak: undefined,\n keepTogether: oneList(),\n}\n\nfunction holding(component: Component): Holding<Component> | undefined {\n return CONTAINERS[component.kind] as Holding<Component> | undefined\n}\n\n/** `component` with every list of components it holds changed by `change`; itself when it holds none. */\nexport function withChildren(component: Component, change: Lists): Component {\n return holding(component)?.rebuild(component, change) ?? component\n}\n\n/** The lists of components `component` holds, in order; none for a kind that holds none. */\nexport function heldLists(component: Component): readonly HeldList[] {\n return holding(component)?.lists(component) ?? []\n}\n\n/** A list of components, and the JSON Pointer to it. */\nexport interface ComponentList {\n readonly pointer: string\n readonly list: readonly Component[]\n}\n\n/** The list a location names, without its index, or why it names none. */\nexport function listAt(report: ReportDefinition, location: Omit<Location, 'index'>): ComponentList | Refusal {\n const { region, parent, column } = location\n if (parent === undefined) {\n if (column !== undefined) return refuse('invalid-location', 'a column is chosen only inside a columns block')\n return { pointer: `/regions/${region}`, list: report.regions[region] }\n }\n const found = componentAt(report, parent)\n if (found === undefined) return refuse('not-found', `no component is ${quote(parent)}`, { componentId: parent })\n const place = { path: found.path, componentId: parent }\n if (found.region !== region) return refuse('invalid-location', `${quote(parent)} stands in the ${found.region}, not the ${region}`, place)\n const container = found.component\n if (holding(container) === undefined) return refuse('not-a-container', `${quote(parent)} is a ${container.kind}, which holds no components`, place)\n if (container.kind === 'columns') {\n if (column === undefined) return refuse('invalid-location', 'a columns block holds components in its columns; say which column', place)\n const slot = container.columns[column]\n if (!Number.isInteger(column) || slot === undefined) {\n return refuse('index-out-of-range', `${String(column)} is not a column of ${quote(parent)}, which has ${container.columns.length}`, place)\n }\n return { pointer: `${found.path}/columns/${column}/components`, list: slot.components }\n }\n if (column !== undefined) return refuse('invalid-location', `${quote(parent)} is a ${container.kind}, which has no columns`, place)\n // Every other container holds one list, under `components`.\n return { pointer: `${found.path}/components`, list: (container as { readonly components: readonly Component[] }).components }\n}\n\n/** The list a component stands in, and its position there, from the component's own pointer. */\nexport function standing(path: string): { readonly pointer: string; readonly index: number } {\n const cut = path.lastIndexOf('/')\n return { pointer: path.slice(0, cut), index: Number(path.slice(cut + 1)) }\n}\n\n/** The segments of a JSON Pointer to something inside the report -- never '', the report itself -- unescaped (RFC 6901). */\nfunction segments(pointer: string): string[] {\n return pointer\n .slice(1)\n .split('/')\n .map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'))\n}\n\nfunction updated(value: unknown, path: readonly string[], update: (value: unknown) => unknown): unknown {\n const [head, ...rest] = path\n if (head === undefined) return update(value)\n if (Array.isArray(value)) {\n const index = Number(head)\n return value.map((item: unknown, at) => (at === index ? updated(item, rest, update) : item))\n }\n const record = value as Record<string, unknown>\n return { ...record, [head]: updated(record[head], rest, update) }\n}\n\n/**\n * `report` with the value at `pointer` replaced by what `update` makes of\n * it. Only the objects and arrays on the way to it are copied; everything\n * else is shared with `report`, which is left as it was.\n */\nexport function updateAt<T>(report: ReportDefinition, pointer: string, update: (value: T) => unknown): ReportDefinition {\n return updated(report, segments(pointer), update as (value: unknown) => unknown) as ReportDefinition\n}\n","/**\n * Commands on the component tree: insert, remove, move, update and\n * duplicate, at any depth, and the ids new components take.\n *\n * Every drag has a keyboard path (formancy.ai 0046), so these are that\n * path: a location is a region or container and an index, and an index\n * outside the list is refused, never clamped, so that a keyboard move and a\n * pointer drop that name the same place do the same thing.\n */\nimport { componentAt, isIdentifier, walkComponents } from '@formancy/report-spec'\nimport type { Component, ComponentKind, ReportDefinition } from '@formancy/report-spec'\nimport { checkIndex, insertedAt, patched, removedAt } from '../lists.js'\nimport type { Patch } from '../lists.js'\nimport { isRefusal, quote, refuse } from '../outcome.js'\nimport type { CommandOutcome, Refusal } from '../outcome.js'\nimport { listAt, standing, updateAt, withChildren } from '../tree.js'\nimport type { ComponentList, Location } from '../tree.js'\n\n/**\n * A change to a component of kind `K`: any of its own properties, but never\n * its id or its kind. Typed per kind, so a patch for a text cannot carry a\n * table's columns; `null` removes an optional property.\n */\nexport type ComponentPatch<K extends ComponentKind> = K extends ComponentKind ? Patch<Omit<Extract<Component, { kind: K }>, 'id' | 'kind'>> : never\n\n/** The longest identifier the format allows: `isIdentifier`'s rule in report-spec, at most 64 characters. */\nconst IDENTIFIER_LENGTH = 64\n\n/** A trailing number an id was given to make it unique: `-2` in `intro-2`. */\nconst NUMBERED = /-\\d+$/\n\nfunction missing(id: string): Refusal {\n return refuse('not-found', `no component is ${quote(id)}`, { componentId: id })\n}\n\n/** `component` put at `index` of `target`. */\nfunction placed(report: ReportDefinition, target: ComponentList, index: number, component: Component): CommandOutcome {\n const outside = checkIndex(index, target.list.length, `a list of ${target.list.length} components`, { path: target.pointer })\n if (outside !== undefined) return outside\n return { ok: true, report: updateAt<readonly Component[]>(report, target.pointer, (list) => insertedAt(list, index, component)) }\n}\n\nexport function insertComponent(report: ReportDefinition, location: Location, component: Component): CommandOutcome {\n const target = listAt(report, location)\n return isRefusal(target) ? target : placed(report, target, location.index, component)\n}\n\n/** Removes a component and everything it holds. */\nexport function removeComponent(report: ReportDefinition, id: string): CommandOutcome {\n const found = componentAt(report, id)\n if (found === undefined) return missing(id)\n const { pointer, index } = standing(found.path)\n return { ok: true, report: updateAt<readonly Component[]>(report, pointer, (list) => removedAt(list, index)) }\n}\n\n/**\n * Moves a component, with everything it holds, so that it ends at\n * `location`. The location is read in the report as it is without the\n * component, so moving one down its own list is its index plus one.\n */\nexport function moveComponent(report: ReportDefinition, id: string, location: Location): CommandOutcome {\n const found = componentAt(report, id)\n if (found === undefined) return missing(id)\n const parent = location.parent === undefined ? undefined : componentAt(report, location.parent)\n if (parent !== undefined && (parent.path === found.path || parent.path.startsWith(`${found.path}/`))) {\n return refuse('into-itself', `${quote(id)} cannot be moved into itself or into something it holds`, { path: found.path, componentId: id })\n }\n const { pointer, index } = standing(found.path)\n const without = updateAt<readonly Component[]>(report, pointer, (list) => removedAt(list, index))\n const target = listAt(without, location)\n return isRefusal(target) ? target : placed(without, target, location.index, found.component)\n}\n\n/**\n * Changes a component's own properties. `kind` says which kind the patch is\n * for, so the patch is typed; it is checked against the component's, for a\n * caller -- a proposal read from JSON -- whose types were never checked.\n */\nexport function updateComponent<K extends ComponentKind>(report: ReportDefinition, id: string, kind: K, patch: ComponentPatch<K>): CommandOutcome {\n const found = componentAt(report, id)\n if (found === undefined) return missing(id)\n if (found.component.kind !== kind) return refuse('kind-mismatch', `${quote(id)} is a ${found.component.kind}, not a ${kind}`, { path: found.path, componentId: id })\n for (const key of ['id', 'kind'] as const) {\n if (Object.hasOwn(patch, key)) {\n return refuse('immutable-property', `a component's ${key} never changes in place; insert a new component instead`, { path: `${found.path}/${key}`, componentId: id })\n }\n }\n return { ok: true, report: updateAt<Component>(report, found.path, (component) => patched(component as object, patch as Patch<object>)) }\n}\n\n/** `prefix` if no component has it, otherwise its base numbered from 2, within the identifier's length. */\nfunction freshId(prefix: string, taken: ReadonlySet<string>): string {\n if (!taken.has(prefix)) return prefix\n const base = prefix.replace(NUMBERED, '')\n for (let number = 2; ; number += 1) {\n const suffix = `-${number}`\n const id = `${base.slice(0, IDENTIFIER_LENGTH - suffix.length)}${suffix}`\n if (!taken.has(id)) return id\n }\n}\n\nfunction idsOf(report: ReportDefinition): Set<string> {\n return new Set(walkComponents(report).map(({ component }) => component.id))\n}\n\n/**\n * What a new component of each kind is named after: its kind, written as an\n * identifier. A table over every kind, so a kind added to the format is\n * named too; a camelCase kind is not an identifier as it stands.\n */\nconst NAMED_AFTER: { readonly [K in ComponentKind]: string } = {\n text: 'text',\n image: 'image',\n line: 'line',\n rectangle: 'rectangle',\n spacer: 'spacer',\n columns: 'columns',\n section: 'section',\n table: 'table',\n pageBreak: 'page-break',\n keepTogether: 'keep-together',\n}\n\n/**\n * An id no component in `report` has: `prefix` itself when it is free, and\n * otherwise `prefix-2`, `prefix-3` and so on, counted from the prefix's base\n * when it already ends in a number. A component kind is a prefix too, the\n * palette's: `pageBreak` gives `page-break`. Throws a RangeError for any\n * other prefix that is not an identifier, which would give an id the\n * validator refuses.\n */\nexport function nextComponentId(report: ReportDefinition, prefix: string): string {\n const named = Object.hasOwn(NAMED_AFTER, prefix) ? NAMED_AFTER[prefix as ComponentKind] : prefix\n if (!isIdentifier(named)) throw new RangeError(`${quote(prefix)} is not an identifier: lower-case letters, digits and hyphens, starting with a letter`)\n return freshId(named, idsOf(report))\n}\n\n/** A copy of `component` and all it holds, each given a fresh id, recorded in `taken` as it is given. */\nfunction renamed(component: Component, taken: Set<string>): Component {\n const id = freshId(component.id, taken)\n taken.add(id)\n return withChildren({ ...component, id }, (list) => list.map((child) => renamed(child, taken)))\n}\n\n/** Copies a component, and everything it holds, to just after it, with fresh ids; the outcome says the copy's id. */\nexport function duplicateComponent(report: ReportDefinition, id: string): CommandOutcome<{ readonly id: string }> {\n const found = componentAt(report, id)\n if (found === undefined) return missing(id)\n const copy = renamed(found.component, idsOf(report))\n const { pointer, index } = standing(found.path)\n return { ok: true, report: updateAt<readonly Component[]>(report, pointer, (list) => insertedAt(list, index + 1, copy)), id: copy.id }\n}\n","/**\n * Commands on what a report declares: print styles, datasets and their\n * fields, parameters, assets and aggregates.\n *\n * Every declaration is a list of objects with an id (0007), so one pair of\n * operations serves them all: a put, which replaces the declaration with\n * that id where it stands or appends a new one, and a remove. The id is the\n * key, and the body is everything else, so a put cannot rename: renaming\n * would leave every reference to the old id behind.\n *\n * A remove does not chase references. Removing a style a component still\n * uses gives a report the validator refuses, so the session refuses the\n * edit with the validator's `unknown-style` at each place that uses it,\n * which is what an author needs to see before deciding.\n */\nimport type { AggregateDef, AssetRef, DatasetContract, DatasetRole, FieldContract, ParameterDef, PrintStyle, ReportDefinition } from '@formancy/report-spec'\nimport { checkIndex, movedTo, removedAt, replacedAt } from '../lists.js'\nimport { quote, refuse } from '../outcome.js'\nimport type { CommandOutcome, Refusal } from '../outcome.js'\n\ninterface Declared {\n readonly id: string\n}\n\n/** `list` with the declaration `id` replaced where it stands, or appended. */\nfunction put<T extends Declared>(list: readonly T[], id: string, body: Omit<T, 'id'>): T[] {\n const item = { id, ...body } as unknown as T\n const index = list.findIndex((existing) => existing.id === id)\n return index === -1 ? [...list, item] : replacedAt(list, index, item)\n}\n\n/** `list` without the declaration `id`, or a refusal pointing at the list. */\nfunction remove<T extends Declared>(list: readonly T[], id: string, path: string, what: string): T[] | Refusal {\n const index = list.findIndex((existing) => existing.id === id)\n return index === -1 ? refuse('not-found', `no ${what} is ${quote(id)}`, { path }) : removedAt(list, index)\n}\n\n/** `report` with `key` set to `list`, or the refusal. */\nfunction withList<K extends 'styles' | 'parameters' | 'assets' | 'aggregates'>(report: ReportDefinition, key: K, list: ReportDefinition[K] | Refusal): CommandOutcome {\n return 'ok' in list ? list : { ok: true, report: { ...report, [key]: list } }\n}\n\nexport function putStyle(report: ReportDefinition, id: string, style: Omit<PrintStyle, 'id'>): CommandOutcome {\n return withList(report, 'styles', put(report.styles, id, style))\n}\n\nexport function removeStyle(report: ReportDefinition, id: string): CommandOutcome {\n return withList(report, 'styles', remove(report.styles, id, '/styles', 'style'))\n}\n\nexport function putParameter(report: ReportDefinition, id: string, parameter: Omit<ParameterDef, 'id'>): CommandOutcome {\n return withList(report, 'parameters', put(report.parameters, id, parameter))\n}\n\nexport function removeParameter(report: ReportDefinition, id: string): CommandOutcome {\n return withList(report, 'parameters', remove(report.parameters, id, '/parameters', 'parameter'))\n}\n\n/** The parameter `id` moved so that it ends at `index`: the order the parameter form shows. */\nexport function moveParameter(report: ReportDefinition, id: string, index: number): CommandOutcome {\n const from = report.parameters.findIndex((parameter) => parameter.id === id)\n if (from === -1) return refuse('not-found', `no parameter is ${quote(id)}`, { path: '/parameters' })\n const outside = checkIndex(index, report.parameters.length - 1, 'the parameters', { path: '/parameters' })\n return outside ?? { ok: true, report: { ...report, parameters: movedTo(report.parameters, from, index) } }\n}\n\nexport function putAsset(report: ReportDefinition, id: string, asset: Omit<AssetRef, 'id'>): CommandOutcome {\n return withList(report, 'assets', put(report.assets, id, asset))\n}\n\nexport function removeAsset(report: ReportDefinition, id: string): CommandOutcome {\n return withList(report, 'assets', remove(report.assets, id, '/assets', 'asset'))\n}\n\nexport function putAggregate(report: ReportDefinition, id: string, aggregate: Omit<AggregateDef, 'id'>): CommandOutcome {\n return withList(report, 'aggregates', put(report.aggregates, id, aggregate))\n}\n\nexport function removeAggregate(report: ReportDefinition, id: string): CommandOutcome {\n return withList(report, 'aggregates', remove(report.aggregates, id, '/aggregates', 'aggregate'))\n}\n\n/** The dataset in `slot`: the header or the detail contract, replaced whole. */\nexport function putDataset(report: ReportDefinition, slot: DatasetRole, contract: DatasetContract): CommandOutcome {\n return { ok: true, report: { ...report, datasets: { ...report.datasets, [slot]: contract } } }\n}\n\nexport function removeDataset(report: ReportDefinition, slot: DatasetRole): CommandOutcome {\n if (report.datasets[slot] === undefined) return refuse('not-found', `the report declares no ${slot} dataset`, { path: `/datasets/${slot}` })\n const { [slot]: _removed, ...datasets } = report.datasets\n return { ok: true, report: { ...report, datasets } }\n}\n\n/** `report` with the fields of the dataset in `slot` changed by `change`, or a refusal when there is no such dataset. */\nfunction withFields(report: ReportDefinition, slot: DatasetRole, change: (fields: readonly FieldContract[]) => readonly FieldContract[] | Refusal): CommandOutcome {\n const dataset = report.datasets[slot]\n if (dataset === undefined) return refuse('not-found', `the report declares no ${slot} dataset`, { path: `/datasets/${slot}` })\n const fields = change(dataset.fields)\n return 'ok' in fields ? fields : { ok: true, report: { ...report, datasets: { ...report.datasets, [slot]: { ...dataset, fields } } } }\n}\n\nexport function putField(report: ReportDefinition, slot: DatasetRole, fieldId: string, field: Omit<FieldContract, 'id'>): CommandOutcome {\n return withFields(report, slot, (fields) => put(fields, fieldId, field))\n}\n\nexport function removeField(report: ReportDefinition, slot: DatasetRole, fieldId: string): CommandOutcome {\n return withFields(report, slot, (fields) => remove(fields, fieldId, `/datasets/${slot}/fields`, `field of the ${slot} dataset`))\n}\n","/**\n * Commands on the report as a whole: its title, its locale, its page, and\n * the whole document at once.\n */\nimport type { Margins, Orientation, PageSizeName, ReportDefinition } from '@formancy/report-spec'\nimport { patched } from '../lists.js'\nimport type { CommandOutcome } from '../outcome.js'\n\nexport function setTitle(report: ReportDefinition, title: string): CommandOutcome {\n return { ok: true, report: { ...report, title } }\n}\n\nexport function setLocale(report: ReportDefinition, locale: string): CommandOutcome {\n return { ok: true, report: { ...report, locale } }\n}\n\n/** A change to the page: its size, its orientation, any of its margins. */\nexport interface PagePatch {\n readonly size?: PageSizeName\n readonly orientation?: Orientation\n readonly margins?: Partial<Margins>\n}\n\nexport function setPage(report: ReportDefinition, patch: PagePatch): CommandOutcome {\n const { margins, ...rest } = patch\n const page = { ...patched(report.page, rest), margins: margins === undefined ? report.page.margins : { ...report.page.margins, ...margins } }\n return { ok: true, report: { ...report, page } }\n}\n\n/**\n * The whole document, replaced: a paste, an import, an AI proposal that\n * rewrote the report. Taken as one edit, so the session validates it and\n * records it as one undo step like any other.\n */\nexport function replaceDocument(_report: ReportDefinition, next: ReportDefinition): CommandOutcome {\n return { ok: true, report: next }\n}\n","/**\n * Commands on the table over the detail dataset: its columns, its one\n * grouping level, its sort keys, and the rows under its groups and under\n * the table -- subtotals, tax lines, totals -- cell by cell.\n *\n * Each names the table by its component id. A column is named by its id,\n * which footer cells refer to, so a column's id never changes in place; a\n * footer row has no id and is named by its position.\n */\nimport { componentAt } from '@formancy/report-spec'\nimport type { ReportDefinition, SortKey, TableColumn, TableComponent, TableFooterCell, TableFooterRow, TableGroup } from '@formancy/report-spec'\nimport { checkIndex, insertedAt, movedTo, patched, removedAt, replacedAt } from '../lists.js'\nimport type { Patch } from '../lists.js'\nimport { isRefusal, quote, refuse } from '../outcome.js'\nimport type { CommandOutcome, Place, Refusal } from '../outcome.js'\nimport { updateAt } from '../tree.js'\n\n/** Where a table is: its JSON Pointer and its id. */\ninterface TablePlace {\n readonly path: string\n readonly componentId: string\n}\n\n/** Which footer rows: those under the whole table, or those under each group. */\nexport type FooterRows = 'totals' | 'groupFooter'\n\n/** The table `tableId` changed by `change`, which is told where the table is. */\nfunction withTable(report: ReportDefinition, tableId: string, change: (table: TableComponent, place: TablePlace) => TableComponent | Refusal): CommandOutcome {\n const found = componentAt(report, tableId)\n if (found === undefined) return refuse('not-found', `no component is ${quote(tableId)}`, { componentId: tableId })\n const place = { path: found.path, componentId: tableId }\n if (found.component.kind !== 'table') return refuse('kind-mismatch', `${quote(tableId)} is a ${found.component.kind}, not a table`, place)\n const next = change(found.component, place)\n return isRefusal(next) ? next : { ok: true, report: updateAt(report, found.path, () => next) }\n}\n\n/** The position of the column `columnId`, or a refusal. */\nfunction columnIndex(table: TableComponent, columnId: string, place: TablePlace): number | Refusal {\n const index = table.columns.findIndex((column) => column.id === columnId)\n return index === -1 ? refuse('not-found', `the table has no column ${quote(columnId)}`, { ...place, path: `${place.path}/columns` }) : index\n}\n\nexport function insertColumn(report: ReportDefinition, tableId: string, index: number, column: TableColumn): CommandOutcome {\n return withTable(report, tableId, (table, place) => {\n const outside = checkIndex(index, table.columns.length, `the table's ${table.columns.length} columns`, { ...place, path: `${place.path}/columns` })\n return outside ?? { ...table, columns: insertedAt(table.columns, index, column) }\n })\n}\n\n/** Removes a column, and its cell from every footer row: a cell belongs to its column. */\nexport function removeColumn(report: ReportDefinition, tableId: string, columnId: string): CommandOutcome {\n return withTable(report, tableId, (table, place) => {\n const index = columnIndex(table, columnId, place)\n if (isRefusal(index)) return index\n const uncelled = (rows: readonly TableFooterRow[]): TableFooterRow[] =>\n rows.map((row) => (row.cells.some((cell) => cell.column === columnId) ? { ...row, cells: row.cells.filter((cell) => cell.column !== columnId) } : row))\n return {\n ...table,\n columns: removedAt(table.columns, index),\n ...(table.group === undefined ? {} : { group: { ...table.group, footer: uncelled(table.group.footer) } }),\n ...(table.totals === undefined ? {} : { totals: uncelled(table.totals) }),\n }\n })\n}\n\n/** Moves a column so that it ends at `index`, counted without it. */\nexport function moveColumn(report: ReportDefinition, tableId: string, columnId: string, index: number): CommandOutcome {\n return withTable(report, tableId, (table, place) => {\n const from = columnIndex(table, columnId, place)\n if (isRefusal(from)) return from\n const outside = checkIndex(index, table.columns.length - 1, `the table's ${table.columns.length} columns`, { ...place, path: `${place.path}/columns` })\n return outside ?? { ...table, columns: movedTo(table.columns, from, index) }\n })\n}\n\n/** Changes a column's properties; its id, which footer cells name, never changes in place. */\nexport function updateColumn(report: ReportDefinition, tableId: string, columnId: string, patch: Patch<Omit<TableColumn, 'id'>>): CommandOutcome {\n return withTable(report, tableId, (table, place) => {\n const index = columnIndex(table, columnId, place)\n if (isRefusal(index)) return index\n if (Object.hasOwn(patch, 'id')) {\n return refuse('immutable-property', \"a column's id is what its footer cells name, and never changes in place\", { ...place, path: `${place.path}/columns/${index}/id` })\n }\n return { ...table, columns: replacedAt(table.columns, index, patched<TableColumn>(table.columns[index] as TableColumn, patch)) }\n })\n}\n\n/** Sets the table's one grouping level, or removes it with `null` -- as a patch removes, so a removal survives JSON. */\nexport function setGroup(report: ReportDefinition, tableId: string, group: TableGroup | null): CommandOutcome {\n return withTable(report, tableId, (table) => {\n const { group: _old, ...rest } = table\n return group === null ? rest : { ...rest, group }\n })\n}\n\n/** Sets the table's sort keys, or removes them with `null`. */\nexport function setSort(report: ReportDefinition, tableId: string, sort: readonly SortKey[] | null): CommandOutcome {\n return withTable(report, tableId, (table) => {\n const { sort: _old, ...rest } = table\n return sort === null ? rest : { ...rest, sort }\n })\n}\n\n/** The footer rows a table has in `which`, where they are, and how to give it others; or a refusal. */\nfunction footerOf(table: TableComponent, which: FooterRows, place: TablePlace) {\n if (which === 'totals') {\n return { rows: table.totals ?? [], at: { ...place, path: `${place.path}/totals` }, set: (totals: readonly TableFooterRow[]): TableComponent => ({ ...table, totals }) }\n }\n const group = table.group\n if (group === undefined) return refuse('not-found', `${quote(place.componentId)} has no group, so it has no group footer`, { ...place, path: `${place.path}/group` })\n return {\n rows: group.footer,\n at: { ...place, path: `${place.path}/group/footer` },\n set: (footer: readonly TableFooterRow[]): TableComponent => ({ ...table, group: { ...group, footer } }),\n }\n}\n\n/** The footer rows in `which` changed by `change`, which is told where they are. */\nfunction withFooter(\n report: ReportDefinition,\n tableId: string,\n which: FooterRows,\n change: (rows: readonly TableFooterRow[], at: TablePlace) => readonly TableFooterRow[] | Refusal,\n): CommandOutcome {\n return withTable(report, tableId, (table, place) => {\n const footer = footerOf(table, which, place)\n if (isRefusal(footer)) return footer\n const rows = change(footer.rows, footer.at)\n return isRefusal(rows) ? rows : footer.set(rows)\n })\n}\n\n/** A refusal unless `index` is a row of `rows`. */\nconst checkRow = (rows: readonly TableFooterRow[], index: number, at: Place): Refusal | undefined => checkIndex(index, rows.length - 1, `${rows.length} footer rows`, at)\n\nexport function insertFooterRow(report: ReportDefinition, tableId: string, which: FooterRows, index: number, row: TableFooterRow): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => checkIndex(index, rows.length, `${rows.length} footer rows`, at) ?? insertedAt(rows, index, row))\n}\n\nexport function removeFooterRow(report: ReportDefinition, tableId: string, which: FooterRows, index: number): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => checkRow(rows, index, at) ?? removedAt(rows, index))\n}\n\n/** Moves the footer row at `from` so that it ends at `to`. */\nexport function moveFooterRow(report: ReportDefinition, tableId: string, which: FooterRows, from: number, to: number): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => checkRow(rows, from, at) ?? checkRow(rows, to, at) ?? movedTo(rows, from, to))\n}\n\n/** Changes a footer row: its cells as a whole, or its style. */\nexport function updateFooterRow(report: ReportDefinition, tableId: string, which: FooterRows, index: number, patch: Patch<TableFooterRow>): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => checkRow(rows, index, at) ?? replacedAt(rows, index, patched(rows[index] as TableFooterRow, patch)))\n}\n\n/** Puts the cell of `cell.column` into a footer row: replacing that column's cell where it is, or appending it. */\nexport function putFooterCell(report: ReportDefinition, tableId: string, which: FooterRows, rowIndex: number, cell: TableFooterCell): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => {\n const outside = checkRow(rows, rowIndex, at)\n if (outside !== undefined) return outside\n const row = rows[rowIndex] as TableFooterRow\n const index = row.cells.findIndex(({ column }) => column === cell.column)\n return replacedAt(rows, rowIndex, { ...row, cells: index === -1 ? [...row.cells, cell] : replacedAt(row.cells, index, cell) })\n })\n}\n\nexport function removeFooterCell(report: ReportDefinition, tableId: string, which: FooterRows, rowIndex: number, columnId: string): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => {\n const outside = checkRow(rows, rowIndex, at)\n if (outside !== undefined) return outside\n const row = rows[rowIndex] as TableFooterRow\n const index = row.cells.findIndex(({ column }) => column === columnId)\n if (index === -1) return refuse('not-found', `this footer row has no cell for column ${quote(columnId)}`, { ...at, path: `${at.path}/${rowIndex}/cells` })\n return replacedAt(rows, rowIndex, { ...row, cells: removedAt(row.cells, index) })\n })\n}\n","/**\n * Every command by name, and a command as data: a name and its arguments.\n *\n * A proposal -- from an AI, from a saved macro, from another window -- is a\n * bounded list of operations, not code (plan 16). A descriptor is one such\n * operation, and it runs through exactly the function the builder calls, so\n * a proposal and a click cannot do the same thing two ways.\n */\nimport { DATASET_ROLES, REGION_NAMES } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { quote, refuse } from '../outcome.js'\nimport type { Command, CommandOutcome } from '../outcome.js'\nimport { duplicateComponent, insertComponent, moveComponent, removeComponent, updateComponent } from './components.js'\nimport {\n moveParameter,\n putAggregate,\n putAsset,\n putDataset,\n putField,\n putParameter,\n putStyle,\n removeAggregate,\n removeAsset,\n removeDataset,\n removeField,\n removeParameter,\n removeStyle,\n} from './declarations.js'\nimport { replaceDocument, setLocale, setPage, setTitle } from './document.js'\nimport {\n insertColumn,\n insertFooterRow,\n moveColumn,\n moveFooterRow,\n putFooterCell,\n removeColumn,\n removeFooterCell,\n removeFooterRow,\n setGroup,\n setSort,\n updateColumn,\n updateFooterRow,\n} from './table.js'\n\nexport const COMMANDS = Object.freeze({\n setTitle,\n setLocale,\n setPage,\n replaceDocument,\n putStyle,\n removeStyle,\n putDataset,\n removeDataset,\n putField,\n removeField,\n putParameter,\n removeParameter,\n moveParameter,\n putAsset,\n removeAsset,\n putAggregate,\n removeAggregate,\n insertComponent,\n removeComponent,\n moveComponent,\n updateComponent,\n duplicateComponent,\n insertColumn,\n removeColumn,\n moveColumn,\n updateColumn,\n setGroup,\n setSort,\n insertFooterRow,\n removeFooterRow,\n moveFooterRow,\n updateFooterRow,\n putFooterCell,\n removeFooterCell,\n})\n\nexport type CommandName = keyof typeof COMMANDS\n\n/** A command's arguments after the report. */\ntype ArgumentsOf<F> = F extends (report: ReportDefinition, ...rest: infer A) => unknown ? A : never\n\n/** A command as data: its name and its arguments after the report, typed per command. */\nexport type CommandDescriptor = {\n readonly [N in CommandName]: { readonly command: N; readonly args: Readonly<ArgumentsOf<(typeof COMMANDS)[N]>> }\n}[CommandName]\n\nfunction isObject(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isLocation(value: unknown): boolean {\n return (\n isObject(value) &&\n (REGION_NAMES as readonly unknown[]).includes(value.region) &&\n typeof value.index === 'number' &&\n (value.parent === undefined || typeof value.parent === 'string') &&\n (value.column === undefined || typeof value.column === 'number')\n )\n}\n\n/**\n * What an argument read from JSON must be before its command runs, each\n * with the words a refusal says it in. Only what the command itself reads:\n * whether a string names something, or a number is a position in its list,\n * the command decides; a whole value it stores -- a component, a column, a\n * footer row, a dataset, a document -- the validator judges.\n */\nconst SHAPES = {\n text: { is: (value: unknown) => typeof value === 'string', said: 'a string' },\n index: { is: (value: unknown) => typeof value === 'number', said: 'a number' },\n object: { is: isObject, said: 'an object' },\n objectOrNull: { is: (value: unknown) => value === null || isObject(value), said: 'an object, or null to remove it' },\n listOrNull: { is: (value: unknown) => value === null || Array.isArray(value), said: 'a list, or null to remove it' },\n location: { is: isLocation, said: 'a location: a region, an index, and a parent id and a column where it names them' },\n role: { is: (value: unknown) => (DATASET_ROLES as readonly unknown[]).includes(value), said: \"'header' or 'detail'\" },\n footer: { is: (value: unknown) => value === 'totals' || value === 'groupFooter', said: \"'totals' or 'groupFooter'\" },\n value: { is: () => true, said: 'a value' },\n} as const\n\ntype Shape = keyof typeof SHAPES\n\n/**\n * The shape of each command's arguments after the report, in order. A\n * table over every command, so a command added to `COMMANDS` without its\n * shapes does not compile; a test holds each list to its command's length.\n */\nexport const ARGUMENTS: { readonly [N in CommandName]: readonly Shape[] } = {\n setTitle: ['text'],\n setLocale: ['text'],\n setPage: ['object'],\n replaceDocument: ['value'],\n putStyle: ['text', 'object'],\n removeStyle: ['text'],\n putDataset: ['role', 'value'],\n removeDataset: ['role'],\n putField: ['role', 'text', 'object'],\n removeField: ['role', 'text'],\n putParameter: ['text', 'object'],\n removeParameter: ['text'],\n moveParameter: ['text', 'index'],\n putAsset: ['text', 'object'],\n removeAsset: ['text'],\n putAggregate: ['text', 'object'],\n removeAggregate: ['text'],\n insertComponent: ['location', 'value'],\n removeComponent: ['text'],\n moveComponent: ['text', 'location'],\n updateComponent: ['text', 'text', 'object'],\n duplicateComponent: ['text'],\n insertColumn: ['text', 'index', 'value'],\n removeColumn: ['text', 'text'],\n moveColumn: ['text', 'text', 'index'],\n updateColumn: ['text', 'text', 'object'],\n setGroup: ['text', 'objectOrNull'],\n setSort: ['text', 'listOrNull'],\n insertFooterRow: ['text', 'footer', 'index', 'value'],\n removeFooterRow: ['text', 'footer', 'index'],\n moveFooterRow: ['text', 'footer', 'index', 'index'],\n updateFooterRow: ['text', 'footer', 'index', 'object'],\n putFooterCell: ['text', 'footer', 'index', 'object'],\n removeFooterCell: ['text', 'footer', 'index', 'text'],\n}\n\n/** Why `args` are not arguments `name` takes, or undefined when they are. Never quotes an argument. */\nfunction misfit(name: CommandName, args: unknown): string | undefined {\n const shapes = ARGUMENTS[name]\n if (!Array.isArray(args) || args.length !== shapes.length) {\n return `${name} takes ${shapes.length} ${shapes.length === 1 ? 'argument' : 'arguments'} after the report: ${shapes.map((shape) => SHAPES[shape].said).join('; ')}`\n }\n const wrong = shapes.findIndex((shape, index) => !SHAPES[shape].is(args[index]))\n return wrong === -1 ? undefined : `argument ${wrong + 1} of ${name} is not ${SHAPES[shapes[wrong] as Shape].said}`\n}\n\n/**\n * The command a descriptor names, bound to its arguments. A descriptor read\n * from JSON was never type-checked, so it is checked here: a name that is\n * not a command gives a command that refuses with `unknown-command`, and\n * arguments too few, too many or of a type the command cannot read give one\n * that refuses with `invalid-arguments`. Either way the descriptor never\n * throws. What the command makes of arguments of the right types reaches\n * the validator, as any edit's result does.\n */\nexport function describedCommand(descriptor: CommandDescriptor): Command {\n const { command, args } = descriptor as { readonly command: unknown; readonly args: unknown }\n if (typeof command !== 'string' || !Object.hasOwn(COMMANDS, command)) {\n const name = typeof command === 'string' ? quote(command) : 'a command with no name'\n return () => refuse('unknown-command', `${name} is not a command this package has`)\n }\n const name = command as CommandName\n const wrong = misfit(name, args)\n if (wrong !== undefined) return () => refuse('invalid-arguments', wrong)\n const run = COMMANDS[name] as (report: ReportDefinition, ...rest: unknown[]) => CommandOutcome\n return (report) => run(report, ...(args as unknown[]))\n}\n","/**\n * Several commands as one edit: the draft they run against, and the verdict\n * on where they leave it -- what a session's transaction commits, and what a\n * proposal's review shows before anybody applies it (plan 16).\n *\n * One draft and one verdict for both, so a preview and the commit that\n * follows it cannot disagree about what a proposal does\n * ([0008](../../../docs/decisions/0008-edits-are-commands-and-a-refused-edit-changes-nothing.md)).\n */\nimport { validateReport } from '@formancy/report-spec'\nimport type { ReportDefinition, ReportError } from '@formancy/report-spec'\nimport { describedCommand } from './commands/registry.js'\nimport type { CommandDescriptor } from './commands/registry.js'\nimport { refuse } from './outcome.js'\nimport type { Command, CommandOutcome, Refusal } from './outcome.js'\n\n/** The working document inside a transaction, and the way to edit it. */\nexport interface Draft {\n /** The document as the edits so far have left it, which need not be valid. */\n document(): ReportDefinition\n /** Runs a command against the draft. After a refusal nothing more runs: each later call gives that refusal. */\n apply<E extends object>(command: Command<E>): CommandOutcome<E>\n apply(descriptor: CommandDescriptor): CommandOutcome\n}\n\n/**\n * Whatever a draft's callback returns, so long as it is not a promise. An\n * await inside the callback would end the edit with half its steps run, so\n * an async callback does not compile, and a promise that reaches the edit\n * anyway is refused when it runs.\n */\nexport type Synchronous<R> = R & (R extends PromiseLike<unknown> ? never : unknown)\n\nexport function commandOf<E extends object>(command: Command<E> | CommandDescriptor): Command<E> {\n return typeof command === 'function' ? command : (describedCommand(command) as Command<E>)\n}\n\nfunction thenable(value: unknown): boolean {\n return (typeof value === 'object' || typeof value === 'function') && value !== null && typeof (value as { then?: unknown }).then === 'function'\n}\n\n/**\n * Runs `run` against a draft of `report`: where its commands leave the\n * report, not yet validated, or the first refusal. The draft ends when\n * `run` returns or throws, and reading or editing it after that throws.\n * Throws a TypeError, having run nothing to completion, when `run` returns\n * a promise.\n */\nexport function drafted<R>(report: ReportDefinition, run: (draft: Draft) => Synchronous<R>): CommandOutcome {\n let working = report\n let refused: Refusal | undefined\n let open = true\n const live = (): void => {\n if (!open) throw new Error('this edit has ended: its draft cannot be read or edited any more')\n }\n const draft: Draft = {\n document: () => {\n live()\n return working\n },\n apply: <E extends object>(command: Command<E> | CommandDescriptor): CommandOutcome<E> => {\n live()\n if (refused !== undefined) return refused\n const outcome = commandOf(command)(working)\n if (outcome.ok) working = outcome.report\n else refused = outcome\n return outcome\n },\n }\n let returned: unknown\n try {\n returned = run(draft)\n } finally {\n open = false\n }\n if (thenable(returned)) throw new TypeError('an edit runs synchronously: await before it, not inside it')\n return refused ?? { ok: true, report: working }\n}\n\n/** The refusal for a result the validator refused, pointing at its first error; it gives at least one. */\nfunction invalid(errors: readonly ReportError[]): Refusal {\n const first = errors[0] as ReportError\n return { ...refuse('invalid-document', `the edit would leave a report that is not valid: ${first.message}`, { path: first.path, componentId: first.componentId }), errors }\n}\n\n/** `candidate` as the validator's copy of it, or the refusal that carries the validator's errors. */\nexport function validated(candidate: unknown): CommandOutcome {\n const verdict = validateReport(candidate)\n return verdict.valid ? { ok: true, report: verdict.report } : invalid(verdict.errors)\n}\n\n/**\n * Runs several commands against `report` as a transaction would, and gives\n * the validated result -- the validator's copy -- or the first refusal, or\n * the validator's errors for an invalid end. Nothing is committed anywhere,\n * and `report` is left as it was. Throws as `drafted` does.\n */\nexport function tryEdit<R>(report: ReportDefinition, run: (draft: Draft) => Synchronous<R>): CommandOutcome {\n const outcome = drafted(report, run)\n return outcome.ok ? validated(outcome.report) : outcome\n}\n","/**\n * Snapshots: the frozen documents a session holds, and the mutable copies\n * it hands out.\n */\n\n/** A deeply mutable copy of a readonly type: what `exportDocument` returns. */\nexport type Mutable<T> = T extends readonly (infer U)[] ? Mutable<U>[] : T extends object ? { -readonly [K in keyof T]: Mutable<T[K]> } : T\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** The id an item of a list is known by, when it has one: a component's, a table column's, a declaration's. */\nfunction idOf(item: unknown): string | undefined {\n return isRecord(item) && typeof item.id === 'string' ? item.id : undefined\n}\n\n/**\n * What each item of `next` is compared with: the item of `before` with the\n * same id, so an insert, a remove or a move does not make everything after\n * it look changed; otherwise the item at the same position, for items that\n * have no id -- a column slot, a footer row, a cell, an inline run.\n */\nfunction counterparts(next: readonly unknown[], before: readonly unknown[]): unknown[] {\n const byId = new Map<string, unknown>()\n for (const item of before) {\n const id = idOf(item)\n if (id !== undefined && !byId.has(id)) byId.set(id, item)\n }\n return next.map((item, index) => {\n const id = idOf(item)\n return id !== undefined && byId.has(id) ? byId.get(id) : before[index]\n })\n}\n\nfunction settle(next: unknown, previous: unknown): unknown {\n if (typeof next !== 'object' || next === null) return next\n if (Array.isArray(next)) {\n const before: readonly unknown[] = Array.isArray(previous) ? previous : []\n const compared = counterparts(next, before)\n const items = next.map((item: unknown, index) => settle(item, compared[index]))\n const same = Array.isArray(previous) && before.length === items.length && items.every((item, index) => item === before[index])\n return same ? previous : Object.freeze(items)\n }\n const before = isRecord(previous) ? previous : undefined\n const entries = Object.keys(next).map((key) => [key, settle((next as Record<string, unknown>)[key], before?.[key])] as const)\n const same = before !== undefined && Object.keys(before).length === entries.length && entries.every(([key, value]) => Object.hasOwn(before, key) && before[key] === value)\n return same ? previous : Object.freeze(Object.fromEntries(entries))\n}\n\n/**\n * `next` as a deeply frozen snapshot that shares every subtree equal to its\n * counterpart in `previous`, itself a snapshot this made, or is `previous`\n * itself when the two are equal. An object's counterpart is the value under\n * the same key; a list item's is the item with the same id in the same list,\n * or the one at the same position when it has no id. Key order does not\n * count, as it does not in the canonical hash.\n *\n * So an edit leaves every component, column and declaration it did not\n * change as it was, wherever an insert, a remove or a move within its list\n * shifted it. A component moved into another list is compared with what\n * stood at its new position there, and is usually a new object.\n *\n * Built new, never by freezing `next` in place, so nothing a caller still\n * holds becomes frozen under it, and a caller's later write cannot reach\n * the snapshot. The sharing is what makes a history of whole-document\n * snapshots cost what its edits changed, and what lets a builder keep a\n * component's rendering while that component's object is the same.\n */\nexport function settled<T>(next: T, previous: unknown): T {\n return settle(next, previous) as T\n}\n\n/** A deep, mutable copy of JSON data. A snapshot is JSON by construction: the validator read it. */\nexport function thawed<T>(value: T): Mutable<T> {\n return JSON.parse(JSON.stringify(value)) as Mutable<T>\n}\n","/**\n * The report session: one document, its revision and its undo history,\n * shared by every view of it -- the React builder, the Angular builder, a\n * proposal being reviewed.\n *\n * It follows formancy's builder session (`@formancy/builder-core`), and\n * three rules shape it\n * ([0008](../../../docs/decisions/0008-edits-are-commands-and-a-refused-edit-changes-nothing.md)):\n *\n * - **It never holds a document the validator refuses.** Every edit is a\n * command run against the current document; its result is validated\n * whole, and only a valid result is committed. A refused edit changes\n * nothing: not the document, not its identity, not the revision, not the\n * history, and no listener hears of it.\n * - **A committed document is a frozen snapshot**, the same object until\n * the next commit, so `useSyncExternalStore` and Angular signals can\n * compare it by identity. What an edit did not change keeps its identity\n * too, matched by id within its list, so a view of one component redraws\n * only when that component changed or moved to another list.\n * - **History is snapshots.** Undo puts back the very document that was\n * there; an edit after an undo clears what could be redone.\n */\nimport { reportHash, validateReport } from '@formancy/report-spec'\nimport type { ReportDefinition, ReportError } from '@formancy/report-spec'\nimport type { CommandDescriptor } from './commands/registry.js'\nimport { commandOf, drafted, validated } from './draft.js'\nimport type { Draft, Synchronous } from './draft.js'\nimport { refuse } from './outcome.js'\nimport type { Command, CommandOutcome, Refusal } from './outcome.js'\nimport { settled, thawed } from './snapshot.js'\nimport type { Mutable } from './snapshot.js'\n\n/**\n * Undo steps a session keeps unless told otherwise; past it, the oldest is\n * dropped. Chosen, not measured: two hundred steps is longer than an\n * editing session's worth of undoing anyone does, and it bounds the\n * history's memory. A step holds a whole snapshot, but a snapshot shares\n * every part its edit did not change with the one before it, so a step\n * costs about what its edit changed -- except a component moved into\n * another list, which is copied with all it holds, and a replaced document,\n * which shares what happens to be equal and nothing else.\n */\nexport const DEFAULT_HISTORY_LIMIT = 200\n\n/** The label a step gets when the edit was given none and is not a descriptor. */\nconst UNLABELLED = 'edit'\n\nexport interface SessionOptions {\n /** Undo steps to keep; a whole number, 0 for none. DEFAULT_HISTORY_LIMIT when absent. */\n readonly historyLimit?: number\n}\n\nexport interface EditOptions {\n /** What the toolbar calls this step: \"Undo <label>\". A descriptor's command name, or 'edit', when absent. */\n readonly label?: string\n /** The hash of the document the edit was made against; an edit made against another is refused as stale. */\n readonly expectedHash?: string\n}\n\nexport interface ReportSession {\n /** The current document: frozen, and the same object until the next change. */\n document(): ReportDefinition\n /** Counts changes: one per committed edit, undo or redo. A refused edit, or one that changed nothing, is not one. */\n revision(): number\n /** `reportHash` of the current document, what a save or a proposal is bound to. */\n hash(): string\n /**\n * Calls `listener` after every change, synchronously, until the function\n * returned is called. A listener that throws does not stop the others;\n * once all have run, its error is thrown from the call that made the\n * change -- which has been made -- or an AggregateError when several threw.\n */\n subscribe(listener: () => void): () => void\n /**\n * Runs a command against the document and commits the result if the\n * validator accepts it. A command returns the next report and never edits\n * the session: one that calls the session while it runs throws.\n */\n apply<E extends object>(command: Command<E>, options?: EditOptions): CommandOutcome<E>\n apply(descriptor: CommandDescriptor, options?: EditOptions): CommandOutcome\n /**\n * Runs several commands as one edit: one undo step, one notification,\n * validated once at the end, so the draft may be invalid in between. A\n * refused command, or an invalid end, refuses the whole and changes\n * nothing; an exception thrown by `run` passes through, changing nothing.\n * `run` is synchronous: an async one does not compile, and a promise\n * returned anyway is refused with a TypeError before anything commits.\n * `tryEdit` gives the same verdict without committing.\n */\n transaction<R>(label: string, run: (draft: Draft) => Synchronous<R>, options?: Pick<EditOptions, 'expectedHash'>): CommandOutcome\n /** Takes a whole document -- a paste, an import, a proposal -- as one undoable edit, validated like any other. */\n replaceDocument(next: unknown, options?: EditOptions): CommandOutcome\n canUndo(): boolean\n canRedo(): boolean\n /** Puts back the document before the last step; false when there is none. */\n undo(): boolean\n /** Takes the last undone step again; false when there is none. */\n redo(): boolean\n /** The label of the step undo would take back. */\n undoLabel(): string | undefined\n /** The label of the step redo would take again. */\n redoLabel(): string | undefined\n /** A deep, mutable copy of the document, safe to hand to anything. */\n exportDocument(): Mutable<ReportDefinition>\n}\n\nexport type SessionOpening = { readonly ok: true; readonly session: ReportSession } | { readonly ok: false; readonly errors: readonly ReportError[] }\n\n/** A document in the history, and the label of the step that leads away from it. */\ninterface Step {\n readonly document: ReportDefinition\n readonly label: string\n}\n\n/** What the session is in the middle of, during which nothing may edit it: its own work is not done. */\nconst BUSY = {\n transaction: 'the session is in a transaction: edit the draft the transaction was given, and let it commit',\n command: 'the session is running a command: a command returns the next report, and never edits the session',\n} as const\n\n/**\n * A session over `document`, or the validator's reasons it is not a report\n * this package reads. Never throws on a bad document: a file a person\n * picked is an expected failure. Throws a RangeError for a history limit\n * that is not a whole number from 0.\n */\nexport function openReportSession(document: unknown, options: SessionOptions = {}): SessionOpening {\n const limit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT\n if (!Number.isInteger(limit) || limit < 0) throw new RangeError(`a history limit is a whole number of steps from 0, not ${String(limit)}`)\n const opened = validateReport(document)\n if (!opened.valid) return { ok: false, errors: opened.errors }\n\n let present: ReportDefinition = settled(opened.report, undefined)\n let revision = 0\n const past: Step[] = []\n const future: Step[] = []\n const subscriptions = new Set<{ readonly listener: () => void }>()\n const hashes = new WeakMap<ReportDefinition, string>()\n let busy: keyof typeof BUSY | undefined\n\n function notify(): void {\n const errors: unknown[] = []\n for (const subscription of [...subscriptions]) {\n // Unsubscribed by an earlier listener in this round: not called.\n if (!subscriptions.has(subscription)) continue\n try {\n subscription.listener()\n } catch (error) {\n errors.push(error)\n }\n }\n if (errors.length === 1) throw errors[0]\n if (errors.length > 1) throw new AggregateError(errors, `${errors.length} session listeners threw`)\n }\n\n function hash(): string {\n let known = hashes.get(present)\n if (known === undefined) {\n known = reportHash(present)\n hashes.set(present, known)\n }\n return known\n }\n\n function idle(): void {\n if (busy !== undefined) throw new Error(BUSY[busy])\n }\n\n /** `work`'s result, with the session refusing to be edited while it runs. */\n function during<T>(what: keyof typeof BUSY, work: () => T): T {\n busy = what\n try {\n return work()\n } finally {\n busy = undefined\n }\n }\n\n function stale(expectedHash: string | undefined): Refusal | undefined {\n if (expectedHash === undefined || expectedHash === hash()) return undefined\n return refuse('stale-document', 'the edit was made against a version of the report that has since changed')\n }\n\n /** Validates `candidate`, and commits it as one step unless it is refused or changes nothing. */\n function commit(candidate: unknown, label: string): CommandOutcome {\n const verdict = validated(candidate)\n if (!verdict.ok) return verdict\n const next = settled(verdict.report, present)\n if (next === present) return { ok: true, report: present }\n past.push({ document: present, label })\n if (past.length > limit) past.shift()\n future.length = 0\n present = next\n revision += 1\n notify()\n return { ok: true, report: next }\n }\n\n /** Moves one step from `from` to `to`, the present going the other way. */\n function step(from: Step[], to: Step[]): boolean {\n idle()\n const taken = from.pop()\n if (taken === undefined) return false\n to.push({ document: present, label: taken.label })\n present = taken.document\n revision += 1\n notify()\n return true\n }\n\n function apply<E extends object>(command: Command<E> | CommandDescriptor, options: EditOptions = {}): CommandOutcome<E> {\n idle()\n const refusal = stale(options.expectedHash)\n if (refusal !== undefined) return refusal\n const outcome = during('command', () => commandOf(command)(present))\n if (!outcome.ok) return outcome\n const label = options.label ?? (typeof command === 'function' ? UNLABELLED : command.command)\n const committed = commit(outcome.report, label)\n return committed.ok ? { ...outcome, report: committed.report } : committed\n }\n\n function transaction<R>(label: string, run: (draft: Draft) => Synchronous<R>, options: Pick<EditOptions, 'expectedHash'> = {}): CommandOutcome {\n idle()\n const refusal = stale(options.expectedHash)\n if (refusal !== undefined) return refusal\n const outcome = during('transaction', () => drafted(present, run))\n return outcome.ok ? commit(outcome.report, label) : outcome\n }\n\n const session: ReportSession = {\n document: () => present,\n revision: () => revision,\n hash,\n subscribe(listener) {\n const subscription = { listener }\n subscriptions.add(subscription)\n return () => {\n subscriptions.delete(subscription)\n }\n },\n apply,\n transaction,\n replaceDocument(next, options = {}) {\n idle()\n return stale(options.expectedHash) ?? commit(next, options.label ?? 'replaceDocument')\n },\n canUndo: () => past.length > 0,\n canRedo: () => future.length > 0,\n undo: () => step(past, future),\n redo: () => step(future, past),\n undoLabel: () => past.at(-1)?.label,\n redoLabel: () => future.at(-1)?.label,\n exportDocument: () => thawed(present),\n }\n return { ok: true, session }\n}\n","/**\n * Where a component stands, every place one could go, and the places one\n * may go: what a builder needs for a drop target, a keyboard move and focus\n * after a deletion (plan 8, plan 21's \"valid drop destinations\").\n *\n * Where a component may stand is the validator's to decide (0007): a page\n * counter only in the page header and footer, a table never inside columns.\n * So the destinations are found by asking it, place by place, rather than\n * by a second copy of its placement rules that could disagree with it.\n */\nimport { REGION_NAMES, validateReport, walkComponents } from '@formancy/report-spec'\nimport type { Component, RegionName, ReportDefinition } from '@formancy/report-spec'\nimport { insertComponent, moveComponent, removeComponent } from './commands/components.js'\nimport type { CommandOutcome } from './outcome.js'\nimport { heldLists, standing } from './tree.js'\nimport type { Location } from './tree.js'\n\n/** A columns block's list: the pointer to the block, and the column. */\nconst SLOT = /^(.*)\\/columns\\/(\\d+)\\/components$/\n\n/**\n * Where the component `id` stands, as the location `moveComponent` and\n * `insertComponent` take: a move to it puts the component back where it\n * was. Undefined when the report has no such component.\n */\nexport function locationOf(report: ReportDefinition, id: string): Location | undefined {\n const all = walkComponents(report)\n const found = all.find(({ component }) => component.id === id)\n if (found === undefined) return undefined\n const { pointer, index } = standing(found.path)\n if (pointer === `/regions/${found.region}`) return { region: found.region, index }\n // Inside a container: a columns block's column, or another container's\n // one list, under `components`.\n const slot = SLOT.exec(pointer)\n const parentPath = slot === null ? pointer.slice(0, -'/components'.length) : (slot[1] as string)\n const parent = all.find(({ path }) => path === parentPath)?.component.id as string\n return { region: found.region, parent, ...(slot === null ? {} : { column: Number(slot[2]) }), index }\n}\n\n/**\n * Every place a component could be put, in reading order: before each\n * component and at the end of each list, a container's places right after\n * the place before the container. Each is a location `insertComponent`\n * takes; whether the validator accepts what is put there is\n * `validLocations`' question.\n */\nexport function locations(report: ReportDefinition): Location[] {\n const found: Location[] = []\n const visit = (region: RegionName, list: readonly Component[], place: Omit<Location, 'region' | 'index'>): void => {\n for (const [index, component] of list.entries()) {\n found.push({ region, ...place, index })\n for (const { column, list: held } of heldLists(component)) visit(region, held, { parent: component.id, ...(column === undefined ? {} : { column }) })\n }\n found.push({ region, ...place, index: list.length })\n }\n for (const region of REGION_NAMES) visit(region, report.regions[region], {})\n return found\n}\n\n/**\n * The places `subject` may go, in reading order: for a new component, each\n * location where inserting it gives a report the validator accepts; for the\n * id of one the report holds, each location a move of it to gives one --\n * read, as `moveComponent` reads it, in the report without it. None for an\n * id the report lacks, or a component no place accepts, such as a second\n * detail table or one whose id is taken.\n *\n * It validates the whole report once per place, so its cost is the\n * report's size times its number of places: a builder asks it when a drag\n * starts, not on every pointer move.\n */\nexport function validLocations(report: ReportDefinition, subject: Component | string): Location[] {\n if (typeof subject !== 'string') return acceptedOf(locations(report), (location) => insertComponent(report, location, subject))\n const without = removeComponent(report, subject)\n return without.ok ? acceptedOf(locations(without.report), (location) => moveComponent(report, subject, location)) : []\n}\n\n/** The candidates where `put` gives a report the validator accepts. */\nfunction acceptedOf(candidates: readonly Location[], put: (location: Location) => CommandOutcome): Location[] {\n return candidates.filter((location) => {\n const outcome = put(location)\n return outcome.ok && validateReport(outcome.report).valid\n })\n}\n","/**\n * What the diagnostics can say about a valid report, as stable codes, each\n * with the severity it always has.\n *\n * A diagnostic is not a validation error. The report it is about is valid:\n * the session holds nothing else. An error here is one the runtime will\n * refuse to render -- an expression that does not compile, or reads\n * something that is not there -- which plan 15 puts at its second level, the\n * bindings; a warning is something an author probably did not mean, and\n * renders as written.\n */\nimport type { SourceSpan } from '@formancy/expressions'\n\nexport const DIAGNOSTIC_SEVERITIES = {\n /** An expression that does not parse. */\n 'expression-syntax': 'error',\n /** An expression past a structural limit of `@formancy/expressions`: too deep, too many nodes, too long a list. */\n 'expression-limit': 'error',\n /** An expression whose types do not meet, each member read as the type it is declared: an integer parameter added to a string, a decimal field compared with an integer, a decimal converted with dec() again. */\n 'expression-type': 'error',\n /** An expression its place does not allow: a condition that is not a boolean, a function its kind forbids. */\n 'expression-policy': 'error',\n /** An expression that reads a name, or a member of one, that nothing declares, or a member of a single value. */\n 'expression-unknown-name': 'error',\n /** An expression that reads `row` or `group` where there is no row or group. */\n 'expression-out-of-scope': 'error',\n /** An expression that reads an image field, which is drawn and never read. */\n 'expression-unreadable-field': 'error',\n /** An expression that calls the clock or a random draw, so two renders of the same data could differ. */\n 'expression-not-reproducible': 'error',\n /** An expression that computes with a double, which is not exact, or divides with `/`, which on integers drops the remainder: `dec(\"…\")` and `divide(dec(a), dec(b), places)` keep a number exact. */\n 'expression-inexact': 'error',\n /** An expression that calls `matches()`, whose backtracking pattern can run for as long as it likes inside one step of the budget. */\n 'expression-unbounded': 'error',\n /** An expression that reads a name whole -- `size(params)`, `row[key]` -- rather than a member by its id: what it reads cannot be checked, and is never bound. */\n 'expression-dynamic-read': 'error',\n /** An aggregate's expression that gives a value its function cannot total: a sum of strings, an average of instants. */\n 'expression-aggregate-type': 'error',\n /** An aggregate whose expression reads its own total, directly or through other aggregates, or reads one that does: none of them can be computed. */\n 'aggregate-cycle': 'error',\n /** A number or currency format that prints a total at fewer places than its declared rounding keeps, so the total is rounded twice and the second rounding ignores the declared mode. */\n 'format-rounds-again': 'error',\n /** A rounding declared on an aggregate that computes an integer, a date or an instant, which have no places to round: the runtime refuses it. */\n 'rounding-not-decimal': 'error',\n /** A print style nothing uses. */\n 'unused-style': 'warning',\n /** An asset nothing draws. */\n 'unused-asset': 'warning',\n /** A parameter nothing prints or reads: the person rendering is asked for it for nothing. */\n 'unused-parameter': 'warning',\n /** A dataset field nothing prints, draws, orders by, totals or reads: the provider fetches it for nothing. */\n 'unused-field': 'warning',\n /** An aggregate nothing prints or reads: computed over every row for nothing. */\n 'unused-aggregate': 'warning',\n /** A report whose body holds nothing. */\n 'empty-body': 'warning',\n /** A text that prints nothing: no runs, or only empty literal ones. */\n 'empty-text': 'warning',\n} as const satisfies Readonly<Record<string, 'error' | 'warning'>>\n\nexport type DiagnosticCode = keyof typeof DIAGNOSTIC_SEVERITIES\n\nexport type DiagnosticSeverity = (typeof DIAGNOSTIC_SEVERITIES)[DiagnosticCode]\n\nexport const DIAGNOSTIC_CODES = Object.keys(DIAGNOSTIC_SEVERITIES) as readonly DiagnosticCode[]\n\nexport interface Diagnostic {\n readonly severity: DiagnosticSeverity\n readonly code: DiagnosticCode\n /** For a person: what is wrong, in the author's terms. */\n readonly message: string\n /** A JSON Pointer to what it is about: an expression's `cel`, a declaration, a list. */\n readonly path: string\n /** The innermost component it is about, when it is about one. */\n readonly componentId?: string\n /** For an expression in a table's column, the column's id: its value, its condition or a style rule of it. */\n readonly columnId?: string\n /** For an expression, the characters of its source it is about, half-open. */\n readonly position?: SourceSpan\n /** For an expression, what `@formancy/expressions` suggests writing instead, when it suggests something. */\n readonly hint?: string\n}\n\n/** Where a diagnostic points, besides its path. */\nexport interface Where {\n readonly path: string\n readonly componentId?: string | undefined\n readonly columnId?: string | undefined\n readonly position?: SourceSpan | undefined\n readonly hint?: string | undefined\n}\n\nexport function diagnostic(code: DiagnosticCode, message: string, where: Where): Diagnostic {\n return {\n severity: DIAGNOSTIC_SEVERITIES[code],\n code,\n message,\n path: where.path,\n ...(where.componentId === undefined ? {} : { componentId: where.componentId }),\n ...(where.columnId === undefined ? {} : { columnId: where.columnId }),\n ...(where.position === undefined ? {} : { position: where.position }),\n ...(where.hint === undefined ? {} : { hint: where.hint }),\n }\n}\n","/**\n * The parts of a report the diagnostics read: every expression, with the\n * scope its place gives it and what it is for, and every style, asset,\n * field, parameter and aggregate named outside an expression.\n *\n * One walk, so that where an expression stands is decided once: the\n * diagnostics and `compileReport`, which the runtime compiles a report with,\n * both take its sites from here.\n */\nimport { walkComponents } from '@formancy/report-spec'\nimport type { Component, ComponentKind, Expression, FieldRef, Format, Inline, ReportDefinition, StyleRule, TableFooterRow, ValueScope } from '@formancy/report-spec'\n\n/** An expression and how to compile it: the names its scope binds, and the policy of what it is for. */\nexport interface ExpressionSite {\n readonly cel: string\n readonly scope: ValueScope\n /** `visible` for a condition, which must be a boolean; `computed` for a value printed. */\n readonly kind: 'visible' | 'computed'\n /** The JSON Pointer to the expression's `cel`. */\n readonly path: string\n /** The innermost component it stands in; none for an aggregate's. */\n readonly componentId?: string\n /** The table column it belongs to, for a column's value, condition or style rule. */\n readonly columnId?: string\n}\n\n/** What an expression belongs to: a component, and within a table a column. */\ninterface Owner {\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/** An aggregate printed with a number or currency format: where, and at how many places. */\nexport interface PrintedTotal {\n readonly aggregate: string\n readonly scale: number\n /** The JSON Pointer to the format. */\n readonly path: string\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/** Everything the report names, outside expressions, and every expression. */\nexport interface ReportParts {\n readonly expressions: readonly ExpressionSite[]\n /** Every aggregate printed with a format that rounds, in document order. */\n readonly printedTotals: readonly PrintedTotal[]\n readonly styles: readonly string[]\n readonly assets: readonly string[]\n readonly fields: readonly FieldRef[]\n readonly parameters: readonly string[]\n readonly aggregates: readonly string[]\n}\n\n/** What one walk collects into, and the places it is collecting from. */\nclass Collector {\n readonly expressions: ExpressionSite[] = []\n readonly printedTotals: PrintedTotal[] = []\n readonly styles: string[] = []\n readonly assets: string[] = []\n readonly fields: FieldRef[] = []\n readonly parameters: string[] = []\n readonly aggregates: string[] = []\n\n expression(expression: Expression | undefined, path: string, scope: ValueScope, kind: ExpressionSite['kind'], owner: Owner = {}): void {\n if (expression === undefined) return\n this.expressions.push({ cel: expression.cel, scope, kind, path: `${path}/cel`, ...owner })\n }\n\n style(style: string | undefined): void {\n if (style !== undefined) this.styles.push(style)\n }\n\n /** Style rules: each a condition read in `scope`, and a style. */\n rules(rules: readonly StyleRule[] | undefined, path: string, scope: ValueScope, owner: Owner): void {\n for (const [index, rule] of (rules ?? []).entries()) {\n this.expression(rule.when, `${path}/${index}/when`, scope, 'visible', owner)\n this.style(rule.style)\n }\n }\n\n format(format: Format | undefined): void {\n if (format?.kind !== 'currency') return\n if (format.currency.kind === 'field') this.fields.push(format.currency.field)\n if (format.currency.kind === 'parameter') this.parameters.push(format.currency.parameter)\n }\n\n inline(inline: Inline, path: string, scope: ValueScope, owner: Owner): void {\n if (inline.kind === 'field') this.fields.push(inline.field)\n if (inline.kind === 'parameter') this.parameters.push(inline.parameter)\n if (inline.kind === 'aggregate') this.aggregates.push(inline.aggregate)\n if (inline.kind === 'aggregate' && (inline.format?.kind === 'number' || inline.format?.kind === 'currency')) {\n this.printedTotals.push({ aggregate: inline.aggregate, scale: inline.format.scale, path: `${path}/format`, ...owner })\n }\n if (inline.kind === 'expression') this.expression(inline.expression, `${path}/expression`, scope, 'computed', owner)\n if ('format' in inline) this.format(inline.format)\n }\n\n inlines(inlines: readonly Inline[], path: string, scope: ValueScope, owner: Owner): void {\n for (const [index, inline] of inlines.entries()) this.inline(inline, `${path}/${index}`, scope, owner)\n }\n\n footer(rows: readonly TableFooterRow[] | undefined, path: string, scope: ValueScope, owner: Owner): void {\n for (const [index, row] of (rows ?? []).entries()) {\n for (const [at, cell] of row.cells.entries()) this.inline(cell.value, `${path}/${index}/cells/${at}/value`, scope, owner)\n this.style(row.style)\n }\n }\n}\n\ntype Reader<K extends ComponentKind> = (component: Extract<Component, { kind: K }>, path: string, into: Collector) => void\n\nconst NOTHING = (): void => undefined\n\n/**\n * What each kind holds beyond what every component has. A table over every\n * kind, so a kind added to the format without saying what it names does not\n * compile. What a container holds is visited by the walk itself.\n */\nconst READERS: { readonly [K in ComponentKind]: Reader<K> } = {\n text: (text, path, into) => into.inlines(text.content, `${path}/content`, 'report', { componentId: text.id }),\n image: (image, _path, into) => {\n if (image.source.kind === 'asset') into.assets.push(image.source.asset)\n else into.fields.push(image.source.field)\n },\n line: NOTHING,\n rectangle: NOTHING,\n spacer: NOTHING,\n columns: NOTHING,\n section: NOTHING,\n pageBreak: NOTHING,\n keepTogether: NOTHING,\n table: (table, path, into) => {\n into.style(table.headerStyle)\n for (const [index, column] of table.columns.entries()) {\n const at = `${path}/columns/${index}`\n const owner = { componentId: table.id, columnId: column.id }\n // A column's value and style rules are read per row; whether it shows\n // is read once per report.\n into.inline(column.value, `${at}/value`, 'row', owner)\n into.expression(column.visibleWhen, `${at}/visibleWhen`, 'report', 'visible', owner)\n into.style(column.style)\n into.rules(column.styleWhen, `${at}/styleWhen`, 'row', owner)\n }\n const owner = { componentId: table.id }\n for (const key of table.sort ?? []) into.fields.push(key.field)\n if (table.group !== undefined) {\n into.fields.push(table.group.by)\n into.inlines(table.group.header, `${path}/group/header`, 'group', owner)\n into.style(table.group.headerStyle)\n into.footer(table.group.footer, `${path}/group/footer`, 'group', owner)\n }\n into.footer(table.totals, `${path}/totals`, 'report', owner)\n },\n}\n\n/** Every expression and every name the report holds, in document order, the aggregates' expressions last. */\nexport function reportParts(report: ReportDefinition): ReportParts {\n const into = new Collector()\n for (const { component, path } of walkComponents(report)) {\n const owner = { componentId: component.id }\n into.expression(component.visibleWhen, `${path}/visibleWhen`, 'report', 'visible', owner)\n into.style(component.style)\n into.rules(component.styleWhen, `${path}/styleWhen`, 'report', owner)\n ;(READERS[component.kind] as Reader<ComponentKind>)(component as never, path, into)\n }\n for (const [index, aggregate] of report.aggregates.entries()) {\n // What an aggregate reads, it reads from each detail row.\n if (aggregate.of?.kind === 'field') into.fields.push(aggregate.of.field)\n if (aggregate.of?.kind === 'expression') into.expression(aggregate.of.expression, `/aggregates/${index}/of/expression`, 'row', 'computed')\n }\n return into\n}\n\n/** Every expression in the report, each with the scope it is compiled in and what it is for. */\nexport function expressionSites(report: ReportDefinition): readonly ExpressionSite[] {\n return reportParts(report).expressions\n}\n","/**\n * Calls a report expression may not make: the clock and a random draw.\n *\n * A report rendered twice from the same data and parameters prints the\n * same thing (plan 15), so a reviewer's preview is the customer's PDF and a\n * published version renders as it was approved. `@formancy/expressions`\n * allows `now()` and `today()` in every kind of expression and `random()`\n * in a computed one, because a form captures them with its submission; a\n * report has nothing to capture them in. A date the report needs is a\n * parameter.\n *\n * Its parsed expression is opaque, and no kind's policy forbids the clock,\n * so the calls are found by asking its compiler: each place the name is\n * written as a whole word is renamed, keeping its length, to a function\n * that does not exist. Where the rename makes the compiler refuse an\n * unknown function at exactly that place, the expression called the\n * function there. Everything else -- a string, a member, a comprehension's\n * local -- compiles as before, or fails elsewhere. A generic way to ask\n * which functions an expression calls belongs upstream, and replaces this\n * when it is released.\n */\nimport { compile } from '@formancy/expressions'\nimport type { ExpressionKind, SourceSpan, VariableDeclarations } from '@formancy/expressions'\n\n/** The functions whose value is not a function of the report's data. */\nexport const UNREPRODUCIBLE_FUNCTIONS = ['now', 'today', 'random'] as const\n\nexport type UnreproducibleFunction = (typeof UNREPRODUCIBLE_FUNCTIONS)[number]\n\n/** The code `@formancy/expressions` gives a call to a function that has no overload, an unknown one included. */\nexport const UNKNOWN_FUNCTION = 'no_matching_overload'\n\nconst WORD = /[A-Za-z0-9_]/\n\n/** Whether `name` at `at` stands alone, not as part of a longer name. */\nfunction whole(source: string, at: number, name: string): boolean {\n return !WORD.test(source.charAt(at - 1)) && !WORD.test(source.charAt(at + name.length))\n}\n\n/**\n * Each call in `source` -- an expression that compiles, of `kind`, against\n * `variables` -- to a function that would make a render unrepeatable, in\n * the order they are written, with the span of the call.\n */\nexport function unreproducibleCalls(source: string, kind: ExpressionKind, variables: VariableDeclarations): { readonly name: UnreproducibleFunction; readonly span: SourceSpan }[] {\n const found: { readonly name: UnreproducibleFunction; readonly span: SourceSpan }[] = []\n for (const name of UNREPRODUCIBLE_FUNCTIONS) {\n for (let at = source.indexOf(name); at !== -1; at = source.indexOf(name, at + 1)) {\n if (!whole(source, at, name)) continue\n const probe = compile(`${source.slice(0, at)}_${source.slice(at + 1)}`, { kind, variables })\n if (!probe.ok && probe.error.code === UNKNOWN_FUNCTION && probe.error.position?.start === at) found.push({ name, span: probe.error.position })\n }\n }\n return found.sort((a, b) => a.span.start - b.span.start)\n}\n","/**\n * Arithmetic a report expression may not do, and a call whose time nothing\n * bounds.\n *\n * - **A double.** A report's numbers are exact: integers, and decimals from\n * strings (formancy.ai-data 0008). A double is not, and `int()` of one\n * hands back an integer the runtime cannot tell from an exact one:\n * `int(double(\"4.35\") * 100.0)` is 434. Every double comes in through a\n * literal (`100.0`, `1e3`) or `double()`, since the data binds none.\n * - **Division with `/`.** On integers it drops the remainder -- 3 / 2 is\n * 1, -3 / 2 is -1 -- a rounding nobody declared. Decimals have no `/`,\n * and doubles are refused, so every `/` that compiles divides integers.\n * `divide(dec(a), dec(b), places)` rounds where it says, half away from\n * zero. A remainder, `%`, is exact, and allowed.\n * - **`matches()`.** It runs its pattern on JavaScript's backtracking\n * engine, and one call is a few steps of upstream's budget however long\n * it runs: no budget bounds it, and a render cannot be interrupted while\n * it runs.\n *\n * The parsed expression is opaque, so each is found by asking the parser\n * and the compiler, as `reproducible.ts` finds the clock: a candidate is\n * spelled differently where it stands, and the probe sees whether that\n * changes the outcome there. A character no CEL token has makes a syntax\n * error exactly where it stands, unless it stands in a string or a comment;\n * a renamed function makes the call fail. So text that only looks like a\n * double, a division or a call is never one. A generic way to ask an\n * expression's types and calls belongs upstream, and replaces this when it\n * is released.\n */\nimport { compile, parse } from '@formancy/expressions'\nimport type { ExpressionKind, SourceSpan, VariableDeclarations } from '@formancy/expressions'\nimport { UNKNOWN_FUNCTION } from './reproducible.js'\n\nexport type InexactKind = 'double-literal' | 'double-call' | 'integer-division'\n\nexport interface Found<K> {\n readonly kind: K\n readonly span: SourceSpan\n}\n\n/** A CEL float literal: digits, a point and digits, or digits and an exponent; never part of a name or of a hex literal. */\nconst FLOAT = /(?<![A-Za-z0-9_.])(?:\\d+\\.\\d+(?:[eE][+-]?\\d+)?|\\d+[eE][+-]?\\d+)(?![A-Za-z0-9_])/g\n\n/** A character no CEL token has. */\nconst FOREIGN = '@'\n\n/** Whether the `length` characters at `at` are part of the expression, not of a string or a comment: spelled as a foreign character, they make a syntax error there. */\nfunction inCode(source: string, at: number, length: number): boolean {\n const probe = parse(`${source.slice(0, at)}${FOREIGN}${' '.repeat(length - 1)}${source.slice(at + length)}`)\n return !probe.ok && probe.error.kind === 'syntax' && probe.error.position?.start === at\n}\n\nconst WORD = /[A-Za-z0-9_]/\n\n/**\n * Each call in `source` -- which compiles, of `kind`, against `variables` --\n * to the function `name`, by function or method, with the span the compiler\n * gives the call once the function is renamed to one that does not exist.\n */\nfunction callsTo(name: string, source: string, kind: ExpressionKind, variables: VariableDeclarations): SourceSpan[] {\n const spans: SourceSpan[] = []\n for (let at = source.indexOf(name); at !== -1; at = source.indexOf(name, at + 1)) {\n if (WORD.test(source.charAt(at - 1)) || WORD.test(source.charAt(at + name.length))) continue\n const probe = compile(`${source.slice(0, at)}_${source.slice(at + 1)}`, { kind, variables })\n const span = probe.ok ? undefined : probe.error.position\n if (!probe.ok && probe.error.code === UNKNOWN_FUNCTION && span !== undefined && span.start <= at && at < span.end) spans.push(span)\n }\n return spans\n}\n\n/**\n * Each double literal, call to `double()` and division in `source`, an\n * expression that compiles, of `kind`, against `variables`, in the order\n * they are written.\n */\nexport function inexactOperations(source: string, kind: ExpressionKind, variables: VariableDeclarations): Found<InexactKind>[] {\n const found: Found<InexactKind>[] = callsTo('double', source, kind, variables).map((span) => ({ kind: 'double-call', span }))\n for (const literal of source.matchAll(FLOAT)) {\n if (inCode(source, literal.index, literal[0].length)) found.push({ kind: 'double-literal', span: { start: literal.index, end: literal.index + literal[0].length } })\n }\n for (let at = source.indexOf('/'); at !== -1; at = source.indexOf('/', at + 1)) {\n // Two slashes start a comment, or stand in a string; never a division.\n if (source.charAt(at - 1) === '/' || source.charAt(at + 1) === '/') continue\n if (inCode(source, at, 1)) found.push({ kind: 'integer-division', span: { start: at, end: at + 1 } })\n }\n return found.sort((a, b) => a.span.start - b.span.start)\n}\n\n/** The functions whose time no step budget bounds. */\nexport const UNBOUNDED_FUNCTIONS = ['matches'] as const\n\n/** Each call in `source` to a function whose time no budget bounds, in the order written. */\nexport function unboundedCalls(source: string, kind: ExpressionKind, variables: VariableDeclarations): { readonly name: (typeof UNBOUNDED_FUNCTIONS)[number]; readonly span: SourceSpan }[] {\n return UNBOUNDED_FUNCTIONS.flatMap((name) => callsTo(name, source, kind, variables).map((span) => ({ name, span }))).sort((a, b) => a.span.start - b.span.start)\n}\n","/**\n * Where in its source an expression reads a path, for the editor to\n * underline.\n *\n * `@formancy/expressions` gives spans only on its errors, and a read of a\n * member nothing declares is caught here, before it compiles. It does\n * splice: its `rewritePath` replaces exactly the characters of each read,\n * verified by parsing the result again. So a read is where such a rewrite\n * put its replacement -- the real parser's answer, not a second one.\n */\nimport { rewritePath } from '@formancy/expressions'\nimport type { SourceSpan } from '@formancy/expressions'\n\nconst LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n/** CEL's reserved words of two letters, which no identifier may be. */\nconst RESERVED = new Set(['as', 'if', 'in'])\n\n/**\n * A name `source` does not contain anywhere, to mark each read with: one\n * letter, or two different ones. Absent from the source, no local of a\n * comprehension can capture it, and no text of the source can be taken\n * for it; two different letters cannot overlap themselves, so splitting on\n * the mark finds each one. A source of at most 1,024 characters has fewer\n * pairs than there are, so there is always one.\n */\nfunction markFor(source: string): string {\n for (const letter of LETTERS) if (!source.includes(letter)) return letter\n for (const first of LETTERS) {\n for (const second of LETTERS) {\n const mark = `${first}${second}`\n if (first !== second && !RESERVED.has(mark) && !source.includes(mark)) return mark\n }\n }\n throw new RangeError('no two letters are absent from this expression; it is longer than any expression a report holds')\n}\n\n/**\n * The characters of `source` that read `path`, each read on its own,\n * half-open, in order. None when the source does not parse or does not\n * read the path.\n *\n * Each read is at least as long as the path written plainly -- an index or\n * spaces only add to it -- so when the reads together are exactly that\n * long, every read is written plainly and each one's place is known. When\n * one is not, the reads cannot be told apart by length, and one span from\n * the first read to the last covers them all.\n */\nexport function readSpans(source: string, path: string): SourceSpan[] {\n const mark = markFor(source)\n const rewritten = rewritePath(source, path, mark)\n if (!rewritten.ok || !rewritten.changed) return []\n const pieces = rewritten.source.split(mark)\n const reads = pieces.length - 1\n const between = pieces.reduce((length, piece) => length + piece.length, 0)\n if (source.length - between !== reads * path.length) {\n return [{ start: (pieces[0] as string).length, end: source.length - (pieces.at(-1) as string).length }]\n }\n const spans: SourceSpan[] = []\n let at = 0\n for (const piece of pieces.slice(0, -1)) {\n at += piece.length\n spans.push({ start: at, end: at + path.length })\n at += path.length\n }\n return spans\n}\n","/**\n * One expression compiled where it stands, with every member it reads\n * checked as the type it is.\n *\n * `@formancy/expressions` 0.5.0 declares a variable only by its whole name:\n * a declaration of `row.amount` is a variable with a dot in its name, which\n * an expression reading `row.amount` never finds. So each read of a member\n * is spliced, by upstream's own `rewritePath`, which verifies every splice\n * by parsing the result again, into a read of one variable -- `row.amount`\n * becomes `row_amount` -- declared with the member's type. The real checker\n * then types every member read: a decimal meets a decimal, an integer added\n * to a string is refused. The flat name is exactly as long as the read\n * written plainly, so a position the compiler gives is a position in what\n * the author wrote.\n *\n * What a scope does not bind, a member nothing declares, a member of a\n * single value and an image field read as a value are found first, from\n * the paths the parser says the expression reads. The clock and a random\n * draw, which the compiler allows, are refused last (plan 15).\n */\nimport { compile, parse, referencedPaths, rewritePath } from '@formancy/expressions'\nimport type { DeclaredType, ExpressionError, ExpressionErrorKind, Program, SourceSpan, VariableDeclarations } from '@formancy/expressions'\nimport { EXPRESSION_NAMES, VALUE_SCOPES } from '@formancy/report-spec'\nimport type { ValueScope } from '@formancy/report-spec'\nimport { diagnostic } from '../diagnostics/codes.js'\nimport type { Diagnostic, DiagnosticCode, Where } from '../diagnostics/codes.js'\nimport type { ExpressionSite } from '../diagnostics/parts.js'\nimport { quote } from '../outcome.js'\nimport { inexactOperations, unboundedCalls } from './exactness.js'\nimport type { InexactKind } from './exactness.js'\nimport type { Members, ScopeName } from './members.js'\nimport { unreproducibleCalls } from './reproducible.js'\nimport { readSpans } from './spans.js'\n\n/** A member an expression reads, and how the runtime binds it. */\nexport interface ExpressionRead {\n /** The name and the member as the expression writes them: `row` and `amount` for `row.amount`. */\n readonly name: ScopeName\n readonly member: string\n /** The variable the program reads it as, and `expressionValues` binds it under: `row_amount`. */\n readonly variable: string\n /** The type it is bound as, and checked as unless it may be null. */\n readonly type: DeclaredType\n readonly nullable: boolean\n}\n\n/** An expression that compiled clean: what the runtime evaluates, and what it reads. */\nexport interface CompiledExpression {\n readonly site: ExpressionSite\n /** Compiled from the expression with each member read spliced into its variable; evaluate it with `expressionValues`. */\n readonly program: Program\n readonly reads: readonly ExpressionRead[]\n}\n\nexport type SiteOutcome = { readonly ok: true; readonly compiled: CompiledExpression } | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] }\n\n/** The image fields each name holds, which nothing reads. */\nexport type Images = { readonly [N in ScopeName]?: ReadonlySet<string> }\n\n/**\n * The code for each kind of error the compiler gives. It gives the first\n * four when compiling; `runtime` and `budget` are evaluation's, mapped to\n * the nearest so the table is total.\n */\nconst BY_KIND: { readonly [K in ExpressionErrorKind]: DiagnosticCode } = {\n syntax: 'expression-syntax',\n limit: 'expression-limit',\n type: 'expression-type',\n policy: 'expression-policy',\n runtime: 'expression-type',\n budget: 'expression-limit',\n}\n\n/** Where each scope's own names have a value, for a message. */\nconst WHERE: { readonly [S in ValueScope]: string } = {\n report: 'every part of the report',\n group: \"a group's header and footer\",\n row: \"a table's cells and what an aggregate reads from each row\",\n}\n\n/** What each name's members are, for a message about one it lacks. */\nconst MEMBERS_ARE: { readonly [N in ScopeName]: string } = {\n params: 'parameter',\n header: 'field of the header dataset',\n row: 'field of the detail dataset',\n totals: 'aggregate',\n group: 'aggregate',\n}\n\n/** A read path's parts: the name it starts with, the member a dot names after it, and anything else after that. */\nexport interface PathParts {\n readonly name: string\n /** The member, when the name is followed by `.` and an identifier; undefined for a whole read, or one by a key no member could have. */\n readonly member?: string\n /** What follows the name, or the member when there is one: '' when nothing does. */\n readonly rest: string\n}\n\nconst NAME = /^[A-Za-z_][A-Za-z0-9_]*/\n\n/**\n * `path` -- as `referencedPaths` gives one: `row.amount`, `params`, or\n * `row[\"a.b\"]` for a key that is no identifier -- taken apart. A member's\n * id is a field key, an identifier (0007), so a read by any other key reads\n * no member.\n */\nexport function pathParts(path: string): PathParts {\n // Every path upstream gives starts with the name it reads.\n const name = (NAME.exec(path) as RegExpExecArray)[0]\n const after = path.slice(name.length)\n const member = after.startsWith('.') ? NAME.exec(after.slice(1))?.[0] : undefined\n return member === undefined ? { name, rest: after } : { name, member, rest: after.slice(1 + member.length) }\n}\n\nfunction failed(diagnostics: readonly Diagnostic[]): SiteOutcome {\n return { ok: false, diagnostics }\n}\n\n/** Where a diagnostic about `site` points. */\nfunction at(site: ExpressionSite, position?: SourceSpan, hint?: string): Where {\n return { path: site.path, componentId: site.componentId, columnId: site.columnId, position, hint }\n}\n\n/** One diagnostic per place `source` reads `path`, or one with no place when the reads cannot be found. */\nfunction eachRead(site: ExpressionSite, path: string, code: DiagnosticCode, message: string): Diagnostic[] {\n const spans = readSpans(site.cel, path)\n return spans.length === 0 ? [diagnostic(code, message, at(site))] : spans.map((span) => diagnostic(code, message, at(site, span)))\n}\n\n/** The diagnostics for a read of `path` that the scope's names and their members do not allow; none for one they do. */\nfunction readProblems(site: ExpressionSite, path: string, members: Members, images: Images): Diagnostic[] {\n const { name, member, rest } = pathParts(path)\n if (!EXPRESSION_NAMES[site.scope].includes(name)) {\n const scopes = VALUE_SCOPES.filter((scope) => EXPRESSION_NAMES[scope].includes(name))\n if (scopes.length > 0) return eachRead(site, name, 'expression-out-of-scope', `${name} has a value only in ${scopes.map((scope) => WHERE[scope]).join(' and ')}`)\n return eachRead(site, name, 'expression-unknown-name', `${quote(name)} is not a name an expression reads; here it reads ${EXPRESSION_NAMES[site.scope].join(', ')}`)\n }\n // A whole read -- size(params) -- is found once every member read is\n // spliced, when what still reads the name reads it whole.\n if (rest === '' && member === undefined) return []\n const scoped = name as ScopeName\n if (member === undefined) return eachRead(site, path, 'expression-unknown-name', `${name} has no member ${quote(rest)}: a ${MEMBERS_ARE[scoped]} is read by its id, as ${name}.<id>`)\n const held = members[scoped].get(member)\n if (held === undefined && images[scoped]?.has(member) === true) {\n return eachRead(site, path, 'expression-unreadable-field', `${name}.${member} is an image field: an image component draws it, and nothing reads it as a value`)\n }\n if (held === undefined) return eachRead(site, path, 'expression-unknown-name', `${name} has no member ${quote(member)}: no ${MEMBERS_ARE[scoped]} of the report has that id`)\n if (rest !== '') return eachRead(site, path, 'expression-unknown-name', `${name}.${member} is a single value, and has no member ${quote(rest.replace(/^\\./, ''))}`)\n return []\n}\n\n/** Each member the paths read, once, in the order first read, with how it is bound. */\nfunction readsOf(paths: readonly string[], members: Members): ExpressionRead[] {\n const reads = new Map<string, ExpressionRead>()\n for (const path of paths) {\n const { name, member } = pathParts(path)\n const held = member === undefined ? undefined : members[name as ScopeName].get(member)\n if (member === undefined || held === undefined || reads.has(`${name}.${member}`)) continue\n reads.set(`${name}.${member}`, { name: name as ScopeName, member, variable: `${name}_${member}`, type: held.type, nullable: held.nullable })\n }\n return [...reads.values()]\n}\n\n/** The source with each read spliced into its variable, or the diagnostic for a splice upstream refused. */\nfunction flattened(site: ExpressionSite, reads: readonly ExpressionRead[]): { readonly source: string } | Diagnostic {\n let source = site.cel\n for (const read of reads) {\n const rewritten = rewritePath(source, `${read.name}.${read.member}`, read.variable)\n if (!rewritten.ok) {\n return diagnostic(\n BY_KIND[rewritten.error.kind],\n `${read.variable} is the name ${read.name}.${read.member} is checked under, and this expression gives that name to a variable of its own; give the variable another`,\n at(site),\n )\n }\n source = rewritten.source\n }\n return { source }\n}\n\n/** `text` with each variable written back as the read it stands for, so a message names what the author wrote. */\nfunction authored(text: string | undefined, reads: readonly ExpressionRead[]): string | undefined {\n return reads.reduce<string | undefined>((said, read) => said?.replace(new RegExp(`(?<![A-Za-z0-9_])${read.variable}(?![A-Za-z0-9_])`, 'g'), `${read.name}.${read.member}`), text)\n}\n\n/** The diagnostic for an error the compiler gave; its position kept only when the source it checked is the author's, character for character. */\nfunction refused(site: ExpressionSite, error: ExpressionError, source: string, reads: readonly ExpressionRead[]): Diagnostic {\n const position = source.length === site.cel.length ? error.position : undefined\n return diagnostic(BY_KIND[error.kind], authored(error.message, reads) as string, at(site, position, authored(error.hint, reads)))\n}\n\n/**\n * A diagnostic at each place `source` -- with every member read spliced --\n * still reads a name of the scope: each such read reads the name whole,\n * since every read of a member by its id is spliced away. Positions only\n * when `source` is the author's, character for character.\n */\nfunction wholeReads(site: ExpressionSite, paths: readonly string[], source: string): Diagnostic[] {\n const exact = source.length === site.cel.length\n return paths\n .filter((path) => EXPRESSION_NAMES[site.scope].includes(path))\n .flatMap((name) =>\n readSpans(source, name).map((span) =>\n diagnostic('expression-dynamic-read', `${name} is read whole; an expression reads each ${MEMBERS_ARE[name as ScopeName]} by its id, as ${name}.<id>`, at(site, exact ? span : undefined)),\n ),\n )\n}\n\n/**\n * `site` compiled against what its scope binds in this report, or every\n * reason it cannot be: a read its scope does not allow, each where it is;\n * the compiler's first error; or each call to the clock or a random draw.\n */\nexport function compileSite(site: ExpressionSite, members: Members, images: Images): SiteOutcome {\n const parsed = parse(site.cel)\n if (!parsed.ok) return failed([refused(site, parsed.error, site.cel, [])])\n const paths = referencedPaths(parsed.ast)\n const problems = paths.flatMap((path) => readProblems(site, path, members, images))\n if (problems.length > 0) return failed(problems)\n const reads = readsOf(paths, members)\n const flat = flattened(site, reads)\n if (!('source' in flat)) return failed([flat])\n const whole = wholeReads(site, paths, flat.source)\n if (whole.length > 0) return failed(whole)\n const variables: VariableDeclarations = Object.fromEntries(reads.map((read) => [read.variable, read.nullable ? 'dyn' : read.type]))\n const compiled = compile(flat.source, { kind: site.kind, variables })\n if (!compiled.ok) return failed([refused(site, compiled.error, flat.source, reads)])\n const exact = flat.source.length === site.cel.length\n const calls = unreproducibleCalls(flat.source, site.kind, variables)\n if (calls.length > 0) {\n const message = (name: string): string => `${name}() differs from one render to the next, and a report prints the same from the same data; a date the report needs is a parameter`\n return failed(calls.map(({ name, span }) => diagnostic('expression-not-reproducible', message(name), at(site, exact ? span : undefined))))\n }\n const inexact = [\n ...inexactOperations(flat.source, site.kind, variables).map(({ kind, span }) => diagnostic('expression-inexact', INEXACT[kind].message, at(site, exact ? span : undefined, INEXACT[kind].hint))),\n ...unboundedCalls(flat.source, site.kind, variables).map(({ name, span }) => diagnostic('expression-unbounded', UNBOUNDED(name), at(site, exact ? span : undefined))),\n ].sort((a, b) => (a.position?.start ?? 0) - (b.position?.start ?? 0))\n if (inexact.length > 0) return failed(inexact)\n return { ok: true, compiled: { site, program: compiled.program, reads } }\n}\n\n/** What to say of each inexact operation, and what to write instead. */\nconst INEXACT: { readonly [K in InexactKind]: { readonly message: string; readonly hint: string } } = {\n 'double-literal': {\n message: 'a number written with a point or an exponent is a double, which is not exact: 0.1 + 0.2 is not 0.3, and int() of one drops what it lost',\n hint: 'write it as a decimal, dec(\"100.0\"), to keep it exact',\n },\n 'double-call': {\n message: 'double() makes a double, which is not exact: double(\"4.35\") * 100.0 is 434.99999999999994, and int() of it is 434',\n hint: 'compute with decimals instead: dec(\"4.35\") * dec(\"100\")',\n },\n 'integer-division': {\n message: '/ divides integers and drops the remainder, a rounding the report never declares: 3 / 2 is 1, and -3 / 2 is -1',\n hint: 'divide(dec(a), dec(b), places) keeps it exact, and rounds half away from zero where it says',\n },\n}\n\nconst UNBOUNDED = (name: string): string =>\n `${name}() runs its pattern on a backtracking engine that a step budget cannot stop: one pattern can take minutes on a short text, and a render cannot be interrupted while it runs`\n","/**\n * The order aggregates are computed in, and those that never can be.\n *\n * What an aggregate's expression reads from each row is read in the row\n * scope, which binds `totals`, so a share of the whole is\n * `divide(row.amount * dec(\"100\"), totals.subtotal, 2)`. Such an aggregate\n * needs the totals it reads computed first, over every row: the runtime\n * computes aggregates in an order where each comes after every aggregate it\n * reads. One that reads itself -- directly, or through others -- has no\n * place in any order, and neither has one that reads such an aggregate.\n */\nimport { parse, referencedPaths } from '@formancy/expressions'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { diagnostic } from '../diagnostics/codes.js'\nimport type { Diagnostic } from '../diagnostics/codes.js'\nimport type { ExpressionSite } from '../diagnostics/parts.js'\nimport { quote } from '../outcome.js'\nimport { pathParts } from './compile-site.js'\nimport { readSpans } from './spans.js'\n\n/** For each aggregate -- every one has an entry -- the declared aggregates its expression reads as totals, once each, in the order first read. */\nexport function aggregateReads(report: ReportDefinition): ReadonlyMap<string, readonly string[]> {\n const declared = new Set(report.aggregates.map(({ id }) => id))\n return new Map(\n report.aggregates.map((aggregate) => {\n const parsed = aggregate.of?.kind === 'expression' ? parse(aggregate.of.expression.cel) : undefined\n if (parsed?.ok !== true) return [aggregate.id, []]\n const reads = referencedPaths(parsed.ast)\n .map(pathParts)\n .flatMap(({ name, member }) => (name === 'totals' && member !== undefined && declared.has(member) ? [member] : []))\n return [aggregate.id, [...new Set(reads)]]\n }),\n )\n}\n\n/** What the aggregate `id` reads; `aggregateReads` gives every aggregate an entry. */\nfunction readsOf(reads: ReadonlyMap<string, readonly string[]>, id: string): readonly string[] {\n return reads.get(id) as readonly string[]\n}\n\n/**\n * The aggregates in an order where each comes after every aggregate it\n * reads, and otherwise the earliest declared first; and, in declaration\n * order, those that have no place in it.\n */\nexport function aggregateOrder(report: ReportDefinition, reads: ReadonlyMap<string, readonly string[]>): { readonly order: readonly string[]; readonly unordered: readonly string[] } {\n const placed = new Set<string>()\n const ready = (id: string): boolean => !placed.has(id) && readsOf(reads, id).every((read) => placed.has(read))\n for (let next = report.aggregates.find(({ id }) => ready(id)); next !== undefined; next = report.aggregates.find(({ id }) => ready(id))) placed.add(next.id)\n return { order: [...placed], unordered: report.aggregates.map(({ id }) => id).filter((id) => !placed.has(id)) }\n}\n\n/** Whether `from` reaches `to` by what the aggregates read, among `among`. */\nfunction reaches(from: string, to: string, reads: ReadonlyMap<string, readonly string[]>, among: ReadonlySet<string>): boolean {\n const seen = new Set<string>()\n const visit = (id: string): boolean =>\n readsOf(reads, id).some((read) => {\n if (read === to) return true\n if (seen.has(read) || !among.has(read)) return false\n seen.add(read)\n return visit(read)\n })\n return visit(from)\n}\n\n/**\n * The diagnostic for the aggregate `id`, which has no place in the order:\n * at the first total it reads that has none either, saying whether that\n * read closes a circle back to it or reaches one.\n */\nexport function cycleDiagnostic(id: string, site: ExpressionSite, reads: ReadonlyMap<string, readonly string[]>, unordered: ReadonlySet<string>): Diagnostic {\n const blocker = readsOf(reads, id).find((read) => unordered.has(read)) as string\n const [position] = readSpans(site.cel, `totals.${blocker}`)\n const message = reaches(id, id, reads, unordered)\n ? `aggregate ${quote(id)} reads its own total${blocker === id ? '' : `, through ${quote(blocker)}`}, so it would have to be computed before itself and never can be`\n : `aggregate ${quote(id)} reads ${quote(blocker)}, which reads its own total, so neither can be computed`\n return diagnostic('aggregate-cycle', message, { path: site.path, position })\n}\n","/**\n * What an expression in a report can read: the names the format binds and\n * the members each holds, each with the type it is checked and bound as.\n *\n * The names are the format's: `EXPRESSION_NAMES` lists, for each scope, the\n * names the runtime binds (0007) -- `params`, `header` and `totals`\n * everywhere, `row` in a table's cells and in what an aggregate reads from\n * each row, `group` in a group's header and footer. Each holds members --\n * a parameter, a field, an aggregate, a group's key -- read as\n * `<name>.<id>`, and every member is a single value, never a map.\n */\nimport type { DeclaredType } from '@formancy/expressions'\nimport { GROUP_KEY, walkComponents } from '@formancy/report-spec'\nimport type { AggregateFunction, DatasetContract, FieldType, ReportDefinition } from '@formancy/report-spec'\n\n/**\n * The type an expression reads each readable field and parameter type as.\n *\n * - Exact numbers keep their exactness: an integer is `int`, a decimal\n * `decimal`, never a double.\n * - A `date` and a `datetime` are read as their ISO strings. Neither has a\n * zone, and a CEL timestamp is an instant: making one from a date would\n * need a zone the report does not have, and `@formancy/expressions`\n * refuses to guess one. Their ISO forms compare in calendar order.\n * - An `instant` has a zone, so it is a `timestamp`.\n * - An `image` is not readable: its value is an asset id, which is drawn,\n * never printed or computed with (0007).\n */\nexport const EXPRESSION_TYPES: { readonly [T in Exclude<FieldType, 'image'>]: DeclaredType } = {\n string: 'string',\n integer: 'int',\n decimal: 'decimal',\n boolean: 'bool',\n date: 'string',\n datetime: 'string',\n instant: 'timestamp',\n}\n\n/**\n * A value an expression reads as `<name>.<member>`. `type` is the CEL type\n * it is bound as: `expressionValues` makes a value of it from what the data\n * holds. It is checked as that type too, unless it may be null: CEL has no\n * nullable scalars, so a member that may be null is checked as `dyn`, and\n * compared with null before it is used as anything else.\n */\nexport interface ExpressionMember {\n readonly type: DeclaredType\n readonly nullable: boolean\n}\n\n/** Every name the format binds, in some scope. A test holds this to the union of `EXPRESSION_NAMES`. */\nexport const SCOPE_NAMES = ['params', 'header', 'row', 'totals', 'group'] as const\n\nexport type ScopeName = (typeof SCOPE_NAMES)[number]\n\n/** What each name holds in one report, member by member, in declaration order. */\nexport type Members = { readonly [N in ScopeName]: ReadonlyMap<string, ExpressionMember> }\n\n/** The type a field of `type` is read as; undefined for an image, which is not read. */\nexport function readAs(type: FieldType | undefined): DeclaredType | undefined {\n return type === undefined || type === 'image' ? undefined : EXPRESSION_TYPES[type]\n}\n\nexport function fieldsOf(dataset: DatasetContract | undefined): ReadonlyMap<string, ExpressionMember> {\n const members = new Map<string, ExpressionMember>()\n for (const field of dataset?.fields ?? []) {\n const type = readAs(field.type)\n if (type !== undefined) members.set(field.id, { type, nullable: field.nullable })\n }\n return members\n}\n\nexport function parametersOf(report: ReportDefinition): ReadonlyMap<string, ExpressionMember> {\n return new Map(\n report.parameters.map((parameter) => [parameter.id, { type: EXPRESSION_TYPES[parameter.type], nullable: !parameter.required && parameter.default === undefined }]),\n )\n}\n\n/**\n * `group.key`, the value the report's group is keyed by: the field grouped\n * by, read as its type and null where it may be, since the rows without a\n * value are a group of their own. Undefined when the report's table does\n * not group, or groups by a field nothing can read.\n */\nexport function groupKeyOf(report: ReportDefinition): readonly [typeof GROUP_KEY, ExpressionMember] | undefined {\n for (const { component } of walkComponents(report)) {\n if (component.kind !== 'table' || component.group === undefined) continue\n const by = component.group.by.field\n const field = report.datasets.detail?.fields.find(({ id }) => id === by)\n const type = readAs(field?.type)\n return field === undefined || type === undefined ? undefined : [GROUP_KEY, { type, nullable: field.nullable }]\n }\n return undefined\n}\n\n/** The image fields of a dataset: drawn, and never read as a value. */\nexport function imagesOf(dataset: DatasetContract | undefined): ReadonlySet<string> {\n return new Set((dataset?.fields ?? []).filter(({ type }) => type === 'image').map(({ id }) => id))\n}\n\n/**\n * The types each function totals (0007), for an aggregate over an\n * expression; one over a field the validator has already checked. A sum and\n * an average take integers and decimals; a minimum and a maximum those,\n * instants, and dates and date-times as the ISO strings they are read as; a\n * count counts what is not null, whatever it is. `dyn` -- a value that may\n * be null -- is taken by all of them: what it holds is known only at render.\n */\nexport const TOTALS: { readonly [F in AggregateFunction]: ReadonlySet<string> | 'any' } = {\n count: 'any',\n sum: new Set(['int', 'decimal', 'dyn']),\n avg: new Set(['int', 'decimal', 'dyn']),\n min: new Set(['int', 'decimal', 'timestamp', 'string', 'dyn']),\n max: new Set(['int', 'decimal', 'timestamp', 'string', 'dyn']),\n}\n\n/**\n * What each function computes from what it reads (0007): a count is an\n * integer and an average a decimal; a sum, minimum or maximum is the type it\n * read, `dyn` when that is not known. Over no rows, a count and a sum are 0\n * and the others null.\n */\nexport const COMPUTES: { readonly [F in AggregateFunction]: (read: DeclaredType | undefined) => ExpressionMember } = {\n count: () => ({ type: 'int', nullable: false }),\n sum: (read) => ({ type: read ?? 'dyn', nullable: false }),\n avg: () => ({ type: 'decimal', nullable: true }),\n min: (read) => ({ type: read ?? 'dyn', nullable: true }),\n max: (read) => ({ type: read ?? 'dyn', nullable: true }),\n}\n","/**\n * Every expression in a report compiled where it stands: what the editor\n * diagnoses and what the runtime evaluates, from one function.\n *\n * The runtime compiles a report before it renders one. If it assembled its\n * own compile options, it could accept what the editor refuses -- `now()`,\n * a member nothing declares -- or bind a value as a type the editor did not\n * check it as. So both take this: the diagnostics are its errors, and the\n * runtime refuses a report that has any, evaluates the programs it gives,\n * binds each with `expressionValues`, and computes the aggregates in the\n * order it gives.\n */\nimport type { DeclaredType } from '@formancy/expressions'\nimport type { AggregateDef, ReportDefinition } from '@formancy/report-spec'\nimport { diagnostic } from '../diagnostics/codes.js'\nimport type { Diagnostic } from '../diagnostics/codes.js'\nimport { expressionSites } from '../diagnostics/parts.js'\nimport type { ExpressionSite } from '../diagnostics/parts.js'\nimport { quote } from '../outcome.js'\nimport { aggregateOrder, aggregateReads, cycleDiagnostic } from './aggregates.js'\nimport { compileSite } from './compile-site.js'\nimport type { CompiledExpression, Images, SiteOutcome } from './compile-site.js'\nimport { COMPUTES, fieldsOf, groupKeyOf, imagesOf, parametersOf, readAs, TOTALS } from './members.js'\nimport type { ExpressionMember, Members } from './members.js'\n\nexport interface ReportCompilation {\n /** What each name holds in this report: every member an expression can read, with the type it is checked and bound as. */\n readonly members: Members\n /** Every expression that compiled clean, by the JSON Pointer to its `cel`, in document order, the aggregates' last. */\n readonly expressions: ReadonlyMap<string, CompiledExpression>\n /** The aggregates in the order the runtime computes them: each after every aggregate its expression reads. One with no place in it is diagnosed. */\n readonly aggregateOrder: readonly string[]\n /** Every reason an expression cannot be evaluated, in document order, the aggregates' last: what the runtime refuses the report for. */\n readonly diagnostics: readonly Diagnostic[]\n}\n\n/** The CEL types a member can be declared as, of all the types an expression can give. */\nconst SCALARS: ReadonlySet<string> = new Set<DeclaredType>(['bool', 'int', 'double', 'decimal', 'string', 'timestamp', 'dyn'])\n\n/** Every expression in `report` -- a report the validator accepts -- compiled where it stands. */\nexport function compileReport(report: ReportDefinition): ReportCompilation {\n return compiledSites(report, expressionSites(report))\n}\n\n/** `compileReport` over sites already walked: `diagnose` walks the report once for this and for its warnings. */\nexport function compiledSites(report: ReportDefinition, sites: readonly ExpressionSite[]): ReportCompilation {\n const images: Images = { header: imagesOf(report.datasets.header), row: imagesOf(report.datasets.detail) }\n const byPath = new Map(sites.map((site) => [site.path, site]))\n const siteOf = (index: number): ExpressionSite => byPath.get(`/aggregates/${index}/of/expression/cel`) as ExpressionSite\n const reads = aggregateReads(report)\n const { order, unordered } = aggregateOrder(report, reads)\n const cyclic = new Set(unordered)\n const known = new Map<string, ExpressionMember>()\n const base = { params: parametersOf(report), header: fieldsOf(report.datasets.header), row: fieldsOf(report.datasets.detail) }\n const outcomes = new Map<string, SiteOutcome>()\n\n /** What `aggregate` computes, its expression compiled against the totals before it; and why it cannot be computed, when it cannot. */\n const computed = (aggregate: AggregateDef, index: number): ExpressionMember => {\n if (aggregate.of?.kind !== 'expression') {\n const read = aggregate.of?.field.field\n return COMPUTES[aggregate.fn](readAs(report.datasets.detail?.fields.find(({ id }) => id === read)?.type))\n }\n const site = siteOf(index)\n const outcome = compileSite(site, { ...base, totals: known, group: known }, images)\n outcomes.set(site.path, outcome)\n if (!outcome.ok) return COMPUTES[aggregate.fn](undefined)\n const result = outcome.compiled.program.resultType\n const takes = TOTALS[aggregate.fn]\n if (takes === 'any' || takes.has(result)) return COMPUTES[aggregate.fn](SCALARS.has(result) ? (result as DeclaredType) : undefined)\n const said = `aggregate ${quote(aggregate.id)} is a ${aggregate.fn} of what its expression gives, ${result}, and a ${aggregate.fn} takes ${[...takes].filter((type) => type !== 'dyn').join(', ')}`\n outcomes.set(site.path, { ok: false, diagnostics: [diagnostic('expression-aggregate-type', said, { path: site.path })] })\n return COMPUTES[aggregate.fn](undefined)\n }\n for (const id of order) {\n const index = report.aggregates.findIndex((aggregate) => aggregate.id === id)\n known.set(id, computed(report.aggregates[index] as AggregateDef, index))\n }\n // An aggregate that can never be computed has no value anyone could check\n // a read of; it is read as a value that may be anything, so that only the\n // circle is reported, once, where it closes.\n for (const id of unordered) known.set(id, { type: 'dyn', nullable: true })\n const totals = new Map(report.aggregates.map(({ id }) => [id, known.get(id) as ExpressionMember]))\n // A group holds its aggregates and its key; report-spec keeps the key's name from every aggregate.\n const key = groupKeyOf(report)\n const members: Members = { ...base, totals, group: key === undefined ? totals : new Map([...totals, key]) }\n\n const expressions = new Map<string, CompiledExpression>()\n const diagnostics: Diagnostic[] = []\n for (const site of sites) {\n const outcome = outcomes.get(site.path) ?? compileSite(site, members, images)\n const aggregate = site.path.startsWith('/aggregates/') ? report.aggregates[Number(site.path.split('/')[2])]?.id : undefined\n if (aggregate !== undefined && cyclic.has(aggregate)) diagnostics.push(cycleDiagnostic(aggregate, site, reads, cyclic))\n else if (outcome.ok) expressions.set(site.path, outcome.compiled)\n if (!outcome.ok) diagnostics.push(...outcome.diagnostics)\n }\n return { members, expressions, aggregateOrder: order, diagnostics }\n}\n","/**\n * The values one evaluation reads: what the data holds, made into what each\n * member was compiled as. One function, so the type an expression was\n * checked as and the value it is handed cannot disagree.\n *\n * Exact values travel as strings with their type (0007; formancy.ai-data\n * 0008). `@formancy/expressions` converts a value itself only for a variable\n * declared at the top level and never null -- an int from a number, a\n * decimal from a string, a timestamp from a string with a zone -- and a\n * member that may be null is declared `dyn`, which it leaves as it is. So\n * every member is converted here, the same way whether it may be null or\n * not, and upstream finds each already of its type.\n */\nimport { Decimal, decimalFromString } from '@formancy/expressions'\nimport type { CompiledExpression, ExpressionRead } from './compile-site.js'\n\n/**\n * The data one evaluation reads, by name and member: `{ row: { amount:\n * '12.50' } }`. Each value as the format writes it -- an integer and a\n * decimal as their exact strings, an instant as an ISO 8601 date-time with\n * its zone, a date and a date-time as their ISO strings, a boolean, a\n * string, null where there is no value -- or already as the CEL value: a\n * bigint, upstream's `Decimal`, a `Date`.\n */\nexport type ExpressionValues = { readonly [name: string]: Readonly<Record<string, unknown>> | undefined }\n\n/** An ISO 8601 date-time with its zone: one without would be read in the host's zone, which a render on another machine does not share. */\nconst ZONED = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2})$/\n\nconst WHOLE = /^-?\\d+$/\n\n/** A refusal that names the member and its type, and never quotes the value: data is the customer's, and never reaches a message. */\nfunction notOf(read: ExpressionRead, what: string): TypeError {\n return new TypeError(`${read.name}.${read.member} is not ${what}`)\n}\n\nfunction asInt(read: ExpressionRead, raw: unknown): bigint {\n if (typeof raw === 'bigint') return raw\n if (typeof raw === 'number' && Number.isSafeInteger(raw)) return BigInt(raw)\n if (typeof raw === 'string' && WHOLE.test(raw)) return BigInt(raw)\n throw notOf(read, 'an integer, written as its exact digits')\n}\n\nfunction asDecimal(read: ExpressionRead, raw: unknown): Decimal {\n if (raw instanceof Decimal) return raw\n if (typeof raw === 'string') {\n try {\n return decimalFromString(raw)\n } catch {\n // Rethrown below without upstream's message, which quotes the value.\n }\n }\n throw notOf(read, 'a decimal, written as its exact digits')\n}\n\nfunction asInstant(read: ExpressionRead, raw: unknown): Date {\n const instant = raw instanceof Date ? raw : typeof raw === 'string' && ZONED.test(raw) ? new Date(raw) : undefined\n if (instant === undefined || Number.isNaN(instant.getTime())) throw notOf(read, 'an instant: an ISO 8601 date-time with its zone')\n return instant\n}\n\n/** The value `raw` is bound as, for `read`. */\nfunction bound(read: ExpressionRead, raw: unknown): unknown {\n if (raw === null && read.nullable) return null\n switch (read.type) {\n case 'int':\n return asInt(read, raw)\n case 'decimal':\n return asDecimal(read, raw)\n case 'timestamp':\n return asInstant(read, raw)\n case 'string':\n if (typeof raw === 'string') return raw\n throw notOf(read, 'a string')\n case 'bool':\n if (typeof raw === 'boolean') return raw\n throw notOf(read, 'a boolean')\n default:\n // An aggregate over an expression of a type the compiler could not\n // tell: what the runtime computed is handed over as it is.\n if (raw !== undefined && raw !== null) return raw\n throw notOf(read, 'a value')\n }\n}\n\n/**\n * The value bag `evaluate` takes for `expression`: each member it reads,\n * under the variable it was compiled with, made into the type it was\n * compiled as.\n *\n * Throws a TypeError for a value the data lacks, null where the member is\n * never null, or a value not of the member's type -- an amount as a\n * JavaScript number, an instant without its zone. The runtime validates a\n * dataset against its contract before any expression reads it, so each is\n * a defect, and is said as one: naming the member, never quoting the value.\n */\nexport function expressionValues(expression: CompiledExpression, values: ExpressionValues): Record<string, unknown> {\n return Object.fromEntries(expression.reads.map((read) => [read.variable, bound(read, values[read.name]?.[read.member])]))\n}\n","/**\n * Content that prints nothing: a body with no components, a text with no\n * runs or only blank literal ones.\n *\n * Only what the document alone decides. Whether a keep-together block is\n * taller than a page, whether a fixed width fits its column, whether a\n * table's rows overflow: each depends on measured text and the data, and is\n * the layout's to report with the renderer, not this package's to guess.\n * A table without a detail dataset is no diagnostic either: the validator\n * refuses it (`unknown-dataset`), so a session never holds one.\n */\nimport { walkComponents } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { quote } from '../outcome.js'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic } from './codes.js'\n\nexport function contentDiagnostics(report: ReportDefinition): Diagnostic[] {\n const found: Diagnostic[] = []\n if (report.regions.body.length === 0) {\n found.push(diagnostic('empty-body', 'the body holds nothing, so the report prints only its headers, footers and summary', { path: '/regions/body' }))\n }\n for (const { component, path } of walkComponents(report)) {\n if (component.kind !== 'text') continue\n if (component.content.every((inline) => inline.kind === 'text' && inline.text.trim() === '')) {\n found.push(diagnostic('empty-text', `text ${quote(component.id)} prints nothing`, { path: `${path}/content`, componentId: component.id }))\n }\n }\n return found\n}\n","/**\n * Roundings the runtime would refuse, or apply twice.\n *\n * A total is rounded once, by its declared rule (0007). A format then shows\n * it, and rounds half away from zero to the places it shows. Where it shows\n * fewer places than the rounding keeps, the total is rounded a second time,\n * by a rule nobody declared: summed and rounded half-even to three places,\n * 1.2449 is 1.245, and shown at two places that is 1.25, where rounding the\n * total once to two places gives 1.24 in either mode. So such a format is an\n * error, and the author declares the rounding at the places printed.\n *\n * A rounding on an aggregate that computes an integer, a date, a text or\n * an instant has no places to round, and the runtime refuses it; it is an\n * error here too, so the editor says so before a render does. One whose\n * type the compiler cannot tell (`dyn`) is rounded as a decimal, as the\n * runtime does.\n */\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport type { ExpressionMember } from '../expressions/members.js'\nimport { quote } from '../outcome.js'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic } from './codes.js'\nimport type { PrintedTotal } from './parts.js'\n\n/** The types a rounding has places in. */\nconst ROUNDED = new Set(['decimal', 'dyn'])\n\nexport function roundingDiagnostics(report: ReportDefinition, printed: readonly PrintedTotal[], totals: ReadonlyMap<string, ExpressionMember>): Diagnostic[] {\n const found: Diagnostic[] = []\n for (const [index, aggregate] of report.aggregates.entries()) {\n const type = totals.get(aggregate.id)?.type\n if (aggregate.rounding === undefined || type === undefined || ROUNDED.has(type)) continue\n const what = type === 'int' ? 'an integer' : type === 'timestamp' ? 'an instant' : 'a date or a text'\n found.push(diagnostic('rounding-not-decimal', `aggregate ${quote(aggregate.id)} declares a rounding, and computes ${what}, which has no places to round`, { path: `/aggregates/${index}/rounding` }))\n }\n for (const total of printed) {\n const kept = report.aggregates.find(({ id }) => id === total.aggregate)?.rounding?.scale\n if (kept === undefined || total.scale >= kept) continue\n const said = `aggregate ${quote(total.aggregate)} is rounded to ${kept} places as it declares, and printed at ${total.scale}, which rounds it again by another rule; declare its rounding at ${total.scale} places`\n found.push(diagnostic('format-rounds-again', said, { path: total.path, componentId: total.componentId, columnId: total.columnId }))\n }\n return found\n}\n","/**\n * Declarations nothing uses: a style no component names, an asset no image\n * draws, a parameter, field or aggregate nothing prints, orders by, totals\n * or reads. Each renders as written; each is probably a leftover, and a\n * parameter or a field costs something at every render -- a question on\n * the parameter form, a column the provider fetches.\n *\n * What an expression reads counts: its paths are asked of the parser, as\n * the compiler asks them. An expression that does not parse reads nothing\n * it can be credited with; its own diagnostic says why.\n */\nimport { parse, referencedPaths } from '@formancy/expressions'\nimport type { DatasetRole, ReportDefinition } from '@formancy/report-spec'\nimport { pathParts } from '../expressions/compile-site.js'\nimport { quote } from '../outcome.js'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic, DiagnosticCode } from './codes.js'\nimport type { ExpressionSite, ReportParts } from './parts.js'\n\n/** What expressions read, by name: the members read, or 'all' when one reads the whole map. */\ntype Reads = ReadonlyMap<string, ReadonlySet<string> | 'all'>\n\nfunction expressionReads(sites: readonly ExpressionSite[]): Reads {\n const reads = new Map<string, Set<string> | 'all'>()\n for (const site of sites) {\n const parsed = parse(site.cel)\n if (!parsed.ok) continue\n for (const path of referencedPaths(parsed.ast)) {\n const { name, member, rest } = pathParts(path)\n const known = reads.get(name)\n // A whole read may read any member; a read by a key that is no\n // identifier reads none, since every member's id is one.\n if (member === undefined && rest === '') reads.set(name, 'all')\n else if (member === undefined) continue\n else if (known === undefined) reads.set(name, new Set([member]))\n else if (known !== 'all') known.add(member)\n }\n }\n return reads\n}\n\n/** Whether an expression reads `id` under any of `names`. */\nfunction read(reads: Reads, names: readonly string[], id: string): boolean {\n return names.some((name) => {\n const members = reads.get(name)\n return members === 'all' || members?.has(id) === true\n })\n}\n\n/** The name an expression reads each dataset's fields under. */\nconst READ_AS: { readonly [R in DatasetRole]: string } = { header: 'header', detail: 'row' }\n\nexport function unusedDiagnostics(report: ReportDefinition, parts: ReportParts): Diagnostic[] {\n const reads = expressionReads(parts.expressions)\n const found: Diagnostic[] = []\n const check = (declared: readonly { readonly id: string }[], used: (id: string) => boolean, code: DiagnosticCode, list: string, message: (id: string) => string): void => {\n for (const [index, { id }] of declared.entries()) if (!used(id)) found.push(diagnostic(code, message(quote(id)), { path: `${list}/${index}` }))\n }\n const styles = new Set(parts.styles)\n const assets = new Set(parts.assets)\n const parameters = new Set(parts.parameters)\n const aggregates = new Set(parts.aggregates)\n check(report.styles, (id) => styles.has(id), 'unused-style', '/styles', (id) => `style ${id} is used by no component, column or row`)\n check(report.assets, (id) => assets.has(id), 'unused-asset', '/assets', (id) => `asset ${id} is drawn by no image`)\n check(\n report.parameters,\n (id) => parameters.has(id) || read(reads, ['params'], id),\n 'unused-parameter',\n '/parameters',\n (id) => `parameter ${id} is neither printed nor read, and the person rendering would be asked for it for nothing`,\n )\n for (const role of ['header', 'detail'] as const) {\n const fields = new Set(parts.fields.filter(({ dataset }) => dataset === role).map(({ field }) => field))\n check(\n report.datasets[role]?.fields ?? [],\n (id) => fields.has(id) || read(reads, [READ_AS[role]], id),\n 'unused-field',\n `/datasets/${role}/fields`,\n (id) => `field ${id} of the ${role} dataset is neither printed, drawn, ordered by, totalled nor read, and would be fetched for nothing`,\n )\n }\n check(\n report.aggregates,\n (id) => aggregates.has(id) || read(reads, ['totals', 'group'], id),\n 'unused-aggregate',\n '/aggregates',\n (id) => `aggregate ${id} is neither printed nor read, and would be computed over every row for nothing`,\n )\n return found\n}\n","/**\n * What an editor shows about a valid report: the errors the runtime would\n * refuse it for, and the warnings an author probably wants to see.\n */\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { compiledSites } from '../expressions/compile-report.js'\nimport type { Diagnostic } from './codes.js'\nimport { contentDiagnostics } from './content.js'\nimport { reportParts } from './parts.js'\nimport { roundingDiagnostics } from './rounding.js'\nimport { unusedDiagnostics } from './unused.js'\n\n/**\n * Every diagnostic for `report`, a report the validator accepts -- a\n * session's document is one. Expressions first, in document order, the\n * aggregates' last, then roundings, then content, then unused declarations\n * in the order they are declared. The expressions' are `compileReport`'s,\n * so the editor reports exactly what the runtime refuses.\n */\nexport function diagnose(report: ReportDefinition): Diagnostic[] {\n const parts = reportParts(report)\n const compiled = compiledSites(report, parts.expressions)\n return [...compiled.diagnostics, ...roundingDiagnostics(report, parts.printedTotals, compiled.members.totals), ...contentDiagnostics(report), ...unusedDiagnostics(report, parts)]\n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OAAO,OAAO,IAAI,EAAE,GAAG,gBAAgB,YAAY,OAAO,SAAS,GAAG,wCAAwC;CACpI,MAAM,OAAO,SAAS,OAAO,OAAO,IAAI,EAAE,GAAG,gBAAgB,YAAY,OAAO,SAAS,GAAG,sBAAsB;CAClH,MACE,OAAO,aACN,OAAO,WAAW,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,QAAQ,GAAG,EAAE,GACxD,oBACA,gBACC,OAAO,aAAa,GAAG,yFAC1B;CACA,KAAK,MAAM,QAAQ,CAAC,UAAU,QAAQ,GAAY;EAChD,MAAM,SAAS,IAAI,IAAI,MAAM,OAAO,QAAQ,EAAE,cAAc,YAAY,IAAI,CAAC,CAAC,KAAK,EAAE,YAAY,KAAK,CAAC;EACvG,MACE,OAAO,SAAS,KAAK,EAAE,UAAU,CAAC,IACjC,OAAO,OAAO,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,QAAQ,KAAK,GAAG,EAAE,GACzD,gBACA,aAAa,KAAK,WACjB,OAAO,SAAS,GAAG,UAAU,KAAK,oGACrC;CACF;CACA,MACE,OAAO,aACN,OAAO,WAAW,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,UAAU,OAAO,GAAG,EAAE,GACjE,oBACA,gBACC,OAAO,aAAa,GAAG,+EAC1B;CACA,OAAO;AACT;;;;;;;;;;ACtEA,SAAgB,SAAS,QAAwC;CAC/D,MAAM,QAAQ,YAAY,MAAM;CAChC,MAAM,WAAW,cAAc,QAAQ,MAAM,WAAW;CACxD,OAAO;EAAC,GAAG,SAAS;EAAa,GAAG,oBAAoB,QAAQ,MAAM,eAAe,SAAS,QAAQ,MAAM;EAAG,GAAG,mBAAmB,MAAM;EAAG,GAAG,kBAAkB,QAAQ,KAAK;CAAC;AACnL"}
1
+ {"version":3,"file":"index.mjs","names":["missing","put","PATH","missing","PATH","missing","TEXT","WORD","readsOf","readsOf","readsOf","read"],"sources":["../src/outcome.ts","../src/ids.ts","../src/lists.ts","../src/tree.ts","../src/commands/components.ts","../src/commands/declarations.ts","../src/commands/document.ts","../src/commands/e-invoice.ts","../src/commands/first-page-header.ts","../src/commands/payment-part.ts","../src/diagnostics/parts.ts","../src/diagnostics/codes.ts","../src/expressions/members.ts","../src/expressions/e-invoice.ts","../src/expressions/reproducible.ts","../src/expressions/exactness.ts","../src/expressions/spans.ts","../src/expressions/compile-site.ts","../src/expressions/reads.ts","../src/commands/table.ts","../src/commands/readers.ts","../src/commands/translations.ts","../src/commands/registry.ts","../src/draft.ts","../src/snapshot.ts","../src/session.ts","../src/locations.ts","../src/expressions/aggregates.ts","../src/expressions/compile-report.ts","../src/expressions/values.ts","../src/diagnostics/rounding.ts","../src/diagnostics/chart.ts","../src/diagnostics/content.ts","../src/diagnostics/e-invoice.ts","../src/diagnostics/example-payment-part.ts","../src/diagnostics/tables.ts","../src/diagnostics/unused.ts","../src/diagnostics/diagnosis.ts","../src/diagnostics/words.ts","../src/diagnostics/diagnose.ts"],"sourcesContent":["/**\n * What a command gives back: the next report, or the reason there is none.\n *\n * A command is a pure function from a report to an outcome. It never writes\n * to the report it is given, and it refuses -- returns, never throws -- when\n * its own preconditions do not hold: the thing it names exists, the place it\n * names is a place, the kind it was told to expect is the kind there.\n * Whether the result is a valid report is not the command's question; the\n * session asks the validator, once, for every command alike\n * ([0008](../../../docs/decisions/0008-edits-are-commands-and-a-refused-edit-changes-nothing.md)).\n */\nimport type { ReportDefinition, ReportError } from '@formancy/report-spec'\n\n/**\n * Why an edit was refused, as stable codes. A code is for a program -- the\n * builder decides what to say and where -- and the message is for a person.\n * As with the validator's codes, a code is never reworded once released; a\n * new reason gets a new code. Each has a case in `outcome.test.ts` that is\n * refused with it, which does not compile while one is missing.\n */\nexport const REFUSAL_CODES = [\n /** The component, declaration, column, footer row or cell the command names does not exist. */\n 'not-found',\n /** The parent a location names holds no components: a text, a table, an image. */\n 'not-a-container',\n /** A location that contradicts itself: a column outside a columns block, none inside one, or a parent in another region. */\n 'invalid-location',\n /** An index that is not a whole number within the list it indexes. */\n 'index-out-of-range',\n /** A component moved into itself or into something it holds. */\n 'into-itself',\n /** The component a command names is not of the kind the command is for. */\n 'kind-mismatch',\n /** A patch that would change what identifies a thing: a component's id or kind, a column's id. */\n 'immutable-property',\n /** An add under an id the report already declares: an add never replaces, as a put does. */\n 'already-declared',\n /** A command descriptor whose command is not one this package has. */\n 'unknown-command',\n /** A command descriptor whose arguments are too few, too many or of the wrong type -- one read from JSON was never type-checked. */\n 'invalid-arguments',\n /** The result is not a valid report; `errors` holds the validator's reasons. */\n 'invalid-document',\n /** An edit made against a document that is no longer the session's: its hash is not the one the edit expected. */\n 'stale-document',\n /** A value the command would write where the report reads it from the data: an account the e-invoice and its payment codes share, one of them bound (0044). */\n 'read-from-data',\n /** A field the payment part or the e-invoice reads, directly or through an aggregate, named to a command that removes what reads it: only their own commands change them (0039, 0048). */\n 'read-by-part',\n] as const\n\nexport type RefusalCode = (typeof REFUSAL_CODES)[number]\n\nexport interface Refusal {\n readonly ok: false\n readonly code: RefusalCode\n readonly message: string\n /** A JSON Pointer to what the refusal is about, when it is about one place. */\n readonly path?: string\n /** The component the refusal is about, when it is about one. */\n readonly componentId?: string\n /** The validator's errors, for `invalid-document`. */\n readonly errors?: readonly ReportError[]\n}\n\n/** The next report, and whatever else the command says about it (a duplicate's new id), or a refusal. */\nexport type CommandOutcome<E extends object = object> = ({ readonly ok: true; readonly report: ReportDefinition } & Readonly<E>) | Refusal\n\n/** An edit, bound to its arguments: what the session applies. */\nexport type Command<E extends object = object> = (report: ReportDefinition) => CommandOutcome<E>\n\n/** Where a refusal points. */\nexport interface Place {\n readonly path?: string | undefined\n readonly componentId?: string | undefined\n}\n\nexport function refuse(code: RefusalCode, message: string, place: Place = {}): Refusal {\n return {\n ok: false,\n code,\n message,\n ...(place.path === undefined ? {} : { path: place.path }),\n ...(place.componentId === undefined ? {} : { componentId: place.componentId }),\n }\n}\n\nexport function isRefusal(value: unknown): value is Refusal {\n return typeof value === 'object' && value !== null && (value as { ok?: unknown }).ok === false\n}\n\n/** A name as a message quotes it: at most 40 characters, so no message grows with what a caller passed. */\nexport function quote(text: string): string {\n return JSON.stringify(text.length > 40 ? `${text.slice(0, 40)}...` : text)\n}\n","/**\n * The ids new things take: a prefix itself when it is free, and otherwise\n * the prefix numbered. One rule for a component the palette inserts, a\n * copy a duplicate makes and an image a person adds (0033), so that the\n * ids an author reads in the outline and in the report's images are made\n * alike, and every one is an identifier the validator accepts. A copy is\n * numbered from its original's base, `intro-2` copied being `intro-3`; a\n * file's name is numbered as it stands, `img-4711` taken being `img-4711-2`.\n */\nimport { isIdentifier } from '@formancy/report-spec'\nimport { quote } from './outcome.js'\n\n/** The longest identifier the format allows: `isIdentifier`'s rule in report-spec, at most 64 characters. */\nconst IDENTIFIER_LENGTH = 64\n\n/** A trailing number an id was given to make it unique: `-2` in `intro-2`. */\nconst NUMBERED = /-\\d+$/\n\n/** `prefix` if `taken` lacks it, otherwise `base` -- the prefix without a number it was given, unless one is said -- numbered from 2, within the identifier's length. */\nexport function freshId(prefix: string, taken: ReadonlySet<string>, base: string = prefix.replace(NUMBERED, '')): string {\n if (!taken.has(prefix)) return prefix\n for (let number = 2; ; number += 1) {\n const suffix = `-${number}`\n const id = `${base.slice(0, IDENTIFIER_LENGTH - suffix.length)}${suffix}`\n if (!taken.has(id)) return id\n }\n}\n\n/** A RangeError naming `said` when `prefix` is not an identifier, which would give an id the validator refuses. */\nexport function checkPrefix(prefix: string, said: string = prefix): void {\n if (!isIdentifier(prefix)) throw new RangeError(`${quote(said)} is not an identifier: lower-case letters, digits and hyphens, starting with a letter`)\n}\n\n/** `freshId` of `prefix`, once `checkPrefix` has held it to the identifier rule. */\nexport function nextId(prefix: string, taken: ReadonlySet<string>, said: string = prefix): string {\n checkPrefix(prefix, said)\n return freshId(prefix, taken)\n}\n","/**\n * Copy-on-write edits to lists and objects: the vocabulary every command is\n * written in. Each returns a new list or object and leaves its input as it\n * was, so a command never writes to the report it was given.\n */\nimport { refuse } from './outcome.js'\nimport type { Place, Refusal } from './outcome.js'\n\n/**\n * A change to some of an object's properties. A value sets a property;\n * `null` removes one that is optional. A required property cannot be given\n * `null`, so a patch cannot remove one.\n *\n * `null`, not `undefined`, because a patch is also data: a proposal carries\n * it as JSON, which has no undefined and drops a key that holds one. A\n * removal written with undefined would arrive as no change at all.\n */\nexport type Patch<T> = { readonly [K in keyof T]?: undefined extends T[K] ? Exclude<T[K], undefined> | null : T[K] }\n\n/**\n * `target` with `patch` applied: the properties it names set, or removed\n * where it gives `null`. A property given `undefined` -- possible only for a\n * caller tsc never saw -- is left as it is, as it would be once the patch\n * had been through JSON.\n */\nexport function patched<T extends object>(target: T, patch: Patch<T>): T {\n const next = { ...target } as Record<string, unknown>\n for (const [key, value] of Object.entries(patch)) {\n if (value === null) delete next[key]\n else if (value !== undefined) next[key] = value\n }\n return next as T\n}\n\n/** A refusal unless `index` is a whole number from 0 to `last`, inclusive. */\nexport function checkIndex(index: number, last: number, what: string, place: Place = {}): Refusal | undefined {\n if (Number.isInteger(index) && index >= 0 && index <= last) return undefined\n const range = last < 0 ? 'there is nothing to index' : `it is a whole number from 0 to ${last}`\n return refuse('index-out-of-range', `${String(index)} is not a position in ${what}: ${range}`, place)\n}\n\nexport function insertedAt<T>(list: readonly T[], index: number, item: T): T[] {\n return [...list.slice(0, index), item, ...list.slice(index)]\n}\n\nexport function removedAt<T>(list: readonly T[], index: number): T[] {\n return [...list.slice(0, index), ...list.slice(index + 1)]\n}\n\nexport function replacedAt<T>(list: readonly T[], index: number, item: T): T[] {\n return list.map((existing, at) => (at === index ? item : existing))\n}\n\n/** The item at `from` moved so that it ends at `to`; the others keep their order. */\nexport function movedTo<T>(list: readonly T[], from: number, to: number): T[] {\n const item = list[from] as T\n return insertedAt(removedAt(list, from), to, item)\n}\n","/**\n * Places in a report: where a component stands or can be put, and how to\n * change one place without touching the rest.\n *\n * A place is named by the same JSON Pointers `walkComponents` and the\n * validator use, so a command, a diagnostic and a validation error about\n * one component all point at one path.\n */\nimport { componentAt } from '@formancy/report-spec'\nimport type { Component, ComponentKind, RegionName, ReportDefinition } from '@formancy/report-spec'\nimport { quote, refuse } from './outcome.js'\nimport type { Refusal } from './outcome.js'\n\n/**\n * Where a component goes: a position in a region's list, or in the list a\n * container holds -- a section's, a keep-together block's, or one column's\n * of a columns block. `index` is the position the component ends at.\n */\nexport interface Location {\n readonly region: RegionName\n /** The id of the container; absent for the region's own list. */\n readonly parent?: string\n /** Which column, for a columns block, and only for one. */\n readonly column?: number\n readonly index: number\n}\n\ntype Lists = (list: readonly Component[]) => readonly Component[]\n\n/** A list of components a container holds, and for a columns block which column it is. */\nexport interface HeldList {\n readonly column?: number\n readonly list: readonly Component[]\n}\n\n/** How a kind holds components: the lists it holds, and itself rebuilt with every one of them changed. */\ninterface Holding<C extends Component> {\n readonly lists: (component: C) => readonly HeldList[]\n readonly rebuild: (component: C, change: Lists) => C\n}\n\n/** The one shape every container but a columns block has: one list, under `components`. */\nfunction oneList<C extends Extract<Component, { readonly components: readonly Component[] }>>(): Holding<C> {\n return {\n lists: (component) => [{ list: component.components }],\n rebuild: (component, change) => ({ ...component, components: change(component.components) }),\n }\n}\n\n/**\n * How each kind holds components, or undefined for a kind that holds none.\n * A table over every kind, so a container added to the format without\n * saying where it keeps its children does not compile.\n */\nconst CONTAINERS: { readonly [K in ComponentKind]: Holding<Extract<Component, { kind: K }>> | undefined } = {\n text: undefined,\n image: undefined,\n qrCode: undefined,\n epcQrCode: undefined,\n line: undefined,\n rectangle: undefined,\n spacer: undefined,\n columns: {\n lists: (component) => component.columns.map((slot, column) => ({ column, list: slot.components })),\n rebuild: (component, change) => ({ ...component, columns: component.columns.map((slot) => ({ ...slot, components: change(slot.components) })) }),\n },\n section: oneList(),\n table: undefined,\n chart: undefined,\n pageBreak: undefined,\n keepTogether: oneList(),\n}\n\nfunction holding(component: Component): Holding<Component> | undefined {\n return CONTAINERS[component.kind] as Holding<Component> | undefined\n}\n\n/** `component` with every list of components it holds changed by `change`; itself when it holds none. */\nexport function withChildren(component: Component, change: Lists): Component {\n return holding(component)?.rebuild(component, change) ?? component\n}\n\n/** The lists of components `component` holds, in order; none for a kind that holds none. */\nexport function heldLists(component: Component): readonly HeldList[] {\n return holding(component)?.lists(component) ?? []\n}\n\n/** A list of components, and the JSON Pointer to it. */\nexport interface ComponentList {\n readonly pointer: string\n readonly list: readonly Component[]\n}\n\n/** The list a location names, without its index, or why it names none. */\nexport function listAt(report: ReportDefinition, location: Omit<Location, 'index'>): ComponentList | Refusal {\n const { region, parent, column } = location\n if (parent === undefined) {\n if (column !== undefined) return refuse('invalid-location', 'a column is chosen only inside a columns block')\n const list = report.regions[region]\n // A region the report may leave out, left out, has no list to put a component in: it is given one by its own command (0060).\n if (list === undefined) return refuse('not-found', `the report has no ${region}`, { path: `/regions/${region}` })\n return { pointer: `/regions/${region}`, list }\n }\n const found = componentAt(report, parent)\n if (found === undefined) return refuse('not-found', `no component is ${quote(parent)}`, { componentId: parent })\n const place = { path: found.path, componentId: parent }\n if (found.region !== region) return refuse('invalid-location', `${quote(parent)} stands in the ${found.region}, not the ${region}`, place)\n const container = found.component\n if (holding(container) === undefined) return refuse('not-a-container', `${quote(parent)} is a ${container.kind}, which holds no components`, place)\n if (container.kind === 'columns') {\n if (column === undefined) return refuse('invalid-location', 'a columns block holds components in its columns; say which column', place)\n const slot = container.columns[column]\n if (!Number.isInteger(column) || slot === undefined) {\n return refuse('index-out-of-range', `${String(column)} is not a column of ${quote(parent)}, which has ${container.columns.length}`, place)\n }\n return { pointer: `${found.path}/columns/${column}/components`, list: slot.components }\n }\n if (column !== undefined) return refuse('invalid-location', `${quote(parent)} is a ${container.kind}, which has no columns`, place)\n // Every other container holds one list, under `components`.\n return { pointer: `${found.path}/components`, list: (container as { readonly components: readonly Component[] }).components }\n}\n\n/** The list a component stands in, and its position there, from the component's own pointer. */\nexport function standing(path: string): { readonly pointer: string; readonly index: number } {\n const cut = path.lastIndexOf('/')\n return { pointer: path.slice(0, cut), index: Number(path.slice(cut + 1)) }\n}\n\n/** The segments of a JSON Pointer to something inside the report -- never '', the report itself -- unescaped (RFC 6901). */\nfunction segments(pointer: string): string[] {\n return pointer\n .slice(1)\n .split('/')\n .map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'))\n}\n\nfunction updated(value: unknown, path: readonly string[], update: (value: unknown) => unknown): unknown {\n const [head, ...rest] = path\n if (head === undefined) return update(value)\n if (Array.isArray(value)) {\n const index = Number(head)\n return value.map((item: unknown, at) => (at === index ? updated(item, rest, update) : item))\n }\n const record = value as Record<string, unknown>\n return { ...record, [head]: updated(record[head], rest, update) }\n}\n\n/**\n * `report` with the value at `pointer` replaced by what `update` makes of\n * it. Only the objects and arrays on the way to it are copied; everything\n * else is shared with `report`, which is left as it was.\n */\nexport function updateAt<T>(report: ReportDefinition, pointer: string, update: (value: T) => unknown): ReportDefinition {\n return updated(report, segments(pointer), update as (value: unknown) => unknown) as ReportDefinition\n}\n","/**\n * Commands on the component tree: insert, remove, move, update and\n * duplicate, at any depth, and the ids new components take.\n *\n * Every drag has a keyboard path (formancy.ai 0046), so these are that\n * path: a location is a region or container and an index, and an index\n * outside the list is refused, never clamped, so that a keyboard move and a\n * pointer drop that name the same place do the same thing.\n */\nimport { componentAt, walkComponents } from '@formancy/report-spec'\nimport type { Component, ComponentKind, ReportDefinition } from '@formancy/report-spec'\nimport { freshId, nextId } from '../ids.js'\nimport { checkIndex, insertedAt, patched, removedAt } from '../lists.js'\nimport type { Patch } from '../lists.js'\nimport { isRefusal, quote, refuse } from '../outcome.js'\nimport type { CommandOutcome, Refusal } from '../outcome.js'\nimport { listAt, standing, updateAt, withChildren } from '../tree.js'\nimport type { ComponentList, Location } from '../tree.js'\n\n/**\n * A change to a component of kind `K`: any of its own properties, but never\n * its id or its kind. Typed per kind, so a patch for a text cannot carry a\n * table's columns; `null` removes an optional property.\n */\nexport type ComponentPatch<K extends ComponentKind> = K extends ComponentKind ? Patch<Omit<Extract<Component, { kind: K }>, 'id' | 'kind'>> : never\n\nfunction missing(id: string): Refusal {\n return refuse('not-found', `no component is ${quote(id)}`, { componentId: id })\n}\n\n/** `component` put at `index` of `target`. */\nfunction placed(report: ReportDefinition, target: ComponentList, index: number, component: Component): CommandOutcome {\n const outside = checkIndex(index, target.list.length, `a list of ${target.list.length} components`, { path: target.pointer })\n if (outside !== undefined) return outside\n return { ok: true, report: updateAt<readonly Component[]>(report, target.pointer, (list) => insertedAt(list, index, component)) }\n}\n\nexport function insertComponent(report: ReportDefinition, location: Location, component: Component): CommandOutcome {\n const target = listAt(report, location)\n return isRefusal(target) ? target : placed(report, target, location.index, component)\n}\n\n/** Removes a component and everything it holds. */\nexport function removeComponent(report: ReportDefinition, id: string): CommandOutcome {\n const found = componentAt(report, id)\n if (found === undefined) return missing(id)\n const { pointer, index } = standing(found.path)\n return { ok: true, report: updateAt<readonly Component[]>(report, pointer, (list) => removedAt(list, index)) }\n}\n\n/**\n * Moves a component, with everything it holds, so that it ends at\n * `location`. The location is read in the report as it is without the\n * component, so moving one down its own list is its index plus one.\n */\nexport function moveComponent(report: ReportDefinition, id: string, location: Location): CommandOutcome {\n const found = componentAt(report, id)\n if (found === undefined) return missing(id)\n const parent = location.parent === undefined ? undefined : componentAt(report, location.parent)\n if (parent !== undefined && (parent.path === found.path || parent.path.startsWith(`${found.path}/`))) {\n return refuse('into-itself', `${quote(id)} cannot be moved into itself or into something it holds`, { path: found.path, componentId: id })\n }\n const { pointer, index } = standing(found.path)\n const without = updateAt<readonly Component[]>(report, pointer, (list) => removedAt(list, index))\n const target = listAt(without, location)\n return isRefusal(target) ? target : placed(without, target, location.index, found.component)\n}\n\n/**\n * Changes a component's own properties. `kind` says which kind the patch is\n * for, so the patch is typed; it is checked against the component's, for a\n * caller -- a proposal read from JSON -- whose types were never checked.\n */\nexport function updateComponent<K extends ComponentKind>(report: ReportDefinition, id: string, kind: K, patch: ComponentPatch<K>): CommandOutcome {\n const found = componentAt(report, id)\n if (found === undefined) return missing(id)\n if (found.component.kind !== kind)\n return refuse('kind-mismatch', `${quote(id)} is a ${found.component.kind}, not a ${kind}`, { path: found.path, componentId: id })\n for (const key of ['id', 'kind'] as const) {\n if (Object.hasOwn(patch, key)) {\n return refuse('immutable-property', `a component's ${key} never changes in place; insert a new component instead`, {\n path: `${found.path}/${key}`,\n componentId: id,\n })\n }\n }\n return { ok: true, report: updateAt<Component>(report, found.path, (component) => patched(component as object, patch as Patch<object>)) }\n}\n\nfunction idsOf(report: ReportDefinition): Set<string> {\n return new Set(walkComponents(report).map(({ component }) => component.id))\n}\n\n/**\n * What a new component of each kind is named after: its kind, written as an\n * identifier. A table over every kind, so a kind added to the format is\n * named too; a camelCase kind is not an identifier as it stands.\n */\nconst NAMED_AFTER: { readonly [K in ComponentKind]: string } = {\n text: 'text',\n image: 'image',\n qrCode: 'qr-code',\n epcQrCode: 'epc-qr-code',\n line: 'line',\n rectangle: 'rectangle',\n spacer: 'spacer',\n columns: 'columns',\n section: 'section',\n table: 'table',\n chart: 'chart',\n pageBreak: 'page-break',\n keepTogether: 'keep-together',\n}\n\n/**\n * An id no component in `report` has: `prefix` itself when it is free, and\n * otherwise `prefix-2`, `prefix-3` and so on, counted from the prefix's base\n * when it already ends in a number. A component kind is a prefix too, the\n * palette's: `pageBreak` gives `page-break`. Throws a RangeError for any\n * other prefix that is not an identifier, which would give an id the\n * validator refuses.\n */\nexport function nextComponentId(report: ReportDefinition, prefix: string): string {\n const named = Object.hasOwn(NAMED_AFTER, prefix) ? NAMED_AFTER[prefix as ComponentKind] : prefix\n return nextId(named, idsOf(report), prefix)\n}\n\n/** A copy of `component` and all it holds, each given a fresh id, recorded in `taken` as it is given. */\nfunction renamed(component: Component, taken: Set<string>): Component {\n const id = freshId(component.id, taken)\n taken.add(id)\n return withChildren({ ...component, id }, (list) => list.map((child) => renamed(child, taken)))\n}\n\n/** Copies a component, and everything it holds, to just after it, with fresh ids; the outcome says the copy's id. */\nexport function duplicateComponent(report: ReportDefinition, id: string): CommandOutcome<{ readonly id: string }> {\n const found = componentAt(report, id)\n if (found === undefined) return missing(id)\n const copy = renamed(found.component, idsOf(report))\n const { pointer, index } = standing(found.path)\n return { ok: true, report: updateAt<readonly Component[]>(report, pointer, (list) => insertedAt(list, index + 1, copy)), id: copy.id }\n}\n","/**\n * Commands on what a report declares: print styles, datasets and their\n * fields, parameters, assets and aggregates.\n *\n * Every declaration is a list of objects with an id (0007), so one pair of\n * operations serves them all: a put, which replaces the declaration with\n * that id where it stands or appends a new one, and a remove. The id is the\n * key, and the body is everything else, so a put cannot rename: renaming\n * would leave every reference to the old id behind.\n *\n * A remove does not chase references. Removing a style a component still\n * uses gives a report the validator refuses, so the session refuses the\n * edit with the validator's `unknown-style` at each place that uses it,\n * which is what an author needs to see before deciding.\n *\n * An asset has an add besides, which never replaces: an image a person adds\n * is named before a host keeps its bytes under that id and digest, and only\n * then declared (0033), so a put under an id the report came to declare\n * meanwhile would swap another image for it, unseen. `nextAssetId` names\n * it, by the rule a new component's id is made by, the file's name\n * numbered as it stands.\n */\nimport type { AggregateDef, AssetRef, DatasetContract, DatasetRole, FieldContract, ParameterDef, PrintStyle, ReportDefinition } from '@formancy/report-spec'\nimport { checkPrefix, freshId } from '../ids.js'\nimport { checkIndex, movedTo, removedAt, replacedAt } from '../lists.js'\nimport { quote, refuse } from '../outcome.js'\nimport type { CommandOutcome, Refusal } from '../outcome.js'\n\ninterface Declared {\n readonly id: string\n}\n\n/** `list` with the declaration `id` replaced where it stands, or appended. */\nfunction put<T extends Declared>(list: readonly T[], id: string, body: Omit<T, 'id'>): T[] {\n const item = { id, ...body } as unknown as T\n const index = list.findIndex((existing) => existing.id === id)\n return index === -1 ? [...list, item] : replacedAt(list, index, item)\n}\n\n/** `list` without the declaration `id`, or a refusal pointing at the list. */\nfunction remove<T extends Declared>(list: readonly T[], id: string, path: string, what: string): T[] | Refusal {\n const index = list.findIndex((existing) => existing.id === id)\n return index === -1 ? refuse('not-found', `no ${what} is ${quote(id)}`, { path }) : removedAt(list, index)\n}\n\n/** `report` with `key` set to `list`, or the refusal. */\nfunction withList<K extends 'styles' | 'parameters' | 'assets' | 'aggregates'>(\n report: ReportDefinition,\n key: K,\n list: ReportDefinition[K] | Refusal,\n): CommandOutcome {\n return 'ok' in list ? list : { ok: true, report: { ...report, [key]: list } }\n}\n\nexport function putStyle(report: ReportDefinition, id: string, style: Omit<PrintStyle, 'id'>): CommandOutcome {\n return withList(report, 'styles', put(report.styles, id, style))\n}\n\nexport function removeStyle(report: ReportDefinition, id: string): CommandOutcome {\n return withList(report, 'styles', remove(report.styles, id, '/styles', 'style'))\n}\n\nexport function putParameter(report: ReportDefinition, id: string, parameter: Omit<ParameterDef, 'id'>): CommandOutcome {\n return withList(report, 'parameters', put(report.parameters, id, parameter))\n}\n\nexport function removeParameter(report: ReportDefinition, id: string): CommandOutcome {\n return withList(report, 'parameters', remove(report.parameters, id, '/parameters', 'parameter'))\n}\n\n/** The parameter `id` moved so that it ends at `index`: the order the parameter form shows. */\nexport function moveParameter(report: ReportDefinition, id: string, index: number): CommandOutcome {\n const from = report.parameters.findIndex((parameter) => parameter.id === id)\n if (from === -1) return refuse('not-found', `no parameter is ${quote(id)}`, { path: '/parameters' })\n const outside = checkIndex(index, report.parameters.length - 1, 'the parameters', { path: '/parameters' })\n return outside ?? { ok: true, report: { ...report, parameters: movedTo(report.parameters, from, index) } }\n}\n\nexport function putAsset(report: ReportDefinition, id: string, asset: Omit<AssetRef, 'id'>): CommandOutcome {\n return withList(report, 'assets', put(report.assets, id, asset))\n}\n\n/** The asset appended under `id`; refused as `already-declared` when the report declares one under it already. */\nexport function addAsset(report: ReportDefinition, id: string, asset: Omit<AssetRef, 'id'>): CommandOutcome {\n if (report.assets.some((existing) => existing.id === id))\n return refuse('already-declared', `an asset is already declared as ${quote(id)}; an add never replaces one`, { path: '/assets' })\n return withList(report, 'assets', put(report.assets, id, asset))\n}\n\n/**\n * An id no asset of `report` has, and none of `handed`: `base` itself when\n * it is free, and otherwise `base-2`, `base-3` and so on, shortened so that\n * its number fits, as a new component's is. The base is a file's name,\n * folded, so a number it ends in is its own and is numbered too:\n * `img-4711` taken gives `img-4711-2`. Assets are a namespace of their own\n * (0007), so a component's id does not count; `handed` holds the ids a\n * builder has handed a host already, which an undo may declare again for\n * the bytes it handed under them (0033). Throws a RangeError for a base\n * that is not an identifier.\n */\nexport function nextAssetId(report: ReportDefinition, base: string, handed: ReadonlySet<string> = new Set()): string {\n checkPrefix(base)\n return freshId(base, new Set([...handed, ...report.assets.map(({ id }) => id)]), base)\n}\n\nexport function removeAsset(report: ReportDefinition, id: string): CommandOutcome {\n return withList(report, 'assets', remove(report.assets, id, '/assets', 'asset'))\n}\n\nexport function putAggregate(report: ReportDefinition, id: string, aggregate: Omit<AggregateDef, 'id'>): CommandOutcome {\n return withList(report, 'aggregates', put(report.aggregates, id, aggregate))\n}\n\nexport function removeAggregate(report: ReportDefinition, id: string): CommandOutcome {\n return withList(report, 'aggregates', remove(report.aggregates, id, '/aggregates', 'aggregate'))\n}\n\n/** The dataset in `slot`: the header or the detail contract, replaced whole. */\nexport function putDataset(report: ReportDefinition, slot: DatasetRole, contract: DatasetContract): CommandOutcome {\n return { ok: true, report: { ...report, datasets: { ...report.datasets, [slot]: contract } } }\n}\n\nexport function removeDataset(report: ReportDefinition, slot: DatasetRole): CommandOutcome {\n if (report.datasets[slot] === undefined) return refuse('not-found', `the report declares no ${slot} dataset`, { path: `/datasets/${slot}` })\n const { [slot]: _removed, ...datasets } = report.datasets\n return { ok: true, report: { ...report, datasets } }\n}\n\n/** `report` with the fields of the dataset in `slot` changed by `change`, or a refusal when there is no such dataset. */\nfunction withFields(\n report: ReportDefinition,\n slot: DatasetRole,\n change: (fields: readonly FieldContract[]) => readonly FieldContract[] | Refusal,\n): CommandOutcome {\n const dataset = report.datasets[slot]\n if (dataset === undefined) return refuse('not-found', `the report declares no ${slot} dataset`, { path: `/datasets/${slot}` })\n const fields = change(dataset.fields)\n return 'ok' in fields ? fields : { ok: true, report: { ...report, datasets: { ...report.datasets, [slot]: { ...dataset, fields } } } }\n}\n\nexport function putField(report: ReportDefinition, slot: DatasetRole, fieldId: string, field: Omit<FieldContract, 'id'>): CommandOutcome {\n return withFields(report, slot, (fields) => put(fields, fieldId, field))\n}\n\nexport function removeField(report: ReportDefinition, slot: DatasetRole, fieldId: string): CommandOutcome {\n return withFields(report, slot, (fields) => remove(fields, fieldId, `/datasets/${slot}/fields`, `field of the ${slot} dataset`))\n}\n","/**\n * Commands on the report as a whole: its title, its locale, its page, and\n * the whole document at once.\n */\nimport type { Margins, Orientation, PageSizeName, ReportDefinition } from '@formancy/report-spec'\nimport { patched } from '../lists.js'\nimport type { CommandOutcome } from '../outcome.js'\n\nexport function setTitle(report: ReportDefinition, title: string): CommandOutcome {\n return { ok: true, report: { ...report, title } }\n}\n\nexport function setLocale(report: ReportDefinition, locale: string): CommandOutcome {\n return { ok: true, report: { ...report, locale } }\n}\n\n/** A change to the page: its size, its orientation, any of its margins. */\nexport interface PagePatch {\n readonly size?: PageSizeName\n readonly orientation?: Orientation\n readonly margins?: Partial<Margins>\n}\n\nexport function setPage(report: ReportDefinition, patch: PagePatch): CommandOutcome {\n const { margins, ...rest } = patch\n const page = { ...patched(report.page, rest), margins: margins === undefined ? report.page.margins : { ...report.page.margins, ...margins } }\n return { ok: true, report: { ...report, page } }\n}\n\n/**\n * The whole document, replaced: a paste, an import, an AI proposal that\n * rewrote the report. Taken as one edit, so the session validates it and\n * records it as one undo step like any other.\n */\nexport function replaceDocument(_report: ReportDefinition, next: ReportDefinition): CommandOutcome {\n return { ok: true, report: next }\n}\n","/**\n * Commands on the report's e-invoice: the one EN 16931 invoice a report may\n * carry, of either kind\n * ([0027](../../../../docs/decisions/0027-a-report-carries-one-en-16931-invoice-written-from-the-values-its-page-prints.md),\n * [0038](../../../../docs/decisions/0038-a-reports-e-invoice-may-be-an-xrechnung-3-0-whose-xml-a-host-takes-and-whose-pdf-is-its-labelled-copy.md)),\n * put in whole, patched term by term and taken away; and the account it\n * shares with every payment code printed with it, changed in one edit\n * ([0044](../../../../docs/decisions/0044-a-person-edits-a-reports-e-invoice-in-either-builder-one-term-a-field-in-groups.md)).\n *\n * The e-invoice belongs to the report, not to a region, so these name no\n * place. Whether what they leave is an invoice EN 16931's and XRechnung's\n * rules accept -- its rates, its parties, what an XRechnung needs, an\n * account each code can pay -- is report-spec's question, which the session\n * asks of every edit alike (0008): a command here judges nothing of the\n * invoice but that there is one to change.\n */\nimport { walkComponents } from '@formancy/report-spec'\nimport type { EInvoice, FacturXInvoice, Inline, ReportDefinition, XRechnungInvoice } from '@formancy/report-spec'\nimport { patched } from '../lists.js'\nimport type { Patch } from '../lists.js'\nimport { refuse } from '../outcome.js'\nimport type { CommandOutcome, Refusal } from '../outcome.js'\nimport { updateAt } from '../tree.js'\n\n/**\n * A change to some of an e-invoice's terms, but never its kind: `null`\n * removes an optional one, as JSON carries a removal. A term of the other\n * kind -- an XRechnung's version in a Factur-X invoice -- is the\n * validator's to refuse.\n */\nexport type EInvoicePatch = Patch<Omit<FacturXInvoice, 'kind'>> & Patch<Pick<XRechnungInvoice, 'version'>>\n\nconst PATH = '/eInvoice'\n\nfunction missing(): Refusal {\n return refuse('not-found', 'the report has no e-invoice', { path: PATH })\n}\n\n/** The report with `invoice` for its e-invoice: added where it has none, in place of the one it has otherwise. */\nexport function putEInvoice(report: ReportDefinition, invoice: EInvoice): CommandOutcome {\n return { ok: true, report: { ...report, eInvoice: invoice } }\n}\n\n/** The report without its e-invoice. */\nexport function removeEInvoice(report: ReportDefinition): CommandOutcome {\n if (report.eInvoice === undefined) return missing()\n const { eInvoice: _removed, ...rest } = report\n return { ok: true, report: rest }\n}\n\n/** The report's e-invoice with `patch` applied; its kind never changes in place. */\nexport function updateEInvoice(report: ReportDefinition, patch: EInvoicePatch): CommandOutcome {\n const invoice = report.eInvoice\n if (invoice === undefined) return missing()\n if (Object.hasOwn(patch, 'kind'))\n return refuse('immutable-property', \"an e-invoice's kind never changes in place; put a new e-invoice instead\", { path: `${PATH}/kind` })\n return { ok: true, report: { ...report, eInvoice: patched(invoice, patch as Patch<EInvoice>) } }\n}\n\n/** Whether every run of `runs` is literal text: what no data can change, and what an edit may write over. */\nfunction literal(runs: readonly Inline[]): boolean {\n return runs.every((run) => run.kind === 'text')\n}\n\n/** The refusal for an account the report reads from the data at `path`, which the command would write over with a literal. */\nfunction readFromData(place: string, path: string, componentId?: string): Refusal {\n return refuse(\n 'read-from-data',\n `${place} reads its account from the data, which says what it is at the render; bind the e-invoice's account and its payment codes alike, or write them alike`,\n {\n path,\n ...(componentId === undefined ? {} : { componentId }),\n },\n )\n}\n\n/**\n * The report with `account` as the account its e-invoice names (BT-84)\n * and every payment code printed with it asks to be paid to -- its\n * QR-bill's and each EPC QR code's, shown or hidden -- each as one literal\n * run, as typed: one edit, so one undo step, where an edit of any one of\n * them alone is refused, since report-spec holds each code to BT-84 (0027).\n * Refused where the report has no e-invoice, whose codes share no account,\n * or one that names no account; and where one of them reads its account\n * from the data, which this would write over. Whether the account is one\n * each place takes -- an IBAN of SEPA's, a QR-bill's of Switzerland or\n * Liechtenstein, no QR-IBAN in euro -- the validator says, each place by\n * its own rule. A BIC is left as it is: no rule holds a code's to BT-86.\n */\nexport function setPaymentAccount(report: ReportDefinition, account: string): CommandOutcome {\n const payment = report.eInvoice?.payment\n if (report.eInvoice === undefined) return missing()\n if (payment === undefined) return refuse('not-found', 'the e-invoice names no account: its payment instructions (BG-16) give it', { path: `${PATH}/payment` })\n if (!literal(payment.iban)) return readFromData(\"the e-invoice's payment account (BT-84)\", `${PATH}/payment/iban`)\n const bill = report.paymentPart\n if (bill !== undefined && !literal(bill.account)) return readFromData('the QR-bill', '/paymentPart/account')\n const codes = walkComponents(report).filter(({ component }) => component.kind === 'epcQrCode')\n for (const { component, path } of codes) {\n if (component.kind === 'epcQrCode' && !literal(component.iban)) return readFromData('the EPC QR code', `${path}/iban`, component.id)\n }\n const runs: readonly Inline[] = [{ kind: 'text', text: account }]\n let next: ReportDefinition = { ...report, eInvoice: { ...report.eInvoice, payment: { ...payment, iban: runs } } }\n if (bill !== undefined) next = { ...next, paymentPart: { ...bill, account: runs } }\n for (const { path } of codes) next = updateAt<object>(next, path, (code) => ({ ...code, iban: runs }))\n return { ok: true, report: next }\n}\n","/**\n * Commands on a first page's own header: what page 1 prints at its top in\n * place of the page header, which then prints from page 2 on\n * ([0060](../../../../docs/decisions/0060-a-reports-first-page-may-print-a-header-of-its-own-or-none-in-place-of-the-page-header.md)).\n *\n * Its presence is the choice: absent, page 1 prints the page header; an\n * empty one prints no header. So these two make the choice, a header of\n * its own put in whole or taken away, and every component command edits\n * what stands in it once it is there. Whether what it holds may stand\n * there -- no table, no page number -- is report-spec's question, which\n * the session asks of every edit alike (0008).\n */\nimport type { Component, ReportDefinition } from '@formancy/report-spec'\nimport { refuse } from '../outcome.js'\nimport type { CommandOutcome } from '../outcome.js'\n\nconst PATH = '/regions/firstPageHeader'\n\n/** The report with `components` for page 1's own header: added where it has none, in place of the one it has otherwise; none, page 1 prints no header. */\nexport function putFirstPageHeader(report: ReportDefinition, components: readonly Component[]): CommandOutcome {\n return { ok: true, report: { ...report, regions: { ...report.regions, firstPageHeader: components } } }\n}\n\n/** The report without page 1's own header, what it holds with it: page 1 prints the page header again. */\nexport function removeFirstPageHeader(report: ReportDefinition): CommandOutcome {\n if (report.regions.firstPageHeader === undefined) return refuse('not-found', 'page 1 prints the page header, and has no header of its own', { path: PATH })\n const { firstPageHeader: _removed, ...regions } = report.regions\n return { ok: true, report: { ...report, regions } }\n}\n","/**\n * Commands on the report's payment part: the one Swiss QR-bill a report may\n * print at the foot of its last page\n * ([0022](../../../../docs/decisions/0022-a-report-carries-one-swiss-qr-bill-at-the-foot-of-its-last-page.md)),\n * put in whole, patched field by field and taken away\n * ([0039](../../../../docs/decisions/0039-a-person-selects-a-reports-qr-bill-and-edits-it-field-by-field-in-either-builder.md)).\n *\n * The bill belongs to the report, not to a region, so these name no place.\n * Whether what they leave is a bill SIX's rules accept -- its IBAN's check\n * digits, its reference beside its account, its page -- is report-spec's\n * question, which the session asks of every edit alike (0008): a command\n * here judges nothing of the bill but that there is one to change.\n */\nimport type { PaymentPart, ReportDefinition } from '@formancy/report-spec'\nimport { patched } from '../lists.js'\nimport type { Patch } from '../lists.js'\nimport { refuse } from '../outcome.js'\nimport type { CommandOutcome, Refusal } from '../outcome.js'\n\n/** A change to some of a bill's properties, but never its kind: `null` removes an optional one, as JSON carries a removal. */\nexport type PaymentPartPatch = Patch<Omit<PaymentPart, 'kind'>>\n\nconst PATH = '/paymentPart'\n\nfunction missing(): Refusal {\n return refuse('not-found', 'the report has no payment part', { path: PATH })\n}\n\n/** The report with `part` for its payment part: added where it has none, in place of the one it has otherwise. */\nexport function putPaymentPart(report: ReportDefinition, part: PaymentPart): CommandOutcome {\n return { ok: true, report: { ...report, paymentPart: part } }\n}\n\n/** The report without its payment part. */\nexport function removePaymentPart(report: ReportDefinition): CommandOutcome {\n if (report.paymentPart === undefined) return missing()\n const { paymentPart: _removed, ...rest } = report\n return { ok: true, report: rest }\n}\n\n/** The report's payment part with `patch` applied; its kind never changes in place. */\nexport function updatePaymentPart(report: ReportDefinition, patch: PaymentPartPatch): CommandOutcome {\n const part = report.paymentPart\n if (part === undefined) return missing()\n if (Object.hasOwn(patch, 'kind'))\n return refuse('immutable-property', \"a payment part's kind never changes in place; put a new payment part instead\", { path: `${PATH}/kind` })\n return { ok: true, report: { ...report, paymentPart: patched(part, patch as Patch<PaymentPart>) } }\n}\n","/**\n * The parts of a report the diagnostics read: every expression, with the\n * scope its place gives it and what it is for, and every style, asset,\n * field, parameter and aggregate named outside an expression -- in the\n * components, in the payment part and in the e-invoice -- and where each\n * field and aggregate is named, for what removes a field with its readers.\n *\n * One walk, so that where an expression stands is decided once: the\n * diagnostics and `compileReport`, which the runtime compiles a report with,\n * both take its sites from here.\n */\nimport { E_INVOICE_DATES, E_INVOICE_DECIMALS, E_INVOICE_LINE_CODES, E_INVOICE_LINE_COLUMNS, QR_BILL_ADDRESS_RULES, walkComponents } from '@formancy/report-spec'\nimport type {\n Component,\n ComponentKind,\n EInvoice,\n EInvoiceAddress,\n EInvoiceBuyer,\n EInvoiceDateTerm,\n EInvoiceKind,\n EInvoiceLineCode,\n EInvoiceLineColumn,\n EInvoiceSeller,\n Expression,\n FieldRef,\n FieldType,\n Format,\n Inline,\n PaymentInstructions,\n PaymentPart,\n PaymentPartKind,\n QrBillAddress,\n ReportDefinition,\n RowValue,\n SellerContact,\n StyleRule,\n TableFooterRow,\n ValueScope,\n} from '@formancy/report-spec'\n\n/** An expression and how to compile it: the names its scope binds, and the policy of what it is for. */\nexport interface ExpressionSite {\n readonly cel: string\n readonly scope: ValueScope\n /** `visible` for a condition, which must be a boolean; `computed` for a value printed. */\n readonly kind: 'visible' | 'computed'\n /** The JSON Pointer to the expression's `cel`. */\n readonly path: string\n /** The innermost component it stands in; none for an aggregate's. */\n readonly componentId?: string\n /** The table column it belongs to, for a column's value, condition or style rule. */\n readonly columnId?: string\n /** What the expression is the amount of, when it is a payment code's -- a decimal, or null to leave it for the payer. */\n readonly amount?: PaymentAmount\n /**\n * For an expression an e-invoice is written from -- one of the e-invoice's\n * own, or the value of a column that prints a term of each line -- the\n * term it gives the XML. Such an expression is part of what the\n * e-invoice's totals are computed from or written with, so it never\n * reads them.\n */\n readonly term?: InvoiceTerm\n /** For an expression a run holds, the format the run prints its value with, where it has one. */\n readonly format?: Format\n}\n\n/** What an expression gives an e-invoice's XML. */\nexport interface InvoiceTerm {\n /** As a message names it: \"the issue date (BT-2)\", or, for a run of one of the e-invoice's texts, \"a text of the e-invoice\". */\n readonly what: string\n /** The types of field it may be, given as an expression reads each -- for a line's term, report-spec's own -- absent for a run, which gives text whatever it computes. */\n readonly types?: readonly FieldType[]\n}\n\n/** The payment codes an amount is printed in, as a message names each. */\nexport type PaymentAmount = 'a QR-bill' | 'an EPC QR code'\n\n/** What an expression belongs to: a component, and within a table a column. */\ninterface Owner {\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/** An aggregate printed with a number or currency format: where, and at how many places. */\nexport interface PrintedTotal {\n readonly aggregate: string\n readonly scale: number\n /** The JSON Pointer to the format. */\n readonly path: string\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/**\n * A field or an aggregate named outside an expression, and where: the JSON\n * Pointer to what names it -- a run, a format's currency, an image's\n * source, a sort key, a group's key, an aggregate's field, a line's code\n * -- and the component and the column it stands in.\n */\nexport type NamedUse = ({ readonly kind: 'field'; readonly field: FieldRef } | { readonly kind: 'aggregate'; readonly aggregate: string }) & {\n readonly path: string\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/** Everything the report names, outside expressions, and every expression. */\nexport interface ReportParts {\n readonly expressions: readonly ExpressionSite[]\n /** Every aggregate printed with a format that rounds, in document order. */\n readonly printedTotals: readonly PrintedTotal[]\n readonly styles: readonly string[]\n readonly assets: readonly string[]\n readonly fields: readonly FieldRef[]\n readonly parameters: readonly string[]\n readonly aggregates: readonly string[]\n /** Each field and aggregate of `fields` and `aggregates`, where it is named, in document order. */\n readonly named: readonly NamedUse[]\n}\n\n/** A run of one of an e-invoice's texts: text, whatever it computes. */\nconst TEXT: InvoiceTerm = { what: 'a text of the e-invoice' }\n\n/** The table an e-invoice's lines are the rows of, and the term each column it names prints. */\ninterface LineColumns {\n readonly table: string\n readonly columns: ReadonlyMap<string, InvoiceTerm>\n}\n\n/** What one walk collects into, and the places it is collecting from. */\nclass Collector {\n readonly expressions: ExpressionSite[] = []\n readonly printedTotals: PrintedTotal[] = []\n readonly styles: string[] = []\n readonly assets: string[] = []\n readonly fields: FieldRef[] = []\n readonly parameters: string[] = []\n readonly aggregates: string[] = []\n readonly named: NamedUse[] = []\n\n private readonly lines: LineColumns | undefined\n\n constructor(lines: LineColumns | undefined) {\n this.lines = lines\n }\n\n expression(\n expression: Expression | undefined,\n path: string,\n scope: ValueScope,\n kind: ExpressionSite['kind'],\n owner: Owner = {},\n term?: InvoiceTerm,\n format?: Format,\n ): void {\n if (expression === undefined) return\n this.expressions.push({\n cel: expression.cel,\n scope,\n kind,\n path: `${path}/cel`,\n ...owner,\n ...(term === undefined ? {} : { term }),\n ...(format === undefined ? {} : { format }),\n })\n }\n\n /** The term the column `column` of the table `table` prints of each line, when the e-invoice names it. */\n lineTerm(table: string, column: string): InvoiceTerm | undefined {\n return this.lines?.table === table ? this.lines.columns.get(column) : undefined\n }\n\n style(style: string | undefined): void {\n if (style !== undefined) this.styles.push(style)\n }\n\n /** A field named at `path`, outside an expression. */\n field(field: FieldRef, path: string, owner: Owner): void {\n this.fields.push(field)\n this.named.push({ kind: 'field', field, path, ...owner })\n }\n\n /** An aggregate named at `path`, outside an expression. */\n aggregate(aggregate: string, path: string, owner: Owner): void {\n this.aggregates.push(aggregate)\n this.named.push({ kind: 'aggregate', aggregate, path, ...owner })\n }\n\n /** Style rules: each a condition read in `scope`, and a style. */\n rules(rules: readonly StyleRule[] | undefined, path: string, scope: ValueScope, owner: Owner): void {\n for (const [index, rule] of (rules ?? []).entries()) {\n this.expression(rule.when, `${path}/${index}/when`, scope, 'visible', owner)\n this.style(rule.style)\n }\n }\n\n format(format: Format | undefined, path: string, owner: Owner): void {\n if (format?.kind !== 'currency') return\n if (format.currency.kind === 'field') this.field(format.currency.field, `${path}/currency`, owner)\n if (format.currency.kind === 'parameter') this.parameters.push(format.currency.parameter)\n }\n\n inline(inline: Inline, path: string, scope: ValueScope, owner: Owner, term?: InvoiceTerm): void {\n if (inline.kind === 'field') this.field(inline.field, path, owner)\n if (inline.kind === 'parameter') this.parameters.push(inline.parameter)\n if (inline.kind === 'aggregate') this.aggregate(inline.aggregate, path, owner)\n if (inline.kind === 'aggregate' && (inline.format?.kind === 'number' || inline.format?.kind === 'currency')) {\n this.printedTotals.push({ aggregate: inline.aggregate, scale: inline.format.scale, path: `${path}/format`, ...owner })\n }\n if (inline.kind === 'expression') this.expression(inline.expression, `${path}/expression`, scope, 'computed', owner, term, inline.format)\n if ('format' in inline) this.format(inline.format, `${path}/format`, owner)\n }\n\n inlines(inlines: readonly Inline[], path: string, scope: ValueScope, owner: Owner, term?: InvoiceTerm): void {\n for (const [index, inline] of inlines.entries()) this.inline(inline, `${path}/${index}`, scope, owner, term)\n }\n\n /** A text of an e-invoice, read as a paragraph's in the report's scope; absent, it holds none. */\n invoiceText(inlines: readonly Inline[] | undefined, path: string): void {\n if (inlines !== undefined) this.inlines(inlines, path, 'report', {}, TEXT)\n }\n\n /** A code read from each of an e-invoice's lines: a detail field, or an expression in the row's scope. */\n lineCode(value: RowValue, path: string, term: InvoiceTerm): void {\n if (value.kind === 'field') this.field(value.field, path, {})\n else this.expression(value.expression, `${path}/expression`, 'row', 'computed', {}, term)\n }\n\n /** A payment code's amount: a value, read in the report's scope. */\n amount(expression: Expression | undefined, path: string, of: PaymentAmount, owner: Owner): void {\n if (expression !== undefined) this.expressions.push({ cel: expression.cel, scope: 'report', kind: 'computed', path: `${path}/cel`, ...owner, amount: of })\n }\n\n /** A text a code holds, read as a paragraph's in the report's scope; absent, it holds none. */\n optionalInlines(inlines: readonly Inline[] | undefined, path: string, owner: Owner): void {\n if (inlines !== undefined) this.inlines(inlines, path, 'report', owner)\n }\n\n /** Each part of an address, in the order the code holds them; a party absent holds none. */\n address(address: QrBillAddress | undefined, path: string): void {\n for (const part of Object.keys(QR_BILL_ADDRESS_RULES) as (keyof QrBillAddress)[]) {\n const runs = address?.[part]\n if (runs !== undefined) this.inlines(runs, `${path}/${part}`, 'report', {})\n }\n }\n\n footer(rows: readonly TableFooterRow[] | undefined, path: string, scope: ValueScope, owner: Owner): void {\n for (const [index, row] of (rows ?? []).entries()) {\n for (const [at, cell] of row.cells.entries()) this.inline(cell.value, `${path}/${index}/cells/${at}/value`, scope, owner)\n this.style(row.style)\n }\n }\n}\n\ntype Reader<K extends ComponentKind> = (component: Extract<Component, { kind: K }>, path: string, into: Collector) => void\n\nconst NOTHING = (): void => undefined\n\n/**\n * What each kind holds beyond what every component has. A table over every\n * kind, so a kind added to the format without saying what it names does not\n * compile. What a container holds is visited by the walk itself.\n */\nconst READERS: { readonly [K in ComponentKind]: Reader<K> } = {\n text: (text, path, into) => into.inlines(text.content, `${path}/content`, 'report', { componentId: text.id }),\n image: (image, path, into) => {\n if (image.source.kind === 'asset') into.assets.push(image.source.asset)\n else into.field(image.source.field, `${path}/source`, { componentId: image.id })\n },\n // What a QR code encodes is what its content prints, read as a\n // paragraph's in the same place.\n qrCode: (code, path, into) => into.inlines(code.content, `${path}/content`, 'report', { componentId: code.id }),\n // What an EPC QR code encodes, in the order its payload holds it: each\n // text read as a paragraph's in its place, its amount as a value, all\n // named after the code.\n epcQrCode: (code, path, into) => {\n const owner = { componentId: code.id }\n into.optionalInlines(code.bic, `${path}/bic`, owner)\n into.inlines(code.beneficiary, `${path}/beneficiary`, 'report', owner)\n into.inlines(code.iban, `${path}/iban`, 'report', owner)\n into.amount(code.amount, `${path}/amount`, 'an EPC QR code', owner)\n for (const key of ['reference', 'text', 'information'] as const) into.optionalInlines(code[key], `${path}/${key}`, owner)\n },\n line: NOTHING,\n rectangle: NOTHING,\n spacer: NOTHING,\n columns: NOTHING,\n section: NOTHING,\n pageBreak: NOTHING,\n keepTogether: NOTHING,\n // A table's condition is read once per detail row, as its cells are,\n // and is the table's own: it goes with the table (0062). Its total rows\n // read the table's totals, and its group's rows the group's too.\n table: (table, path, into) => {\n into.expression(table.rowsWhen, `${path}/rowsWhen`, 'row', 'visible', { componentId: table.id })\n into.style(table.headerStyle)\n for (const [index, column] of table.columns.entries()) {\n const at = `${path}/columns/${index}`\n const owner = { componentId: table.id, columnId: column.id }\n // A column's value and style rules are read per row; whether it shows\n // is read once per report.\n into.inline(column.value, `${at}/value`, 'row', owner, into.lineTerm(table.id, column.id))\n into.expression(column.visibleWhen, `${at}/visibleWhen`, 'report', 'visible', owner)\n into.style(column.style)\n into.rules(column.styleWhen, `${at}/styleWhen`, 'row', owner)\n }\n const owner = { componentId: table.id }\n for (const [index, key] of (table.sort ?? []).entries()) into.field(key.field, `${path}/sort/${index}`, owner)\n if (table.group !== undefined) {\n into.field(table.group.by, `${path}/group/by`, owner)\n into.inlines(table.group.header, `${path}/group/header`, 'group', owner)\n into.style(table.group.headerStyle)\n into.footer(table.group.footer, `${path}/group/footer`, 'group', owner)\n }\n into.footer(table.totals, `${path}/totals`, 'table', owner)\n },\n // A chart holds no expression: it names the field it groups by, the field\n // each series totals (a count of rows names none), and the currency its\n // formats print in, all after the chart.\n chart: (chart, path, into) => {\n const owner = { componentId: chart.id }\n into.field(chart.category.field, `${path}/category/field`, owner)\n for (const [index, series] of chart.series.entries()) if (series.of !== undefined) into.field(series.of, `${path}/series/${index}/of`, owner)\n into.format(chart.category.format, `${path}/category/format`, owner)\n into.format(chart.valueFormat, `${path}/valueFormat`, owner)\n },\n}\n\ntype PartReader<K extends PaymentPartKind> = (part: Extract<PaymentPart, { kind: K }>, path: string, into: Collector) => void\n\n/**\n * What each kind of payment part holds. A table over every kind, as\n * READERS is. A bill stands in no component: its texts are read as a\n * paragraph's in the report's scope, named by their paths alone, in the\n * order the code holds them.\n */\nconst PAYMENT_PARTS: { readonly [K in PaymentPartKind]: PartReader<K> } = {\n swissQrBill: (bill, path, into) => {\n into.inlines(bill.account, `${path}/account`, 'report', {})\n into.address(bill.creditor, `${path}/creditor`)\n into.amount(bill.amount, `${path}/amount`, 'a QR-bill', {})\n into.address(bill.debtor, `${path}/debtor`)\n for (const key of ['reference', 'message', 'billingInformation'] as const) into.optionalInlines(bill[key], `${path}/${key}`, {})\n },\n}\n\ntype InvoiceReader<K extends EInvoiceKind> = (invoice: Extract<EInvoice, { kind: K }>, path: string, into: Collector) => void\n\n/** A date term: a date, read as its ISO string, as a date field is. */\nconst date = (term: EInvoiceDateTerm): InvoiceTerm => ({ what: E_INVOICE_DATES[term].what, types: ['date'] })\n\n/** The keys of a table over every key of `T`: one added to the format without being read here does not compile. */\nconst keysOf = <T>(table: { readonly [K in keyof T]-?: true }): readonly (keyof T)[] => Object.keys(table) as (keyof T)[]\n\n/** The texts of each party, of the seller's contact and of an address, and of the payment instructions, in the order the type holds them. */\nconst SELLER_TEXTS = keysOf<Omit<EInvoiceSeller, 'legalId' | 'electronicAddress' | 'contact' | 'address'>>({ name: true, vatId: true, taxNumber: true })\nconst BUYER_TEXTS = keysOf<Omit<EInvoiceBuyer, 'legalId' | 'electronicAddress' | 'address'>>({ name: true, vatId: true })\nconst CONTACT_TEXTS = keysOf<SellerContact>({ name: true, telephone: true, email: true })\nconst ADDRESS_TEXTS = keysOf<EInvoiceAddress>({ line1: true, line2: true, postalCode: true, city: true, country: true })\nconst PAYMENT_TEXTS = keysOf<Omit<PaymentInstructions, 'means'>>({ iban: true, bic: true, accountName: true, remittance: true })\n\n/** A party's texts, its legal registration's, its electronic address's, the seller's contact's and its address's, in the order the type holds them. */\nfunction party<P extends EInvoiceSeller | EInvoiceBuyer>(held: P, texts: readonly (keyof P)[], path: string, into: Collector): void {\n for (const key of texts) into.invoiceText(held[key] as readonly Inline[] | undefined, `${path}/${String(key)}`)\n into.invoiceText(held.legalId?.id, `${path}/legalId/id`)\n into.invoiceText(held.electronicAddress?.id, `${path}/electronicAddress/id`)\n const contact = 'contact' in held ? held.contact : undefined\n for (const key of CONTACT_TEXTS) into.invoiceText(contact?.[key], `${path}/contact/${key}`)\n for (const part of ADDRESS_TEXTS) into.invoiceText(held.address[part], `${path}/address/${part}`)\n}\n\n/**\n * EN 16931's terms, which an e-invoice of either kind holds. An e-invoice\n * stands in no component: its texts are read as a paragraph's in the\n * report's scope, its dates and its paid amount as values there, and its\n * line codes in each row's, as what an aggregate reads from each row is;\n * each is named by its path alone, in the order the type holds them. The\n * columns its lines are printed by are read where they stand, in the\n * table.\n */\nconst en16931 = (invoice: EInvoice, path: string, into: Collector): void => {\n into.invoiceText(invoice.number, `${path}/number`)\n into.expression(invoice.issued, `${path}/issued`, 'report', 'computed', {}, date('BT-2'))\n into.invoiceText(invoice.businessProcess, `${path}/businessProcess`)\n party(invoice.seller, SELLER_TEXTS, `${path}/seller`, into)\n party(invoice.buyer, BUYER_TEXTS, `${path}/buyer`, into)\n into.invoiceText(invoice.buyerReference, `${path}/buyerReference`)\n into.expression(invoice.delivered, `${path}/delivered`, 'report', 'computed', {}, date('BT-72'))\n into.expression(invoice.period?.start, `${path}/period/start`, 'report', 'computed', {}, date('BT-73'))\n into.expression(invoice.period?.end, `${path}/period/end`, 'report', 'computed', {}, date('BT-74'))\n for (const [index, category] of invoice.vat.entries()) into.invoiceText(category.reason, `${path}/vat/${index}/reason`)\n for (const key of Object.keys(E_INVOICE_LINE_CODES) as EInvoiceLineCode[])\n into.lineCode(invoice.lines[key], `${path}/lines/${key}`, E_INVOICE_LINE_CODES[key])\n for (const key of PAYMENT_TEXTS) into.invoiceText(invoice.payment?.[key], `${path}/payment/${key}`)\n into.expression(invoice.due, `${path}/due`, 'report', 'computed', {}, date('BT-9'))\n into.invoiceText(invoice.terms, `${path}/terms`)\n into.expression(invoice.paid, `${path}/paid`, 'report', 'computed', {}, { what: E_INVOICE_DECIMALS['BT-113'].what, types: ['decimal'] })\n}\n\n/** What each kind of e-invoice holds. A table over every kind, as PAYMENT_PARTS is: an XRechnung's expressions are where a Factur-X invoice's are, its version and the profile being none (0038). */\nconst E_INVOICES: { readonly [K in EInvoiceKind]: InvoiceReader<K> } = {\n facturX: en16931,\n xrechnung: en16931,\n}\n\n/** The table an e-invoice's lines are the rows of, and the term each column it names prints. */\nfunction lineColumns(invoice: EInvoice | undefined): LineColumns | undefined {\n if (invoice === undefined) return undefined\n const named = Object.keys(E_INVOICE_LINE_COLUMNS) as EInvoiceLineColumn[]\n return { table: invoice.lines.table, columns: new Map(named.map((key) => [invoice.lines[key], E_INVOICE_LINE_COLUMNS[key]])) }\n}\n\n/** Every expression and every name the report holds, in document order -- the components, the payment part, the e-invoice -- the aggregates' expressions last. */\nexport function reportParts(report: ReportDefinition): ReportParts {\n const into = new Collector(lineColumns(report.eInvoice))\n for (const { component, path } of walkComponents(report)) {\n const owner = { componentId: component.id }\n into.expression(component.visibleWhen, `${path}/visibleWhen`, 'report', 'visible', owner)\n into.style(component.style)\n into.rules(component.styleWhen, `${path}/styleWhen`, 'report', owner)\n ;(READERS[component.kind] as Reader<ComponentKind>)(component, path, into)\n }\n if (report.paymentPart !== undefined) PAYMENT_PARTS[report.paymentPart.kind](report.paymentPart, '/paymentPart', into)\n if (report.eInvoice !== undefined) (E_INVOICES[report.eInvoice.kind] as InvoiceReader<EInvoiceKind>)(report.eInvoice, '/eInvoice', into)\n for (const [index, aggregate] of report.aggregates.entries()) {\n // What an aggregate reads, it reads from each detail row.\n if (aggregate.of?.kind === 'field') into.field(aggregate.of.field, `/aggregates/${index}/of`, {})\n if (aggregate.of?.kind === 'expression') into.expression(aggregate.of.expression, `/aggregates/${index}/of/expression`, 'row', 'computed')\n }\n return into\n}\n\n/** Every expression in the report, each with the scope it is compiled in and what it is for. */\nexport function expressionSites(report: ReportDefinition): readonly ExpressionSite[] {\n return reportParts(report).expressions\n}\n","/**\n * What the diagnostics can say about a valid report, as stable codes, each\n * with the severity it always has.\n *\n * A diagnostic is not a validation error. The report it is about is valid:\n * the session holds nothing else. An error here is one the runtime will\n * refuse to render -- an expression that does not compile, or reads\n * something that is not there -- which plan 15 puts at its second level, the\n * bindings; a warning is something an author probably did not mean, and\n * renders as written.\n */\nimport type { SourceSpan } from '@formancy/expressions'\n\nexport const DIAGNOSTIC_SEVERITIES = {\n /** An expression that does not parse. */\n 'expression-syntax': 'error',\n /** An expression past a structural limit of `@formancy/expressions`: too deep, too many nodes, too long a list. */\n 'expression-limit': 'error',\n /** An expression whose types do not meet, each member read as the type it is declared: an integer parameter added to a string, a decimal field compared with an integer, a decimal converted with dec() again; a QR-bill's or an EPC QR code's amount that gives anything but a decimal or null; or an e-invoice's date, paid amount or line term that gives what its term is not. */\n 'expression-type': 'error',\n /** An expression its place does not allow: a condition that is not a boolean, a function its kind forbids. */\n 'expression-policy': 'error',\n /** An expression that reads a name, or a member of one, that nothing declares, or a member of a single value; or an e-invoice's total where there is none, or where it is computed from. */\n 'expression-unknown-name': 'error',\n /** An expression that reads `row`, `table` or `group` where there is no row, table or group. */\n 'expression-out-of-scope': 'error',\n /** An expression that reads an image field, which is drawn and never read. */\n 'expression-unreadable-field': 'error',\n /** An expression that calls the clock or a random draw, so two renders of the same data could differ. */\n 'expression-not-reproducible': 'error',\n /** An expression that computes with a double, which is not exact, or divides with `/`, which on integers drops the remainder: `dec(\"…\")` and `divide(dec(a), dec(b), places)` keep a number exact. */\n 'expression-inexact': 'error',\n /** An expression that calls `matches()`, whose backtracking pattern can run for as long as it likes inside one step of the budget. */\n 'expression-unbounded': 'error',\n /** An expression that reads a name whole -- `size(params)`, `row[key]` -- rather than a member by its id: what it reads cannot be checked, and is never bound. */\n 'expression-dynamic-read': 'error',\n /** An aggregate's expression that gives a value its function cannot total: a sum of strings, an average of instants. */\n 'expression-aggregate-type': 'error',\n /** An aggregate whose expression reads its own total, directly or through other aggregates, or reads one that does: none of them can be computed. */\n 'aggregate-cycle': 'error',\n /** A number or currency format that prints a total at fewer places than its declared rounding keeps -- an aggregate's, or a chart's series' -- so the total is rounded twice and the second rounding ignores the declared mode. */\n 'format-rounds-again': 'error',\n /** A rounding declared on an aggregate that computes an integer, a date or an instant, or on a chart's series that totals an integer, which have no places to round: the runtime refuses it. */\n 'rounding-not-decimal': 'error',\n /** A total an e-invoice's XML holds -- a document total, or a declared VAT category's basis or amount -- that no text or table of the page prints: the page would show another invoice than the one it carries. */\n 'e-invoice-total-unprinted': 'error',\n /** A format that prints what an e-invoice's XML holds otherwise: a total or a line's net amount at fewer than two places, or in another currency than the e-invoice's; a line's net price in another currency; a line's name in another case. The page would show another invoice than the one it carries. */\n 'e-invoice-format-differs': 'error',\n /** A word of the report, or an expression that prints words, that a language it declares does not translate: a render in that language is refused, and never prints it in another (0063). */\n 'word-missing': 'error',\n /** A translated expression that would print another thing than the expression it translates: another type, other reads, or a value where the expression prints no words (0063). */\n 'translation-differs': 'error',\n /** A print style nothing uses. */\n 'unused-style': 'warning',\n /** An asset nothing draws. */\n 'unused-asset': 'warning',\n /** A parameter nothing prints or reads: the person rendering is asked for it for nothing. */\n 'unused-parameter': 'warning',\n /** A dataset field nothing prints, draws, orders by, totals or reads: the provider fetches it for nothing. */\n 'unused-field': 'warning',\n /** An aggregate nothing prints or reads: computed over every row for nothing. */\n 'unused-aggregate': 'warning',\n /** A report whose body holds nothing. */\n 'empty-body': 'warning',\n /** A text that prints nothing: no runs, or only empty literal ones. */\n 'empty-text': 'warning',\n /** A translation of a word, or of an expression, the report no longer prints: kept for nothing, and never printed (0063). */\n 'unused-translation': 'warning',\n /** A payment part that holds, written in the report, one of SIX's example accounts, or the creditor, the debtor or the QR reference a builder puts in from SIX's examples, which are no one's (0039). */\n 'example-payment-part': 'warning',\n /** A total row, under a table that prints only the rows its condition selects, that prints a total over every detail row: an aggregate over the report, or an expression that reads `totals` and not `table` (0062). Printed under those rows, it reads as theirs. */\n 'total-of-every-row': 'warning',\n} as const satisfies Readonly<Record<string, 'error' | 'warning'>>\n\nexport type DiagnosticCode = keyof typeof DIAGNOSTIC_SEVERITIES\n\nexport type DiagnosticSeverity = (typeof DIAGNOSTIC_SEVERITIES)[DiagnosticCode]\n\nexport const DIAGNOSTIC_CODES = Object.keys(DIAGNOSTIC_SEVERITIES) as readonly DiagnosticCode[]\n\nexport interface Diagnostic {\n readonly severity: DiagnosticSeverity\n readonly code: DiagnosticCode\n /** For a person: what is wrong, in the author's terms. */\n readonly message: string\n /** A JSON Pointer to what it is about: an expression's `cel`, a declaration, a list. */\n readonly path: string\n /** The innermost component it is about, when it is about one. */\n readonly componentId?: string\n /** For an expression in a table's column, the column's id: its value, its condition or a style rule of it. */\n readonly columnId?: string\n /** For an expression, the characters of its source it is about, half-open. */\n readonly position?: SourceSpan\n /** For an expression, what `@formancy/expressions` suggests writing instead, when it suggests something. */\n readonly hint?: string\n /** The language it is about, where it is one a translation declares: an error that names one refuses a render in that language alone (0063). */\n readonly language?: string\n}\n\n/** Where a diagnostic points, besides its path. */\nexport interface Where {\n readonly path: string\n readonly componentId?: string | undefined\n readonly columnId?: string | undefined\n readonly position?: SourceSpan | undefined\n readonly hint?: string | undefined\n readonly language?: string | undefined\n}\n\nexport function diagnostic(code: DiagnosticCode, message: string, where: Where): Diagnostic {\n return {\n severity: DIAGNOSTIC_SEVERITIES[code],\n code,\n message,\n path: where.path,\n ...(where.componentId === undefined ? {} : { componentId: where.componentId }),\n ...(where.columnId === undefined ? {} : { columnId: where.columnId }),\n ...(where.position === undefined ? {} : { position: where.position }),\n ...(where.hint === undefined ? {} : { hint: where.hint }),\n ...(where.language === undefined ? {} : { language: where.language }),\n }\n}\n","/**\n * What an expression in a report can read: the names the format binds and\n * the members each holds, each with the type it is checked and bound as.\n *\n * The names are the format's: `EXPRESSION_NAMES` lists, for each scope, the\n * names the runtime binds (0007) -- `params`, `header` and `totals`\n * everywhere, `row` in a table's cells, its row condition and what an\n * aggregate reads from each row, `table` in a table's total rows and its\n * group's header and footer (0062), `group` in a group's header and\n * footer. A report that is an e-invoice binds `invoice`, `vatBasis` and\n * `vatAmount` besides, wherever `totals` is but where they are computed\n * from (`e-invoice.ts`). Each name holds members -- a parameter, a field,\n * an aggregate, a group's key, a total of the e-invoice -- read as\n * `<name>.<id>`, and every member is a single value, never a map.\n */\nimport type { DeclaredType } from '@formancy/expressions'\nimport { GROUP_KEY, walkComponents } from '@formancy/report-spec'\nimport type { AggregateFunction, ChartSeries, DatasetContract, FieldType, ReportDefinition } from '@formancy/report-spec'\n\n/**\n * The type an expression reads each readable field and parameter type as.\n *\n * - Exact numbers keep their exactness: an integer is `int`, a decimal\n * `decimal`, never a double.\n * - A `date` and a `datetime` are read as their ISO strings. Neither has a\n * zone, and a CEL timestamp is an instant: making one from a date would\n * need a zone the report does not have, and `@formancy/expressions`\n * refuses to guess one. Their ISO forms compare in calendar order.\n * - An `instant` has a zone, so it is a `timestamp`.\n * - An `image` is not readable: its value is an asset id, which is drawn,\n * never printed or computed with (0007).\n */\nexport const EXPRESSION_TYPES: { readonly [T in Exclude<FieldType, 'image'>]: DeclaredType } = {\n string: 'string',\n integer: 'int',\n decimal: 'decimal',\n boolean: 'bool',\n date: 'string',\n datetime: 'string',\n instant: 'timestamp',\n}\n\n/**\n * A value an expression reads as `<name>.<member>`. `type` is the CEL type\n * it is bound as: `expressionValues` makes a value of it from what the data\n * holds. It is checked as that type too, unless it may be null: CEL has no\n * nullable scalars, so a member that may be null is checked as `dyn`, and\n * compared with null before it is used as anything else.\n */\nexport interface ExpressionMember {\n readonly type: DeclaredType\n readonly nullable: boolean\n}\n\n/** Every name the format binds, in some scope or in an e-invoice. A test holds this to the union of `EXPRESSION_NAMES` and `E_INVOICE_NAMES`. */\nexport const SCOPE_NAMES = ['params', 'header', 'row', 'totals', 'table', 'group', 'invoice', 'vatBasis', 'vatAmount'] as const\n\nexport type ScopeName = (typeof SCOPE_NAMES)[number]\n\n/**\n * What each name holds in one report, member by member, in declaration\n * order; `group` the aggregates alone. A group's key, `group.key`, is its\n * own table's, and two tables may group by fields of two types (0062), so\n * each table that groups has its key in `groupKeys`, by the table's id,\n * and a group's header and footer are compiled with their table's.\n */\nexport type Members = { readonly [N in ScopeName]: ReadonlyMap<string, ExpressionMember> } & {\n readonly groupKeys: ReadonlyMap<string, ExpressionMember>\n}\n\n/** The type a field of `type` is read as; undefined for an image, which is not read. */\nexport function readAs(type: FieldType | undefined): DeclaredType | undefined {\n return type === undefined || type === 'image' ? undefined : EXPRESSION_TYPES[type]\n}\n\nexport function fieldsOf(dataset: DatasetContract | undefined): ReadonlyMap<string, ExpressionMember> {\n const members = new Map<string, ExpressionMember>()\n for (const field of dataset?.fields ?? []) {\n const type = readAs(field.type)\n if (type !== undefined) members.set(field.id, { type, nullable: field.nullable })\n }\n return members\n}\n\nexport function parametersOf(report: ReportDefinition): ReadonlyMap<string, ExpressionMember> {\n return new Map(\n report.parameters.map((parameter) => [\n parameter.id,\n { type: EXPRESSION_TYPES[parameter.type], nullable: !parameter.required && parameter.default === undefined },\n ]),\n )\n}\n\n/**\n * `group.key` in each table that groups, by the table's id: the value its\n * group is keyed by, the field the table groups by, read as its type and\n * null where it may be, since the rows without a value are a group of\n * their own. A table that does not group, or groups by a field nothing can\n * read, has none.\n */\nexport function groupKeysOf(report: ReportDefinition): ReadonlyMap<string, ExpressionMember> {\n const keys = new Map<string, ExpressionMember>()\n for (const { component } of walkComponents(report)) {\n if (component.kind !== 'table' || component.group === undefined) continue\n const by = component.group.by.field\n const field = report.datasets.detail?.fields.find(({ id }) => id === by)\n const type = readAs(field?.type)\n if (field !== undefined && type !== undefined) keys.set(component.id, { type, nullable: field.nullable })\n }\n return keys\n}\n\n/** What `group` holds in a group's header and footer of the table `table`: the aggregates, and its key as `GROUP_KEY` where it has one. */\nexport function groupOf(members: Members, table: string): ReadonlyMap<string, ExpressionMember> {\n const key = members.groupKeys.get(table)\n return key === undefined ? members.group : new Map([...members.group, [GROUP_KEY, key]])\n}\n\n/** The image fields of a dataset: drawn, and never read as a value. */\nexport function imagesOf(dataset: DatasetContract | undefined): ReadonlySet<string> {\n return new Set((dataset?.fields ?? []).filter(({ type }) => type === 'image').map(({ id }) => id))\n}\n\n/**\n * The types each function totals (0007), for an aggregate over an\n * expression; one over a field the validator has already checked. A sum and\n * an average take integers and decimals; a minimum and a maximum those,\n * instants, and dates and date-times as the ISO strings they are read as; a\n * count counts what is not null, whatever it is. `dyn` -- a value that may\n * be null -- is taken by all of them: what it holds is known only at render.\n */\nexport const TOTALS: { readonly [F in AggregateFunction]: ReadonlySet<string> | 'any' } = {\n count: 'any',\n sum: new Set(['int', 'decimal', 'dyn']),\n avg: new Set(['int', 'decimal', 'dyn']),\n min: new Set(['int', 'decimal', 'timestamp', 'string', 'dyn']),\n max: new Set(['int', 'decimal', 'timestamp', 'string', 'dyn']),\n}\n\n/**\n * What each function computes from what it reads (0007): a count is an\n * integer and an average a decimal; a sum, minimum or maximum is the type it\n * read, `dyn` when that is not known. Over no rows, a count and a sum are 0\n * and the others null.\n */\nexport const COMPUTES: { readonly [F in AggregateFunction]: (read: DeclaredType | undefined) => ExpressionMember } = {\n count: () => ({ type: 'int', nullable: false }),\n sum: (read) => ({ type: read ?? 'dyn', nullable: false }),\n avg: () => ({ type: 'decimal', nullable: true }),\n min: (read) => ({ type: read ?? 'dyn', nullable: true }),\n max: (read) => ({ type: read ?? 'dyn', nullable: true }),\n}\n\n/** What an aggregate of `fn` over the detail field `field` names computes, typed by `COMPUTES`: the one place the compiler and a chart's series ask. */\nexport function fieldTotalType(report: ReportDefinition, fn: AggregateFunction, field: string | undefined): ExpressionMember {\n return COMPUTES[fn](readAs(report.datasets.detail?.fields.find(({ id }) => id === field)?.type))\n}\n\n/** What a chart's `series` computes: the compiler's type of an aggregate of its function over the detail field it names. */\nexport function seriesType(report: ReportDefinition, series: ChartSeries): ExpressionMember {\n return fieldTotalType(report, series.fn, series.of?.field)\n}\n","/**\n * What a report that is an e-invoice binds beside the format's names, where\n * those cannot be read, and what each of the e-invoice's expressions must\n * give (0027, beside 0009).\n *\n * `invoice`, `vatBasis` and `vatAmount` (report-spec's `E_INVOICE_NAMES`)\n * hold the totals the runtime computes once from the e-invoice's lines,\n * after the aggregates, for the page and the XML alike. Every member is a\n * decimal: a document total is never null; a category's basis and amount\n * are null when no line is in it; the paid amount is what the e-invoice's\n * expression gives, and no member where it declares none.\n *\n * They are read wherever `totals` is, but not where they are computed\n * from: an aggregate's expression, computed before them; one of the\n * e-invoice's own, which the XML writes beside them and the amount due is\n * computed from; and a column that prints a term of each line, which they\n * are the sums of. A read there is a circle no render could close, and is\n * refused as a name the place does not bind, as one in a report that is no\n * e-invoice is.\n */\nimport type { DeclaredType } from '@formancy/expressions'\nimport { INVOICE_TOTALS } from '@formancy/report-spec'\nimport type { EInvoice, EInvoiceName, FieldType, InvoiceTotal } from '@formancy/report-spec'\nimport type { ExpressionSite } from '../diagnostics/parts.js'\nimport type { SiteOutcome } from './compile-site.js'\nimport type { ExpressionMember } from './members.js'\nimport { readAs } from './members.js'\n\n/** What each of the e-invoice's names holds, member by member. */\nexport type InvoiceMembers = { readonly [N in EInvoiceName]: ReadonlyMap<string, ExpressionMember> }\n\n/** A document total: computed over every line, 0.00 over none. */\nconst TOTAL: ExpressionMember = { type: 'decimal', nullable: false }\n\n/** A category's basis or amount: null when no line is in it. */\nconst BREAKDOWN: ExpressionMember = { type: 'decimal', nullable: true }\n\n/**\n * What each name holds in a report whose e-invoice is `invoice`, its paid\n * amount read as `paid`; nothing in a report that is none. The totals in\n * report-spec's order, the categories in the order the e-invoice declares\n * them.\n */\nexport function invoiceMembers(invoice: EInvoice | undefined, paid: ExpressionMember | undefined): InvoiceMembers {\n if (invoice === undefined) return { invoice: new Map(), vatBasis: new Map(), vatAmount: new Map() }\n const totals = (Object.keys(INVOICE_TOTALS) as InvoiceTotal[]).flatMap((id): [string, ExpressionMember][] => {\n if (id !== 'paid') return [[id, TOTAL]]\n return paid === undefined ? [] : [[id, paid]]\n })\n const categories = (): Map<string, ExpressionMember> => new Map(invoice.vat.map(({ id }) => [id, BREAKDOWN]))\n return { invoice: new Map(totals), vatBasis: categories(), vatAmount: categories() }\n}\n\n/**\n * What `invoice.paid` is read as, from how the e-invoice's paid amount\n * compiled: a decimal, null where the expression may give null. One that\n * did not compile has no type anyone could check a read of: it is read as\n * a value that may be anything, so its fault is reported once, where it is.\n */\nexport function paidMember(outcome: SiteOutcome): ExpressionMember {\n if (!outcome.ok) return { type: 'dyn', nullable: true }\n return { type: 'decimal', nullable: outcome.compiled.program.resultType !== 'decimal' }\n}\n\n/**\n * Why the expression at `site` cannot read the e-invoice's names, said\n * after the name; undefined where it can. `invoiced` says whether the\n * report is an e-invoice.\n */\nexport function invoiceRefusal(site: ExpressionSite, invoiced: boolean): string | undefined {\n if (!invoiced) return 'has a value only in a report that is an e-invoice, and this report is none'\n // An aggregate's expression is the one site under /aggregates/, as compileReport finds it.\n if (site.path.startsWith('/aggregates/')) return \"holds what the e-invoice computes after every aggregate, and an aggregate's expression cannot read it\"\n if (site.term === undefined) return undefined\n const what = site.columnId === undefined ? site.term.what : `the column that prints ${site.term.what}`\n return `holds the totals the e-invoice computes from its lines, and ${what} is part of what they are computed from or written with: it cannot read them`\n}\n\n/** What a field of each type is, as a message says it. */\nconst SAID: { readonly [T in FieldType]: string } = {\n string: 'a text',\n integer: 'an integer',\n decimal: 'a decimal',\n boolean: 'a boolean',\n date: 'a date, read as its ISO string',\n datetime: 'a date and a time',\n instant: 'an instant',\n image: 'an image',\n}\n\n/** What to say of an expression of an e-invoice's term that gives what the term is not. */\nexport interface TermBreak {\n readonly message: string\n readonly hint?: string\n}\n\n/**\n * What breaks the term of the expression at `site`, which gives `type`; or\n * undefined, when it has no term of a type or gives one the term takes. A\n * term takes what an expression reads each type of field it may be as,\n * and a value that may be null, checked as `dyn`, which the render checks\n * again once it holds the value. A date is taken as the ISO string a date\n * field is read as, so whether a text is a date is the render's to say.\n */\nexport function termBreak(site: ExpressionSite, type: string): TermBreak | undefined {\n const term = site.term\n if (term?.types === undefined) return undefined\n // No term is an image, the one type of field nothing reads.\n const takes = new Set<string>(['dyn', ...term.types.map((field) => readAs(field) as DeclaredType)])\n if (takes.has(type)) return undefined\n const what = `${term.what} is ${term.types.map((field) => SAID[field]).join(' or ')}, and ${site.columnId === undefined ? 'this expression' : \"this column's value\"} gives ${type}`\n const decimal = term.types.length === 1 && term.types[0] === 'decimal' && (type === 'int' || type === 'string')\n return decimal ? { message: what, hint: 'dec() makes a decimal of an integer, or of a string of digits' } : { message: what }\n}\n","/**\n * Calls a report expression may not make: the clock and a random draw.\n *\n * A report rendered twice from the same data and parameters prints the\n * same thing (plan 15), so a reviewer's preview is the customer's PDF and a\n * published version renders as it was approved. `@formancy/expressions`\n * allows `now()` and `today()` in every kind of expression and `random()`\n * in a computed one, because a form captures them with its submission; a\n * report has nothing to capture them in. A date the report needs is a\n * parameter.\n *\n * Its parsed expression is opaque, and no kind's policy forbids the clock,\n * so the calls are found by asking its compiler: each place the name is\n * written as a whole word is renamed, keeping its length, to a function\n * that does not exist. Where the rename makes the compiler refuse an\n * unknown function at exactly that place, the expression called the\n * function there. Everything else -- a string, a member, a comprehension's\n * local -- compiles as before, or fails elsewhere. A generic way to ask\n * which functions an expression calls belongs upstream, and replaces this\n * when it is released.\n */\nimport { compile } from '@formancy/expressions'\nimport type { ExpressionKind, SourceSpan, VariableDeclarations } from '@formancy/expressions'\n\n/** The functions whose value is not a function of the report's data. */\nexport const UNREPRODUCIBLE_FUNCTIONS = ['now', 'today', 'random'] as const\n\nexport type UnreproducibleFunction = (typeof UNREPRODUCIBLE_FUNCTIONS)[number]\n\n/** The code `@formancy/expressions` gives a call to a function that has no overload, an unknown one included. */\nexport const UNKNOWN_FUNCTION = 'no_matching_overload'\n\nconst WORD = /[A-Za-z0-9_]/\n\n/** Whether `name` at `at` stands alone, not as part of a longer name. */\nfunction whole(source: string, at: number, name: string): boolean {\n return !WORD.test(source.charAt(at - 1)) && !WORD.test(source.charAt(at + name.length))\n}\n\n/**\n * Each call in `source` -- an expression that compiles, of `kind`, against\n * `variables` -- to a function that would make a render unrepeatable, in\n * the order they are written, with the span of the call.\n */\nexport function unreproducibleCalls(\n source: string,\n kind: ExpressionKind,\n variables: VariableDeclarations,\n): { readonly name: UnreproducibleFunction; readonly span: SourceSpan }[] {\n const found: { readonly name: UnreproducibleFunction; readonly span: SourceSpan }[] = []\n for (const name of UNREPRODUCIBLE_FUNCTIONS) {\n for (let at = source.indexOf(name); at !== -1; at = source.indexOf(name, at + 1)) {\n if (!whole(source, at, name)) continue\n const probe = compile(`${source.slice(0, at)}_${source.slice(at + 1)}`, { kind, variables })\n if (!probe.ok && probe.error.code === UNKNOWN_FUNCTION && probe.error.position?.start === at) found.push({ name, span: probe.error.position })\n }\n }\n return found.sort((a, b) => a.span.start - b.span.start)\n}\n","/**\n * Arithmetic a report expression may not do, and a call whose time nothing\n * bounds.\n *\n * - **A double.** A report's numbers are exact: integers, and decimals from\n * strings (formancy.ai-data 0008). A double is not, and `int()` of one\n * hands back an integer the runtime cannot tell from an exact one:\n * `int(double(\"4.35\") * 100.0)` is 434. Every double comes in through a\n * literal (`100.0`, `1e3`) or `double()`, since the data binds none.\n * - **Division with `/`.** On integers it drops the remainder -- 3 / 2 is\n * 1, -3 / 2 is -1 -- a rounding nobody declared. Decimals have no `/`,\n * and doubles are refused, so every `/` that compiles divides integers.\n * `divide(dec(a), dec(b), places)` rounds where it says, half away from\n * zero. A remainder, `%`, is exact, and allowed.\n * - **`matches()`.** It runs its pattern on JavaScript's backtracking\n * engine, and one call is a few steps of upstream's budget however long\n * it runs: no budget bounds it, and a render cannot be interrupted while\n * it runs.\n *\n * The parsed expression is opaque, so each is found by asking the parser\n * and the compiler, as `reproducible.ts` finds the clock: a candidate is\n * spelled differently where it stands, and the probe sees whether that\n * changes the outcome there. A character no CEL token has makes a syntax\n * error exactly where it stands, unless it stands in a string or a comment;\n * a renamed function makes the call fail. So text that only looks like a\n * double, a division or a call is never one. A generic way to ask an\n * expression's types and calls belongs upstream, and replaces this when it\n * is released.\n */\nimport { compile, parse } from '@formancy/expressions'\nimport type { ExpressionKind, SourceSpan, VariableDeclarations } from '@formancy/expressions'\nimport { UNKNOWN_FUNCTION } from './reproducible.js'\n\nexport type InexactKind = 'double-literal' | 'double-call' | 'integer-division'\n\nexport interface Found<K> {\n readonly kind: K\n readonly span: SourceSpan\n}\n\n/** A CEL float literal: digits, a point and digits, or digits and an exponent; never part of a name or of a hex literal. */\nconst FLOAT = /(?<![A-Za-z0-9_.])(?:\\d+\\.\\d+(?:[eE][+-]?\\d+)?|\\d+[eE][+-]?\\d+)(?![A-Za-z0-9_])/g\n\n/** A character no CEL token has. */\nconst FOREIGN = '@'\n\n/** Whether the `length` characters at `at` are part of the expression, not of a string or a comment: spelled as a foreign character, they make a syntax error there. */\nfunction inCode(source: string, at: number, length: number): boolean {\n const probe = parse(`${source.slice(0, at)}${FOREIGN}${' '.repeat(length - 1)}${source.slice(at + length)}`)\n return !probe.ok && probe.error.kind === 'syntax' && probe.error.position?.start === at\n}\n\nconst WORD = /[A-Za-z0-9_]/\n\n/**\n * Each call in `source` -- which compiles, of `kind`, against `variables` --\n * to the function `name`, by function or method, with the span the compiler\n * gives the call once the function is renamed to one that does not exist.\n */\nfunction callsTo(name: string, source: string, kind: ExpressionKind, variables: VariableDeclarations): SourceSpan[] {\n const spans: SourceSpan[] = []\n for (let at = source.indexOf(name); at !== -1; at = source.indexOf(name, at + 1)) {\n if (WORD.test(source.charAt(at - 1)) || WORD.test(source.charAt(at + name.length))) continue\n const probe = compile(`${source.slice(0, at)}_${source.slice(at + 1)}`, { kind, variables })\n const span = probe.ok ? undefined : probe.error.position\n if (!probe.ok && probe.error.code === UNKNOWN_FUNCTION && span !== undefined && span.start <= at && at < span.end) spans.push(span)\n }\n return spans\n}\n\n/**\n * Each double literal, call to `double()` and division in `source`, an\n * expression that compiles, of `kind`, against `variables`, in the order\n * they are written.\n */\nexport function inexactOperations(source: string, kind: ExpressionKind, variables: VariableDeclarations): Found<InexactKind>[] {\n const found: Found<InexactKind>[] = callsTo('double', source, kind, variables).map((span) => ({ kind: 'double-call', span }))\n for (const literal of source.matchAll(FLOAT)) {\n if (inCode(source, literal.index, literal[0].length))\n found.push({ kind: 'double-literal', span: { start: literal.index, end: literal.index + literal[0].length } })\n }\n for (let at = source.indexOf('/'); at !== -1; at = source.indexOf('/', at + 1)) {\n // Two slashes start a comment, or stand in a string; never a division.\n if (source.charAt(at - 1) === '/' || source.charAt(at + 1) === '/') continue\n if (inCode(source, at, 1)) found.push({ kind: 'integer-division', span: { start: at, end: at + 1 } })\n }\n return found.sort((a, b) => a.span.start - b.span.start)\n}\n\n/** The functions whose time no step budget bounds. */\nexport const UNBOUNDED_FUNCTIONS = ['matches'] as const\n\n/** Each call in `source` to a function whose time no budget bounds, in the order written. */\nexport function unboundedCalls(\n source: string,\n kind: ExpressionKind,\n variables: VariableDeclarations,\n): { readonly name: (typeof UNBOUNDED_FUNCTIONS)[number]; readonly span: SourceSpan }[] {\n return UNBOUNDED_FUNCTIONS.flatMap((name) => callsTo(name, source, kind, variables).map((span) => ({ name, span }))).sort(\n (a, b) => a.span.start - b.span.start,\n )\n}\n","/**\n * Where in its source an expression reads a path, for the editor to\n * underline.\n *\n * `@formancy/expressions` gives spans only on its errors, and a read of a\n * member nothing declares is caught here, before it compiles. It does\n * splice: its `rewritePath` replaces exactly the characters of each read,\n * verified by parsing the result again. So a read is where such a rewrite\n * put its replacement -- the real parser's answer, not a second one.\n */\nimport { rewritePath } from '@formancy/expressions'\nimport type { SourceSpan } from '@formancy/expressions'\n\nconst LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n/** CEL's reserved words of two letters, which no identifier may be. */\nconst RESERVED = new Set(['as', 'if', 'in'])\n\n/**\n * A name `source` does not contain anywhere, to mark each read with: one\n * letter, or two different ones. Absent from the source, no local of a\n * comprehension can capture it, and no text of the source can be taken\n * for it; two different letters cannot overlap themselves, so splitting on\n * the mark finds each one. A source of at most 1,024 characters has fewer\n * pairs than there are, so there is always one.\n */\nfunction markFor(source: string): string {\n for (const letter of LETTERS) if (!source.includes(letter)) return letter\n for (const first of LETTERS) {\n for (const second of LETTERS) {\n const mark = `${first}${second}`\n if (first !== second && !RESERVED.has(mark) && !source.includes(mark)) return mark\n }\n }\n throw new RangeError('no two letters are absent from this expression; it is longer than any expression a report holds')\n}\n\n/**\n * The characters of `source` that read `path`, each read on its own,\n * half-open, in order. None when the source does not parse or does not\n * read the path.\n *\n * Each read is at least as long as the path written plainly -- an index or\n * spaces only add to it -- so when the reads together are exactly that\n * long, every read is written plainly and each one's place is known. When\n * one is not, the reads cannot be told apart by length, and one span from\n * the first read to the last covers them all.\n */\nexport function readSpans(source: string, path: string): SourceSpan[] {\n const mark = markFor(source)\n const rewritten = rewritePath(source, path, mark)\n if (!rewritten.ok || !rewritten.changed) return []\n const pieces = rewritten.source.split(mark)\n const reads = pieces.length - 1\n const between = pieces.reduce((length, piece) => length + piece.length, 0)\n if (source.length - between !== reads * path.length) {\n return [{ start: (pieces[0] as string).length, end: source.length - (pieces.at(-1) as string).length }]\n }\n const spans: SourceSpan[] = []\n let at = 0\n for (const piece of pieces.slice(0, -1)) {\n at += piece.length\n spans.push({ start: at, end: at + path.length })\n at += path.length\n }\n return spans\n}\n","/**\n * One expression compiled where it stands, with every member it reads\n * checked as the type it is.\n *\n * `@formancy/expressions` 0.12.0, as 0.5.0 to 0.7.0 and 0.11.0, declares a variable only by its\n * whole name: a declaration of `row.amount` is a variable with a dot in its\n * name, which an expression reading `row.amount` never finds. So each read of a member\n * is spliced, by upstream's own `rewritePath`, which verifies every splice\n * by parsing the result again, into a read of one variable -- `row.amount`\n * becomes `row_amount` -- declared with the member's type. The real checker\n * then types every member read: a decimal meets a decimal, an integer added\n * to a string is refused. The flat name is exactly as long as the read\n * written plainly, so a position the compiler gives is a position in what\n * the author wrote.\n *\n * What a scope does not bind, a member nothing declares, a member of a\n * single value and an image field read as a value are found first, from\n * the paths the parser says the expression reads; so is an e-invoice's\n * total read where it cannot be (`e-invoice.ts`). The clock and a random\n * draw, which the compiler allows, are refused last (plan 15), and then\n * what its place needs it to give: a payment code's amount, an\n * e-invoice's term.\n */\nimport { compile, parse, referencedPaths, rewritePath } from '@formancy/expressions'\nimport type { DeclaredType, ExpressionError, ExpressionErrorKind, Program, SourceSpan, VariableDeclarations } from '@formancy/expressions'\nimport { E_INVOICE_NAMES, EXPRESSION_NAMES, VALUE_SCOPES } from '@formancy/report-spec'\nimport type { ValueScope } from '@formancy/report-spec'\nimport { diagnostic } from '../diagnostics/codes.js'\nimport type { Diagnostic, DiagnosticCode, Where } from '../diagnostics/codes.js'\nimport type { ExpressionSite } from '../diagnostics/parts.js'\nimport { quote } from '../outcome.js'\nimport { invoiceRefusal, termBreak } from './e-invoice.js'\nimport { inexactOperations, unboundedCalls } from './exactness.js'\nimport type { InexactKind } from './exactness.js'\nimport { groupOf } from './members.js'\nimport type { Members, ScopeName } from './members.js'\nimport { unreproducibleCalls } from './reproducible.js'\nimport { readSpans } from './spans.js'\n\n/** A member an expression reads, and how the runtime binds it. */\nexport interface ExpressionRead {\n /** The name and the member as the expression writes them: `row` and `amount` for `row.amount`. */\n readonly name: ScopeName\n readonly member: string\n /** The variable the program reads it as, and `expressionValues` binds it under: `row_amount`. */\n readonly variable: string\n /** The type it is bound as, and checked as unless it may be null. */\n readonly type: DeclaredType\n readonly nullable: boolean\n}\n\n/** An expression that compiled clean: what the runtime evaluates, and what it reads. */\nexport interface CompiledExpression {\n readonly site: ExpressionSite\n /** Compiled from the expression with each member read spliced into its variable; evaluate it with `expressionValues`. */\n readonly program: Program\n readonly reads: readonly ExpressionRead[]\n}\n\nexport type SiteOutcome = { readonly ok: true; readonly compiled: CompiledExpression } | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] }\n\n/** The image fields each name holds, which nothing reads. */\nexport type Images = { readonly [N in ScopeName]?: ReadonlySet<string> }\n\n/**\n * The code for each kind of error the compiler gives. It gives the first\n * four when compiling; `runtime` and `budget` are evaluation's, mapped to\n * the nearest so the table is total.\n */\nconst BY_KIND: { readonly [K in ExpressionErrorKind]: DiagnosticCode } = {\n syntax: 'expression-syntax',\n limit: 'expression-limit',\n type: 'expression-type',\n policy: 'expression-policy',\n runtime: 'expression-type',\n budget: 'expression-limit',\n}\n\n/** Where each scope's own names have a value, for a message. */\nconst WHERE: { readonly [S in ValueScope]: string } = {\n report: 'every part of the report',\n table: \"a table's total rows\",\n group: \"a group's header and footer\",\n row: \"a table's cells and what an aggregate reads from each row\",\n}\n\n/** What each name's members are, for a message about one it lacks. */\nconst MEMBERS_ARE: { readonly [N in ScopeName]: string } = {\n params: 'parameter',\n header: 'field of the header dataset',\n row: 'field of the detail dataset',\n totals: 'aggregate',\n table: 'aggregate',\n group: 'aggregate',\n invoice: 'total of the e-invoice',\n vatBasis: 'VAT category of the e-invoice',\n vatAmount: 'VAT category of the e-invoice',\n}\n\n/** A read path's parts: the name it starts with, the member a dot names after it, and anything else after that. */\nexport interface PathParts {\n readonly name: string\n /** The member, when the name is followed by `.` and an identifier; undefined for a whole read, or one by a key no member could have. */\n readonly member?: string\n /** What follows the name, or the member when there is one: '' when nothing does. */\n readonly rest: string\n}\n\nconst NAME = /^[A-Za-z_][A-Za-z0-9_]*/\n\n/**\n * `path` -- as `referencedPaths` gives one: `row.amount`, `params`, or\n * `row[\"a.b\"]` for a key that is no identifier -- taken apart. A member's\n * id is a field key, an identifier (0007), so a read by any other key reads\n * no member.\n */\nexport function pathParts(path: string): PathParts {\n // Every path upstream gives starts with the name it reads.\n const name = (NAME.exec(path) as RegExpExecArray)[0]\n const after = path.slice(name.length)\n const member = after.startsWith('.') ? NAME.exec(after.slice(1))?.[0] : undefined\n return member === undefined ? { name, rest: after } : { name, member, rest: after.slice(1 + member.length) }\n}\n\nfunction failed(diagnostics: readonly Diagnostic[]): SiteOutcome {\n return { ok: false, diagnostics }\n}\n\n/** Where a diagnostic about `site` points. */\nfunction at(site: ExpressionSite, position?: SourceSpan, hint?: string): Where {\n return { path: site.path, componentId: site.componentId, columnId: site.columnId, position, hint }\n}\n\n/** One diagnostic per place `source` reads `path`, or one with no place when the reads cannot be found. */\nfunction eachRead(site: ExpressionSite, path: string, code: DiagnosticCode, message: string): Diagnostic[] {\n const spans = readSpans(site.cel, path)\n return spans.length === 0 ? [diagnostic(code, message, at(site))] : spans.map((span) => diagnostic(code, message, at(site, span)))\n}\n\n/** What the expression at a site reads: the names its scope binds, and the e-invoice's where it may read them, or why it cannot. */\ninterface Names {\n readonly names: readonly string[]\n /** Why the e-invoice's names are not read here, said after the name; undefined where they are. */\n readonly refusal: string | undefined\n}\n\nconst INVOICE_NAMES: readonly string[] = E_INVOICE_NAMES\n\n/** The names `site` reads, in a report that is an e-invoice when `invoiced` says so. */\nfunction namesAt(site: ExpressionSite, invoiced: boolean): Names {\n const refusal = invoiceRefusal(site, invoiced)\n return { names: refusal === undefined ? [...EXPRESSION_NAMES[site.scope], ...INVOICE_NAMES] : EXPRESSION_NAMES[site.scope], refusal }\n}\n\n/** The diagnostics for a read of `path` that the site's names and their members do not allow; none for one they do. */\nfunction readProblems(site: ExpressionSite, path: string, members: Members, images: Images, { names, refusal }: Names): Diagnostic[] {\n const { name, member, rest } = pathParts(path)\n if (refusal !== undefined && INVOICE_NAMES.includes(name)) return eachRead(site, name, 'expression-unknown-name', `${name} ${refusal}`)\n if (!names.includes(name)) {\n const scopes = VALUE_SCOPES.filter((scope) => EXPRESSION_NAMES[scope].includes(name))\n if (scopes.length > 0)\n return eachRead(site, name, 'expression-out-of-scope', `${name} has a value only in ${scopes.map((scope) => WHERE[scope]).join(' and ')}`)\n return eachRead(site, name, 'expression-unknown-name', `${quote(name)} is not a name an expression reads; here it reads ${names.join(', ')}`)\n }\n // A whole read -- size(params) -- is found once every member read is\n // spliced, when what still reads the name reads it whole.\n if (rest === '' && member === undefined) return []\n const scoped = name as ScopeName\n if (member === undefined)\n return eachRead(site, path, 'expression-unknown-name', `${name} has no member ${quote(rest)}: a ${MEMBERS_ARE[scoped]} is read by its id, as ${name}.<id>`)\n const held = members[scoped].get(member)\n if (held === undefined && images[scoped]?.has(member) === true) {\n return eachRead(\n site,\n path,\n 'expression-unreadable-field',\n `${name}.${member} is an image field: an image component draws it, and nothing reads it as a value`,\n )\n }\n if (held === undefined)\n return eachRead(site, path, 'expression-unknown-name', `${name} has no member ${quote(member)}: no ${MEMBERS_ARE[scoped]} of the report has that id`)\n if (rest !== '')\n return eachRead(site, path, 'expression-unknown-name', `${name}.${member} is a single value, and has no member ${quote(rest.replace(/^\\./, ''))}`)\n return []\n}\n\n/** Each member the paths read, once, in the order first read, with how it is bound. */\nfunction readsOf(paths: readonly string[], members: Members): ExpressionRead[] {\n const reads = new Map<string, ExpressionRead>()\n for (const path of paths) {\n const { name, member } = pathParts(path)\n const held = member === undefined ? undefined : members[name as ScopeName].get(member)\n if (member === undefined || held === undefined || reads.has(`${name}.${member}`)) continue\n reads.set(`${name}.${member}`, { name: name as ScopeName, member, variable: `${name}_${member}`, type: held.type, nullable: held.nullable })\n }\n return [...reads.values()]\n}\n\n/** The source with each read spliced into its variable, or the diagnostic for a splice upstream refused. */\nfunction flattened(site: ExpressionSite, reads: readonly ExpressionRead[]): { readonly source: string } | Diagnostic {\n let source = site.cel\n for (const read of reads) {\n const rewritten = rewritePath(source, `${read.name}.${read.member}`, read.variable)\n if (!rewritten.ok) {\n return diagnostic(\n BY_KIND[rewritten.error.kind],\n `${read.variable} is the name ${read.name}.${read.member} is checked under, and this expression gives that name to a variable of its own; give the variable another`,\n at(site),\n )\n }\n source = rewritten.source\n }\n return { source }\n}\n\n/** `text` with each variable written back as the read it stands for, so a message names what the author wrote. */\nfunction authored(text: string | undefined, reads: readonly ExpressionRead[]): string | undefined {\n return reads.reduce<string | undefined>(\n (said, read) => said?.replace(new RegExp(`(?<![A-Za-z0-9_])${read.variable}(?![A-Za-z0-9_])`, 'g'), `${read.name}.${read.member}`),\n text,\n )\n}\n\n/** The diagnostic for an error the compiler gave; its position kept only when the source it checked is the author's, character for character. */\nfunction refused(site: ExpressionSite, error: ExpressionError, source: string, reads: readonly ExpressionRead[]): Diagnostic {\n const position = source.length === site.cel.length ? error.position : undefined\n return diagnostic(BY_KIND[error.kind], authored(error.message, reads) as string, at(site, position, authored(error.hint, reads)))\n}\n\n/**\n * A diagnostic at each place `source` -- with every member read spliced --\n * still reads a name of the scope: each such read reads the name whole,\n * since every read of a member by its id is spliced away. Positions only\n * when `source` is the author's, character for character.\n */\nfunction wholeReads(site: ExpressionSite, paths: readonly string[], source: string, names: readonly string[]): Diagnostic[] {\n const exact = source.length === site.cel.length\n return paths\n .filter((path) => names.includes(path))\n .flatMap((name) =>\n readSpans(source, name).map((span) =>\n diagnostic(\n 'expression-dynamic-read',\n `${name} is read whole; an expression reads each ${MEMBERS_ARE[name as ScopeName]} by its id, as ${name}.<id>`,\n at(site, exact ? span : undefined),\n ),\n ),\n )\n}\n\n/**\n * `site` compiled against what its scope binds in this report -- a report\n * that is an e-invoice when `invoiced` says so, and in a group's header\n * and footer the key of the table the site stands in (0062) -- or every\n * reason it cannot be: a read its scope does not allow, each where it is;\n * the compiler's first error; each call to the clock or a random draw; or\n * a value its place does not take.\n */\nexport function compileSite(site: ExpressionSite, held: Members, images: Images, invoiced: boolean): SiteOutcome {\n // A group's header and footer stand in their table, which the walk names as their component.\n const members = site.scope === 'group' ? { ...held, group: groupOf(held, site.componentId as string) } : held\n const parsed = parse(site.cel)\n if (!parsed.ok) return failed([refused(site, parsed.error, site.cel, [])])\n const paths = referencedPaths(parsed.ast)\n const names = namesAt(site, invoiced)\n const problems = paths.flatMap((path) => readProblems(site, path, members, images, names))\n if (problems.length > 0) return failed(problems)\n const reads = readsOf(paths, members)\n const flat = flattened(site, reads)\n if (!('source' in flat)) return failed([flat])\n const whole = wholeReads(site, paths, flat.source, names.names)\n if (whole.length > 0) return failed(whole)\n const variables: VariableDeclarations = Object.fromEntries(reads.map((read) => [read.variable, read.nullable ? 'dyn' : read.type]))\n const compiled = compile(flat.source, { kind: site.kind, variables })\n if (!compiled.ok) return failed([refused(site, compiled.error, flat.source, reads)])\n const exact = flat.source.length === site.cel.length\n const calls = unreproducibleCalls(flat.source, site.kind, variables)\n if (calls.length > 0) {\n const message = (name: string): string =>\n `${name}() differs from one render to the next, and a report prints the same from the same data; a date the report needs is a parameter`\n return failed(calls.map(({ name, span }) => diagnostic('expression-not-reproducible', message(name), at(site, exact ? span : undefined))))\n }\n const inexact = [\n ...inexactOperations(flat.source, site.kind, variables).map(({ kind, span }) =>\n diagnostic('expression-inexact', INEXACT[kind].message, at(site, exact ? span : undefined, INEXACT[kind].hint)),\n ),\n ...unboundedCalls(flat.source, site.kind, variables).map(({ name, span }) =>\n diagnostic('expression-unbounded', UNBOUNDED(name), at(site, exact ? span : undefined)),\n ),\n ].sort((a, b) => (a.position?.start ?? 0) - (b.position?.start ?? 0))\n if (inexact.length > 0) return failed(inexact)\n const type = compiled.program.resultType\n if (site.amount !== undefined && !AMOUNTS.has(type)) {\n const hint = type === 'int' || type === 'string' ? 'dec() makes a decimal of an integer, or of a string of digits' : undefined\n return failed([\n diagnostic(\n 'expression-type',\n `${site.amount}'s amount is a decimal, or null to leave it for the payer, and this expression gives ${type}`,\n at(site, undefined, hint),\n ),\n ])\n }\n const broken = termBreak(site, type)\n if (broken !== undefined) return failed([diagnostic('expression-type', broken.message, at(site, undefined, broken.hint))])\n return { ok: true, compiled: { site, program: compiled.program, reads } }\n}\n\n/**\n * What a payment code's amount -- a QR-bill's, an EPC QR code's -- may\n * give: one rule for both. A decimal, null, or a value that may be\n * either -- a decimal that may be null is checked as `dyn` -- which the\n * render, seeing the value, checks again.\n */\nconst AMOUNTS: ReadonlySet<string> = new Set(['decimal', 'null', 'dyn'])\n\n/** What to say of each inexact operation, and what to write instead. */\nconst INEXACT: { readonly [K in InexactKind]: { readonly message: string; readonly hint: string } } = {\n 'double-literal': {\n message: 'a number written with a point or an exponent is a double, which is not exact: 0.1 + 0.2 is not 0.3, and int() of one drops what it lost',\n hint: 'write it as a decimal, dec(\"100.0\"), to keep it exact',\n },\n 'double-call': {\n message: 'double() makes a double, which is not exact: double(\"4.35\") * 100.0 is 434.99999999999994, and int() of it is 434',\n hint: 'compute with decimals instead: dec(\"4.35\") * dec(\"100\")',\n },\n 'integer-division': {\n message: '/ divides integers and drops the remainder, a rounding the report never declares: 3 / 2 is 1, and -3 / 2 is -1',\n hint: 'divide(dec(a), dec(b), places) keeps it exact, and rounds half away from zero where it says',\n },\n}\n\nconst UNBOUNDED = (name: string): string =>\n `${name}() runs its pattern on a backtracking engine that a step budget cannot stop: one pattern can take minutes on a short text, and a render cannot be interrupted while it runs`\n","/**\n * What expressions read, by name, asked of the parser as the compiler asks\n * it (`compile-site.ts`): the paths `referencedPaths` gives, taken apart by\n * `pathParts`. The diagnostics ask it to know what nothing reads\n * (`unused.ts`), and the command that removes a field with its readers to\n * know what does (`readers.ts`), so the two cannot disagree on what an\n * expression reads. An expression that does not parse reads nothing it\n * can be credited with; its own diagnostic says why.\n */\nimport { parse, referencedPaths } from '@formancy/expressions'\nimport type { DatasetRole } from '@formancy/report-spec'\nimport { pathParts } from './compile-site.js'\n\n/** The name an expression reads each dataset's fields under: `header.<id>`, `row.<id>`. */\nexport const READ_AS: { readonly [R in DatasetRole]: 'header' | 'row' } = { header: 'header', detail: 'row' }\n\n/**\n * The names an expression reads an aggregate under: over every detail row,\n * over the rows its table prints (0062), and over its group's. One list, so\n * that what counts as using an aggregate and what goes with one removed\n * cannot disagree.\n */\nexport const AGGREGATE_NAMES: readonly string[] = ['totals', 'table', 'group']\n\n/** What expressions read, by name: the members read, or 'all' where one reads the whole map. */\nexport type Reads = ReadonlyMap<string, ReadonlySet<string> | 'all'>\n\n/** What the expressions `cels` read between them. */\nexport function expressionReads(cels: Iterable<string>): Reads {\n const reads = new Map<string, Set<string> | 'all'>()\n for (const cel of cels) {\n const parsed = parse(cel)\n if (!parsed.ok) continue\n for (const path of referencedPaths(parsed.ast)) {\n const { name, member, rest } = pathParts(path)\n const known = reads.get(name)\n // A whole read may read any member; a read by a key that is no\n // identifier reads none, since every member's id is one.\n if (member === undefined && rest === '') reads.set(name, 'all')\n else if (member === undefined) continue\n else if (known === undefined) reads.set(name, new Set([member]))\n else if (known !== 'all') known.add(member)\n }\n }\n return reads\n}\n\n/** Whether `reads` read `id` under any of `names`: by its id, or by reading the name whole. */\nexport function readsMember(reads: Reads, names: readonly string[], id: string): boolean {\n return names.some((name) => {\n const members = reads.get(name)\n return members === 'all' || members?.has(id) === true\n })\n}\n","/**\n * Commands on a table over the detail dataset: its columns, its one\n * grouping level, its sort keys, and the rows under its groups and under\n * the table -- subtotals, tax lines, totals -- cell by cell. Its condition\n * on its rows changes through `updateComponent`, as its empty text does\n * (0062).\n *\n * Each names the table by its component id. A column is named by its id,\n * which footer cells refer to, so a column's id never changes in place; a\n * footer row has no id and is named by its position.\n */\nimport { componentAt } from '@formancy/report-spec'\nimport type { ReportDefinition, SortKey, TableColumn, TableComponent, TableFooterCell, TableFooterRow, TableGroup } from '@formancy/report-spec'\nimport { checkIndex, insertedAt, movedTo, patched, removedAt, replacedAt } from '../lists.js'\nimport type { Patch } from '../lists.js'\nimport { isRefusal, quote, refuse } from '../outcome.js'\nimport type { CommandOutcome, Place, Refusal } from '../outcome.js'\nimport { updateAt } from '../tree.js'\n\n/** Where a table is: its JSON Pointer and its id. */\ninterface TablePlace {\n readonly path: string\n readonly componentId: string\n}\n\n/** Which footer rows: those under the whole table, or those under each group. */\nexport type FooterRows = 'totals' | 'groupFooter'\n\n/** The table `tableId` changed by `change`, which is told where the table is. */\nfunction withTable(report: ReportDefinition, tableId: string, change: (table: TableComponent, place: TablePlace) => TableComponent | Refusal): CommandOutcome {\n const found = componentAt(report, tableId)\n if (found === undefined) return refuse('not-found', `no component is ${quote(tableId)}`, { componentId: tableId })\n const place = { path: found.path, componentId: tableId }\n if (found.component.kind !== 'table') return refuse('kind-mismatch', `${quote(tableId)} is a ${found.component.kind}, not a table`, place)\n const next = change(found.component, place)\n return isRefusal(next) ? next : { ok: true, report: updateAt(report, found.path, () => next) }\n}\n\n/** The position of the column `columnId`, or a refusal. */\nfunction columnIndex(table: TableComponent, columnId: string, place: TablePlace): number | Refusal {\n const index = table.columns.findIndex((column) => column.id === columnId)\n return index === -1 ? refuse('not-found', `the table has no column ${quote(columnId)}`, { ...place, path: `${place.path}/columns` }) : index\n}\n\nexport function insertColumn(report: ReportDefinition, tableId: string, index: number, column: TableColumn): CommandOutcome {\n return withTable(report, tableId, (table, place) => {\n const outside = checkIndex(index, table.columns.length, `the table's ${table.columns.length} columns`, { ...place, path: `${place.path}/columns` })\n return outside ?? { ...table, columns: insertedAt(table.columns, index, column) }\n })\n}\n\n/** Removes a column, and its cell from every footer row: a cell belongs to its column. */\nexport function removeColumn(report: ReportDefinition, tableId: string, columnId: string): CommandOutcome {\n return withTable(report, tableId, (table, place) => {\n const index = columnIndex(table, columnId, place)\n if (isRefusal(index)) return index\n const uncelled = (rows: readonly TableFooterRow[]): TableFooterRow[] =>\n rows.map((row) => (row.cells.some((cell) => cell.column === columnId) ? { ...row, cells: row.cells.filter((cell) => cell.column !== columnId) } : row))\n return {\n ...table,\n columns: removedAt(table.columns, index),\n ...(table.group === undefined ? {} : { group: { ...table.group, footer: uncelled(table.group.footer) } }),\n ...(table.totals === undefined ? {} : { totals: uncelled(table.totals) }),\n }\n })\n}\n\n/** Moves a column so that it ends at `index`, counted without it. */\nexport function moveColumn(report: ReportDefinition, tableId: string, columnId: string, index: number): CommandOutcome {\n return withTable(report, tableId, (table, place) => {\n const from = columnIndex(table, columnId, place)\n if (isRefusal(from)) return from\n const outside = checkIndex(index, table.columns.length - 1, `the table's ${table.columns.length} columns`, { ...place, path: `${place.path}/columns` })\n return outside ?? { ...table, columns: movedTo(table.columns, from, index) }\n })\n}\n\n/** Changes a column's properties; its id, which footer cells name, never changes in place. */\nexport function updateColumn(report: ReportDefinition, tableId: string, columnId: string, patch: Patch<Omit<TableColumn, 'id'>>): CommandOutcome {\n return withTable(report, tableId, (table, place) => {\n const index = columnIndex(table, columnId, place)\n if (isRefusal(index)) return index\n if (Object.hasOwn(patch, 'id')) {\n return refuse('immutable-property', \"a column's id is what its footer cells name, and never changes in place\", {\n ...place,\n path: `${place.path}/columns/${index}/id`,\n })\n }\n return { ...table, columns: replacedAt(table.columns, index, patched<TableColumn>(table.columns[index] as TableColumn, patch)) }\n })\n}\n\n/** Sets the table's one grouping level, or removes it with `null` -- as a patch removes, so a removal survives JSON. */\nexport function setGroup(report: ReportDefinition, tableId: string, group: TableGroup | null): CommandOutcome {\n return withTable(report, tableId, (table) => {\n const { group: _old, ...rest } = table\n return group === null ? rest : { ...rest, group }\n })\n}\n\n/** Sets the table's sort keys, or removes them with `null`. */\nexport function setSort(report: ReportDefinition, tableId: string, sort: readonly SortKey[] | null): CommandOutcome {\n return withTable(report, tableId, (table) => {\n const { sort: _old, ...rest } = table\n return sort === null ? rest : { ...rest, sort }\n })\n}\n\n/** The footer rows a table has in `which`, where they are, and how to give it others; or a refusal. */\nfunction footerOf(table: TableComponent, which: FooterRows, place: TablePlace) {\n if (which === 'totals') {\n return {\n rows: table.totals ?? [],\n at: { ...place, path: `${place.path}/totals` },\n set: (totals: readonly TableFooterRow[]): TableComponent => ({ ...table, totals }),\n }\n }\n const group = table.group\n if (group === undefined)\n return refuse('not-found', `${quote(place.componentId)} has no group, so it has no group footer`, { ...place, path: `${place.path}/group` })\n return {\n rows: group.footer,\n at: { ...place, path: `${place.path}/group/footer` },\n set: (footer: readonly TableFooterRow[]): TableComponent => ({ ...table, group: { ...group, footer } }),\n }\n}\n\n/** The footer rows in `which` changed by `change`, which is told where they are. */\nfunction withFooter(\n report: ReportDefinition,\n tableId: string,\n which: FooterRows,\n change: (rows: readonly TableFooterRow[], at: TablePlace) => readonly TableFooterRow[] | Refusal,\n): CommandOutcome {\n return withTable(report, tableId, (table, place) => {\n const footer = footerOf(table, which, place)\n if (isRefusal(footer)) return footer\n const rows = change(footer.rows, footer.at)\n return isRefusal(rows) ? rows : footer.set(rows)\n })\n}\n\n/** A refusal unless `index` is a row of `rows`. */\nconst checkRow = (rows: readonly TableFooterRow[], index: number, at: Place): Refusal | undefined =>\n checkIndex(index, rows.length - 1, `${rows.length} footer rows`, at)\n\nexport function insertFooterRow(report: ReportDefinition, tableId: string, which: FooterRows, index: number, row: TableFooterRow): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => checkIndex(index, rows.length, `${rows.length} footer rows`, at) ?? insertedAt(rows, index, row))\n}\n\nexport function removeFooterRow(report: ReportDefinition, tableId: string, which: FooterRows, index: number): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => checkRow(rows, index, at) ?? removedAt(rows, index))\n}\n\n/** Moves the footer row at `from` so that it ends at `to`. */\nexport function moveFooterRow(report: ReportDefinition, tableId: string, which: FooterRows, from: number, to: number): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => checkRow(rows, from, at) ?? checkRow(rows, to, at) ?? movedTo(rows, from, to))\n}\n\n/** Changes a footer row: its cells as a whole, or its style. */\nexport function updateFooterRow(report: ReportDefinition, tableId: string, which: FooterRows, index: number, patch: Patch<TableFooterRow>): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => checkRow(rows, index, at) ?? replacedAt(rows, index, patched(rows[index] as TableFooterRow, patch)))\n}\n\n/** Puts the cell of `cell.column` into a footer row: replacing that column's cell where it is, or appending it. */\nexport function putFooterCell(report: ReportDefinition, tableId: string, which: FooterRows, rowIndex: number, cell: TableFooterCell): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => {\n const outside = checkRow(rows, rowIndex, at)\n if (outside !== undefined) return outside\n const row = rows[rowIndex] as TableFooterRow\n const index = row.cells.findIndex(({ column }) => column === cell.column)\n return replacedAt(rows, rowIndex, { ...row, cells: index === -1 ? [...row.cells, cell] : replacedAt(row.cells, index, cell) })\n })\n}\n\nexport function removeFooterCell(report: ReportDefinition, tableId: string, which: FooterRows, rowIndex: number, columnId: string): CommandOutcome {\n return withFooter(report, tableId, which, (rows, at) => {\n const outside = checkRow(rows, rowIndex, at)\n if (outside !== undefined) return outside\n const row = rows[rowIndex] as TableFooterRow\n const index = row.cells.findIndex(({ column }) => column === columnId)\n if (index === -1) return refuse('not-found', `this footer row has no cell for column ${quote(columnId)}`, { ...at, path: `${at.path}/${rowIndex}/cells` })\n return replacedAt(rows, rowIndex, { ...row, cells: removedAt(row.cells, index) })\n })\n}\n","/**\n * A field removed with everything that reads it (0048): what a review\n * offers where a form version removed a field the report reads, and the\n * author would rather it printed no more.\n *\n * What reads it is what the diagnostics find, from one walk\n * (`reportParts`): a run, a format's currency, an image's source, a sort\n * key, a group's key, an aggregate's field, each where it is named; and an\n * expression, wherever it stands, that reads it by what the parser the\n * compiler asks says it reads (`reads.ts`), never a second reading of CEL.\n * Each reader goes with what holds it: the component, for its content or\n * its condition; the table, for its condition on its rows (0062); the\n * table's column, for its value or its condition; a\n * style rule alone, since a rule says how something prints and never\n * what; a footer cell, and its row where no cell of it is left; a sort\n * key, and the sort with its last; the group, for its key or its header;\n * an aggregate, and then every reader of that aggregate in turn, to the\n * end of the chain; a chart's series, alone. A table whose every column\n * goes, and a chart whose every series goes, goes whole, and\n * whatever stands inside a component that goes goes with it, once.\n *\n * The payment part and the e-invoice change by their own commands alone\n * (0039, `PART_COMMANDS`): a field either of them reads, directly or\n * through an aggregate, is refused as `read-by-part`, and nothing goes.\n * What is left is the validator's to judge, as every edit's is: a column\n * the e-invoice prints its lines by, gone, refuses the edit whole.\n *\n * `fieldReaders` walks a report and reads its expressions once, for every\n * field a review asks about: the removal, and the expressions a change of\n * the field's type can reach -- those that read it, directly, through an\n * aggregate or as the key of a group its table groups by it -- which a\n * review compiles alone.\n */\nimport { GROUP_KEY, walkComponents } from '@formancy/report-spec'\nimport type { ChartComponent, Component, DatasetRole, ReportDefinition, SortKey, StyleRule, TableComponent, TableFooterRow } from '@formancy/report-spec'\nimport { reportParts } from '../diagnostics/parts.js'\nimport type { ExpressionSite, NamedUse } from '../diagnostics/parts.js'\nimport { AGGREGATE_NAMES, expressionReads, READ_AS, readsMember } from '../expressions/reads.js'\nimport type { Reads } from '../expressions/reads.js'\nimport { quote, refuse } from '../outcome.js'\nimport type { CommandOutcome } from '../outcome.js'\nimport { removeComponent, updateComponent } from './components.js'\nimport { removeAggregate, removeField } from './declarations.js'\nimport { removeColumn, removeFooterCell, removeFooterRow, setGroup, setSort, updateColumn } from './table.js'\nimport type { FooterRows } from './table.js'\n\n/** Where a read stands: a JSON Pointer, and the component and column it is in. */\ntype Place = Pick<NamedUse, 'path' | 'componentId' | 'columnId'>\n\n/** Each component of a report by its id, and where it stands. */\ntype Placed = ReadonlyMap<string, { readonly path: string; readonly component: Component }>\n\n/** What holds a read of the field, and so goes with it. */\ntype Holder =\n | { readonly kind: 'part'; readonly part: 'paymentPart' | 'eInvoice'; readonly path: string }\n | { readonly kind: 'aggregate'; readonly index: number }\n | { readonly kind: 'component'; readonly id: string }\n | { readonly kind: 'rule'; readonly component: string; readonly column?: string; readonly index: number }\n | { readonly kind: 'column'; readonly table: string; readonly column: string }\n | { readonly kind: 'cell'; readonly table: string; readonly footer: FooterRows; readonly row: number; readonly column: string }\n | { readonly kind: 'sort'; readonly table: string; readonly index: number }\n | { readonly kind: 'group'; readonly table: string }\n | { readonly kind: 'series'; readonly chart: string; readonly series: string }\n\nconst PART = /^\\/(paymentPart|eInvoice)(?:\\/|$)/\nconst AGGREGATE = /^\\/aggregates\\/(\\d+)\\//\nconst RULE = /\\/styleWhen\\/(\\d+)\\/when\\/cel$/\nconst CELL = /^\\/(totals|group\\/footer)\\/(\\d+)\\/cells\\/(\\d+)\\//\nconst SORT = /^\\/sort\\/(\\d+)$/\nconst SERIES = /^\\/series\\/(\\d+)\\/of$/\n\n/** What holds a read of a chart at `rest`, its pointer inside the chart: the series that totals the field, and the chart itself for anything else. */\nfunction chartHolder(chart: ChartComponent, rest: string): Holder {\n const series = SERIES.exec(rest)\n // The walk named a series of the chart.\n return series === null\n ? { kind: 'component', id: chart.id }\n : { kind: 'series', chart: chart.id, series: (chart.series[Number(series[1])] as { readonly id: string }).id }\n}\n\n/** What holds a read of a table at `rest`, its pointer inside the table. */\nfunction tableHolder(table: TableComponent, rest: string, columnId: string | undefined): Holder {\n if (columnId !== undefined) return { kind: 'column', table: table.id, column: columnId }\n const cell = CELL.exec(rest)\n if (cell !== null) {\n const footer: FooterRows = cell[1] === 'totals' ? 'totals' : 'groupFooter'\n // The walk named a cell of a footer row the table holds.\n const rows = (footer === 'totals' ? table.totals : table.group?.footer) as readonly TableFooterRow[]\n const row = Number(cell[2])\n return { kind: 'cell', table: table.id, footer, row, column: (rows[row] as TableFooterRow).cells[Number(cell[3])]?.column as string }\n }\n if (rest.startsWith('/group/')) return { kind: 'group', table: table.id }\n const sort = SORT.exec(rest)\n return sort === null ? { kind: 'component', id: table.id } : { kind: 'sort', table: table.id, index: Number(sort[1]) }\n}\n\n/** What holds the read at `place`, in a report whose components are `placed`. */\nfunction holderOf(placed: Placed, place: Place): Holder {\n const part = PART.exec(place.path)\n if (part !== null) return { kind: 'part', part: part[1] as 'paymentPart' | 'eInvoice', path: place.path }\n const aggregate = AGGREGATE.exec(place.path)\n if (aggregate !== null) return { kind: 'aggregate', index: Number(aggregate[1]) }\n // Every other place a report names a field or an aggregate is in a component, which reportParts names.\n const found = placed.get(place.componentId as string) as { readonly path: string; readonly component: Component }\n const rule = RULE.exec(place.path)\n if (rule !== null)\n return { kind: 'rule', component: found.component.id, ...(place.columnId === undefined ? {} : { column: place.columnId }), index: Number(rule[1]) }\n if (found.component.kind === 'chart') return chartHolder(found.component, place.path.slice(found.path.length))\n if (found.component.kind !== 'table') return { kind: 'component', id: found.component.id }\n return tableHolder(found.component, place.path.slice(found.path.length), place.columnId)\n}\n\n/** One walk of a report: what it names where, each expression with what it reads, each component where it stands. */\ninterface Walk {\n readonly report: ReportDefinition\n readonly named: readonly NamedUse[]\n readonly sites: readonly { readonly site: ExpressionSite; readonly reads: Reads }[]\n readonly walked: readonly { readonly path: string; readonly component: Component }[]\n readonly placed: Placed\n}\n\n/** Every place that reads `fieldId` of `slot`, and every reader of an aggregate that reads it, in turn; and the expressions among them, by the pointer to their `cel`. */\nfunction readsOf(walk: Walk, slot: DatasetRole, fieldId: string): { readonly places: readonly Place[]; readonly expressions: ReadonlySet<string> } {\n const expressions = new Set<string>()\n const readers = (names: (use: NamedUse) => boolean, scope: readonly string[], id: string): Place[] => {\n const sites = walk.sites.filter(({ reads }) => readsMember(reads, scope, id)).map(({ site }) => site)\n for (const site of sites) expressions.add(site.path)\n return [...walk.named.filter(names), ...sites]\n }\n const places = readers((use) => use.kind === 'field' && use.field.dataset === slot && use.field.field === fieldId, [READ_AS[slot]], fieldId)\n const gone = new Set<number>()\n for (let next = 0; next < places.length; next++) {\n const aggregate = AGGREGATE.exec((places[next] as Place).path)\n const index = aggregate === null ? undefined : Number(aggregate[1])\n if (index === undefined || gone.has(index)) continue\n gone.add(index)\n const id = (walk.report.aggregates[index] as { readonly id: string }).id\n places.push(...readers((use) => use.kind === 'aggregate' && use.aggregate === id, AGGREGATE_NAMES, id))\n }\n return { places, expressions }\n}\n\n/** What goes from one table, by kind. */\ninterface TableParts {\n readonly columns: Set<string>\n /** Each cell once, by its footer, its row and its column. */\n readonly cells: Map<string, Extract<Holder, { kind: 'cell' }>>\n readonly sort: Set<number>\n group: boolean\n}\n\n/** The holders, gathered, once the payment part and the e-invoice are known to hold none: the components, the style rules by component and column, each table's parts, the aggregates by index. */\nfunction gathered(holders: readonly Exclude<Holder, { kind: 'part' }>[]) {\n const components = new Set<string>()\n const rules = new Map<string, Set<number>>()\n const tables = new Map<string, TableParts>()\n const aggregates = new Set<number>()\n const charts = new Map<string, Set<string>>()\n const of = (table: string): TableParts =>\n tables.get(table) ?? (tables.set(table, { columns: new Set(), cells: new Map(), sort: new Set(), group: false }).get(table) as TableParts)\n for (const holder of holders) {\n if (holder.kind === 'component') components.add(holder.id)\n else if (holder.kind === 'aggregate') aggregates.add(holder.index)\n else if (holder.kind === 'rule') {\n const key = ruleKey(holder.component, holder.column)\n rules.set(key, (rules.get(key) ?? new Set()).add(holder.index))\n } else if (holder.kind === 'column') of(holder.table).columns.add(holder.column)\n else if (holder.kind === 'cell') of(holder.table).cells.set(`${holder.footer} ${holder.row} ${holder.column}`, holder)\n else if (holder.kind === 'series') charts.set(holder.chart, (charts.get(holder.chart) ?? new Set()).add(holder.series))\n else if (holder.kind === 'sort') of(holder.table).sort.add(holder.index)\n else of(holder.table).group = true\n }\n return { components, rules, tables, aggregates, charts }\n}\n\n/** The key the style rules of a component, or of a column of a table, are gathered by. */\nconst ruleKey = (component: string, column?: string): string => `${component} ${column ?? ''}`\n\ntype Edit = (working: ReportDefinition) => CommandOutcome\n\n/** What goes of one footer of a table: the rows no cell of which is left, and the cells that go alone, by row and column. */\ninterface FooterFate {\n readonly rows: readonly number[]\n readonly cells: readonly { readonly row: number; readonly index: number; readonly column: string }[]\n}\n\n/** What goes of `rows`, a footer of a table whose `parts` go: a cell under a column that goes, with it; a cell that reads the field, alone; a row of which no cell is left, whole. */\nfunction footerFate(rows: readonly TableFooterRow[], footer: FooterRows, parts: TableParts): FooterFate {\n const fate: { rows: number[]; cells: { row: number; index: number; column: string }[] } = { rows: [], cells: [] }\n for (const [row, { cells }] of rows.entries()) {\n const read = (column: string): boolean => parts.cells.has(`${footer} ${row} ${column}`)\n if (cells.length > 0 && cells.every(({ column }) => parts.columns.has(column) || read(column))) fate.rows.push(row)\n else for (const [index, { column }] of cells.entries()) if (read(column) && !parts.columns.has(column)) fate.cells.push({ row, index, column })\n }\n return fate\n}\n\n/** The style rules of `rules` kept once those at `gone` go: null where none is left, which removes them. */\nfunction keptRules(rules: readonly StyleRule[], gone: ReadonlySet<number>): readonly StyleRule[] | null {\n const kept = rules.filter((_rule, index) => !gone.has(index))\n return kept.length === 0 ? null : kept\n}\n\n/** The pointers to the rules at `gone` under `path`, and the edit that takes them, through `edit`. */\nfunction ruleRemoval(\n path: string,\n gone: ReadonlySet<number> | undefined,\n edit: (kept: readonly StyleRule[] | null) => Edit,\n rules: readonly StyleRule[] | undefined,\n): { readonly pointers: string[]; readonly edits: Edit[] } {\n if (gone === undefined) return { pointers: [], edits: [] }\n // The walk named a rule of them; one found through an aggregate is found after one that reads the field itself.\n return {\n pointers: [...gone].sort((a, b) => a - b).map((index) => `${path}/styleWhen/${index}`),\n edits: [edit(keptRules(rules as readonly StyleRule[], gone))],\n }\n}\n\n/** What goes of `table`, at `path`, as pointers and as the commands that take it: its columns' rules and its columns, its sort keys, its group, its footers' rows and cells. */\nfunction tableRemoval(\n table: TableComponent,\n path: string,\n parts: TableParts | undefined,\n rules: ReadonlyMap<string, ReadonlySet<number>>,\n): { readonly pointers: string[]; readonly edits: Edit[] } {\n const pointers: string[] = []\n const edits: Edit[] = []\n const later: Edit[] = []\n for (const [index, column] of table.columns.entries()) {\n if (parts?.columns.has(column.id) === true) {\n pointers.push(`${path}/columns/${index}`)\n later.push((working) => removeColumn(working, table.id, column.id))\n continue\n }\n const kept = ruleRemoval(\n `${path}/columns/${index}`,\n rules.get(ruleKey(table.id, column.id)),\n (styleWhen) => (working) => updateColumn(working, table.id, column.id, { styleWhen }),\n column.styleWhen,\n )\n pointers.push(...kept.pointers)\n edits.push(...kept.edits)\n }\n if (parts === undefined) return { pointers, edits }\n // A sort key names its field outside any expression, so the walk named each in document order, once.\n pointers.push(...[...parts.sort].map((index) => `${path}/sort/${index}`))\n if (parts.group) pointers.push(`${path}/group`)\n const footers: [FooterRows, string, readonly TableFooterRow[] | undefined][] = [\n ['groupFooter', 'group/footer', parts.group ? undefined : table.group?.footer],\n ['totals', 'totals', table.totals],\n ]\n const rowEdits: Edit[] = []\n for (const [footer, at, rows] of footers) {\n const fate = footerFate(rows ?? [], footer, parts)\n const goes = [\n ...fate.rows.map((row) => ({ row, pointer: `${path}/${at}/${row}` })),\n ...fate.cells.map(({ row, index }) => ({ row, pointer: `${path}/${at}/${row}/cells/${index}` })),\n ]\n pointers.push(...goes.sort((a, b) => a.row - b.row).map(({ pointer }) => pointer))\n // A cell goes before any row does, while each row stands at its index; the rows go last first.\n edits.push(\n ...fate.cells.map(\n ({ row, column }) =>\n (working: ReportDefinition) =>\n removeFooterCell(working, table.id, footer, row, column),\n ),\n )\n rowEdits.push(...[...fate.rows].reverse().map((row) => (working: ReportDefinition) => removeFooterRow(working, table.id, footer, row)))\n }\n edits.push(...rowEdits)\n if (parts.sort.size > 0) {\n const kept = (table.sort as readonly SortKey[]).filter((_key, index) => !parts.sort.has(index))\n edits.push((working) => setSort(working, table.id, kept.length === 0 ? null : kept))\n }\n if (parts.group) edits.push((working) => setGroup(working, table.id, null))\n return { pointers, edits: [...edits, ...later] }\n}\n\n/** What goes of `chart`, at `path`, once the series at `gone` are known not to be all of them: those series, as pointers and as the one command that keeps the rest. */\nfunction chartRemoval(chart: ChartComponent, path: string, gone: ReadonlySet<string> | undefined): { readonly pointers: string[]; readonly edits: Edit[] } {\n if (gone === undefined) return { pointers: [], edits: [] }\n const pointers = chart.series.flatMap((series, index) => (gone.has(series.id) ? [`${path}/series/${index}`] : []))\n const kept = chart.series.filter((series) => !gone.has(series.id))\n return { pointers, edits: [(working) => updateComponent(working, chart.id, 'chart', { series: kept })] }\n}\n\n/** The removal of `fieldId` of `slot` from the report `walk` walked, with its readers, as `removeFieldWithReaders` gives it. */\nfunction removal(walk: Walk, slot: DatasetRole, fieldId: string): CommandOutcome<{ readonly removed: readonly string[] }> {\n const { report, walked, placed } = walk\n const fields = report.datasets[slot]?.fields\n if (fields === undefined) return refuse('not-found', `the report declares no ${slot} dataset`, { path: `/datasets/${slot}` })\n const index = fields.findIndex(({ id }) => id === fieldId)\n if (index === -1) return refuse('not-found', `no field of the ${slot} dataset is ${quote(fieldId)}`, { path: `/datasets/${slot}/fields` })\n const holders = readsOf(walk, slot, fieldId).places.map((place) => holderOf(placed, place))\n const part = holders.find((holder) => holder.kind === 'part')\n if (part !== undefined) {\n const what = part.part === 'paymentPart' ? \"the report's payment part\" : \"the report's e-invoice\"\n return refuse(\n 'read-by-part',\n `${quote(fieldId)} of the ${slot} dataset is read by ${what}, which only its own commands change: change what it reads there first`,\n { path: part.path },\n )\n }\n const { components, rules, tables, aggregates, charts } = gathered(holders as Exclude<Holder, { kind: 'part' }>[])\n // A table that loses every column holds nothing to print, and goes whole.\n for (const [id, parts] of tables)\n if ((placed.get(id)?.component as TableComponent).columns.every((column) => parts.columns.has(column.id))) components.add(id)\n // A chart that loses every series draws nothing it could say, and goes whole.\n for (const [id, series] of charts) if ((placed.get(id)?.component as ChartComponent).series.every((each) => series.has(each.id))) components.add(id)\n const removed: string[] = []\n const gone: string[] = []\n const edits: Edit[] = []\n for (const { component, path } of walked) {\n if (gone.some((prefix) => path.startsWith(`${prefix}/`))) continue\n if (components.has(component.id)) {\n gone.push(path)\n removed.push(path)\n edits.push((working) => removeComponent(working, component.id))\n continue\n }\n const own = ruleRemoval(\n path,\n rules.get(ruleKey(component.id)),\n (styleWhen) => (working) => updateComponent(working, component.id, component.kind, { styleWhen }),\n component.styleWhen,\n )\n const table = component.kind === 'table' ? tableRemoval(component, path, tables.get(component.id), rules) : { pointers: [], edits: [] }\n const series = component.kind === 'chart' ? chartRemoval(component, path, charts.get(component.id)) : { pointers: [], edits: [] }\n removed.push(...own.pointers, ...table.pointers, ...series.pointers)\n edits.push(...own.edits, ...table.edits, ...series.edits)\n }\n for (const at of [...aggregates].sort((a, b) => a - b)) {\n removed.push(`/aggregates/${at}`)\n const id = (report.aggregates[at] as { readonly id: string }).id\n edits.push((working) => removeAggregate(working, id))\n }\n removed.push(`/datasets/${slot}/fields/${index}`)\n edits.push((working) => removeField(working, slot, fieldId))\n let working = report\n for (const edit of edits) {\n const outcome = edit(working)\n if (!outcome.ok) return outcome\n working = outcome.report\n }\n return { ok: true, report: working, removed }\n}\n\n/** What reads each field of one report, from one walk of it and one reading of each of its expressions (0048). */\nexport interface FieldReaders {\n /** The field removed with everything that reads it: what `removeFieldWithReaders` gives, without walking the report again. */\n readonly removal: (slot: DatasetRole, fieldId: string) => CommandOutcome<{ readonly removed: readonly string[] }>\n /**\n * The expressions, by the JSON Pointer to their `cel`, whose compilation\n * a change of the field's type, or of whether it may be null, can\n * change: each that reads it, each that reads an aggregate that reads\n * it, in turn, and, for a field a table is grouped by, each that reads\n * that table's group's key (0062). `compileReport(report, them)`\n * compiles them alone.\n */\n readonly expressions: (slot: DatasetRole, fieldId: string) => ReadonlySet<string>\n}\n\n/** What reads each field of `report`, walked once and its expressions read once, for a review that asks of many fields. */\nexport function fieldReaders(report: ReportDefinition): FieldReaders {\n const parts = reportParts(report)\n const walked = [...walkComponents(report)]\n const walk: Walk = {\n report,\n named: parts.named,\n sites: parts.expressions.map((site) => ({ site, reads: expressionReads([site.cel]) })),\n walked,\n placed: new Map(walked.map((entry) => [entry.component.id, entry])),\n }\n return {\n removal: (slot, fieldId) => removal(walk, slot, fieldId),\n expressions: (slot, fieldId) => {\n const { expressions } = readsOf(walk, slot, fieldId)\n // A group's key is its own table's: the tables grouped by the field, whose group's header and footer name them.\n const grouping = new Set(\n walk.named\n .filter(\n (use) =>\n slot === 'detail' && use.kind === 'field' && use.field.dataset === 'detail' && use.field.field === fieldId && use.path.endsWith('/group/by'),\n )\n .map(({ componentId }) => componentId),\n )\n const keyed = walk.sites\n .filter(({ site, reads }) => grouping.has(site.componentId) && readsMember(reads, ['group'], GROUP_KEY))\n .map(({ site }) => site.path)\n return keyed.length === 0 ? expressions : new Set([...expressions, ...keyed])\n },\n }\n}\n\n/**\n * The field `fieldId` of the dataset in `slot` removed, with every\n * component, column, style rule, footer cell and row, sort key, group and\n * aggregate that reads it, and every reader of such an aggregate, as one\n * edit; and what went, as JSON Pointers into the report before it, in\n * document order, the aggregates and the field last. Refused as\n * `not-found` for a field the dataset does not declare, and as\n * `read-by-part` for one the payment part or the e-invoice reads.\n */\nexport function removeFieldWithReaders(report: ReportDefinition, slot: DatasetRole, fieldId: string): CommandOutcome<{ readonly removed: readonly string[] }> {\n return fieldReaders(report).removal(slot, fieldId)\n}\n","/**\n * Commands on a report's languages (0063): a language added, with no\n * words yet, or removed with its words; and a word, or an expression that\n * prints words, written in a language, or taken back.\n *\n * A word is named by its exact text in the report's own language, as the\n * translation keys it; an expression by its exact source. A command\n * refuses what names nothing: a language the report has no translation\n * in, a word or a source the report prints nowhere a word stands, a\n * translation taken back that is not there. Whether what it writes is a\n * translation the format holds -- not blank, a locale written as one --\n * the session's validator says, as it says of every command's result.\n * Nothing else changes: the report's own words are edited where they\n * stand, by the commands that edit them.\n */\nimport { reportWords, wordExpressionSites } from '@formancy/report-spec'\nimport type { Expression, ReportDefinition, Translation } from '@formancy/report-spec'\nimport { quote, refuse } from '../outcome.js'\nimport type { CommandOutcome, Refusal } from '../outcome.js'\n\n/** `report` with `translations`, none left out as no property at all: one report has one spelling. */\nfunction withTranslations(report: ReportDefinition, translations: readonly Translation[]): ReportDefinition {\n const { translations: _translations, ...rest } = report\n return translations.length === 0 ? rest : { ...rest, translations }\n}\n\n/** The report's translations, the one into `locale` among them and where it is; or the refusal when the report has none in it. */\ninterface Found {\n readonly translations: readonly Translation[]\n readonly index: number\n readonly translation: Translation\n}\n\nfunction translationIn(report: ReportDefinition, locale: string): Found | Refusal {\n const translations = report.translations ?? []\n const index = translations.findIndex((translation) => translation.locale === locale)\n if (index !== -1) return { translations, index, translation: translations[index] as Translation }\n const own = locale === report.locale ? \": it is the report's own, whose words are edited where they stand\" : ''\n return refuse('not-found', `the report has no translation in ${quote(locale)}${own}`, { path: '/translations' })\n}\n\n/** `report` with the translation `found` names replaced by `translation`. */\nfunction replaced(report: ReportDefinition, found: Found, translation: Translation): CommandOutcome {\n return {\n ok: true,\n report: withTranslations(\n report,\n found.translations.map((held, at) => (at === found.index ? translation : held)),\n ),\n }\n}\n\n/** `entries` with the entry `matches` names replaced by `entry`, or taken out for null, or `entry` after them; undefined when null takes out nothing. */\nfunction put<T>(entries: readonly T[], matches: (entry: T) => boolean, entry: T | null): readonly T[] | undefined {\n const at = entries.findIndex(matches)\n if (entry === null) return at === -1 ? undefined : entries.filter((_, index) => index !== at)\n return at === -1 ? [...entries, entry] : entries.map((held, index) => (index === at ? entry : held))\n}\n\n/** A language added, its words not yet written: every word is then missing in it, which the diagnostics say. Refused for the report's own and for one it has. */\nexport function addLanguage(report: ReportDefinition, locale: string): CommandOutcome {\n if (locale === report.locale || (report.translations ?? []).some((translation) => translation.locale === locale)) {\n return refuse('already-declared', `the report is written in ${quote(locale)} already`, { path: '/translations' })\n }\n return { ok: true, report: withTranslations(report, [...(report.translations ?? []), { locale, words: [], expressions: [] }]) }\n}\n\n/** A language removed with its words; the last leaves the report without translations. */\nexport function removeLanguage(report: ReportDefinition, locale: string): CommandOutcome {\n const found = translationIn(report, locale)\n if (!('index' in found)) return found\n return {\n ok: true,\n report: withTranslations(\n report,\n found.translations.filter((_, index) => index !== found.index),\n ),\n }\n}\n\n/**\n * `word` -- a word of the report's own language -- written as `text` in\n * `locale`, or, for null, its translation there taken back. A word the\n * report prints nowhere is refused, unless its translation is taken back:\n * one kept for a word the report no longer prints is said unused, and\n * removed by this.\n */\nexport function translateWord(report: ReportDefinition, locale: string, word: string, text: string | null): CommandOutcome {\n const found = translationIn(report, locale)\n if (!('index' in found)) return found\n if (text !== null && !reportWords(report).some((place) => place.text === word)) {\n return refuse('not-found', `the report prints no word ${quote(word)} to translate`)\n }\n const words = put(found.translation.words, (entry) => entry.word === word, text === null ? null : { word, text })\n if (words === undefined) return refuse('not-found', `${quote(word)} has no translation in ${quote(locale)} to take back`)\n return replaced(report, found, { ...found.translation, words })\n}\n\n/**\n * The expression whose source is `cel`, standing where a word does,\n * written as `expression` in `locale`, or, for null, its translation\n * there taken back. Whether it prints words, and whether the translation\n * prints what it does, the diagnostics say (0063).\n */\nexport function translateExpression(report: ReportDefinition, locale: string, cel: string, expression: Expression | null): CommandOutcome {\n const found = translationIn(report, locale)\n if (!('index' in found)) return found\n if (expression !== null && !wordExpressionSites(report).some((site) => site.cel === cel)) {\n return refuse('not-found', 'the report holds this expression nowhere a word stands, and an expression is translated only where it prints words')\n }\n const expressions = put(found.translation.expressions, (entry) => entry.cel === cel, expression === null ? null : { cel, expression })\n if (expressions === undefined) return refuse('not-found', `this expression has no translation in ${quote(locale)} to take back`)\n return replaced(report, found, { ...found.translation, expressions })\n}\n","/**\n * Every command by name, and a command as data: a name and its arguments.\n *\n * A proposal -- from an AI, from a saved macro, from another window -- is a\n * bounded list of operations, not code (plan 16). A descriptor is one such\n * operation, and it runs through exactly the function the builder calls, so\n * a proposal and a click cannot do the same thing two ways. A batch is\n * several of them as one command (0048): a transaction written down, so\n * that an edit of several commands -- a review's resolution -- travels as\n * data and is applied as one step.\n */\nimport { DATASET_ROLES, REGION_NAMES } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { quote, refuse } from '../outcome.js'\nimport type { Command, CommandOutcome } from '../outcome.js'\nimport { duplicateComponent, insertComponent, moveComponent, removeComponent, updateComponent } from './components.js'\nimport {\n addAsset,\n moveParameter,\n putAggregate,\n putAsset,\n putDataset,\n putField,\n putParameter,\n putStyle,\n removeAggregate,\n removeAsset,\n removeDataset,\n removeField,\n removeParameter,\n removeStyle,\n} from './declarations.js'\nimport { replaceDocument, setLocale, setPage, setTitle } from './document.js'\nimport { putEInvoice, removeEInvoice, setPaymentAccount, updateEInvoice } from './e-invoice.js'\nimport { putFirstPageHeader, removeFirstPageHeader } from './first-page-header.js'\nimport { putPaymentPart, removePaymentPart, updatePaymentPart } from './payment-part.js'\nimport { removeFieldWithReaders } from './readers.js'\nimport { addLanguage, removeLanguage, translateExpression, translateWord } from './translations.js'\nimport {\n insertColumn,\n insertFooterRow,\n moveColumn,\n moveFooterRow,\n putFooterCell,\n removeColumn,\n removeFooterCell,\n removeFooterRow,\n setGroup,\n setSort,\n updateColumn,\n updateFooterRow,\n} from './table.js'\n\n/** Every command a batch may hold: every command but the batch. */\nconst STEPS = Object.freeze({\n setTitle,\n setLocale,\n setPage,\n replaceDocument,\n putStyle,\n removeStyle,\n putDataset,\n removeDataset,\n putField,\n removeField,\n putParameter,\n removeParameter,\n moveParameter,\n addAsset,\n putAsset,\n removeAsset,\n putAggregate,\n removeAggregate,\n insertComponent,\n removeComponent,\n moveComponent,\n updateComponent,\n duplicateComponent,\n insertColumn,\n removeColumn,\n moveColumn,\n updateColumn,\n setGroup,\n setSort,\n insertFooterRow,\n removeFooterRow,\n moveFooterRow,\n updateFooterRow,\n putFooterCell,\n removeFooterCell,\n putFirstPageHeader,\n removeFirstPageHeader,\n putPaymentPart,\n updatePaymentPart,\n removePaymentPart,\n putEInvoice,\n updateEInvoice,\n removeEInvoice,\n setPaymentAccount,\n removeFieldWithReaders,\n addLanguage,\n removeLanguage,\n translateWord,\n translateExpression,\n})\n\nexport const COMMANDS = Object.freeze({ ...STEPS, batch })\n\nexport type CommandName = keyof typeof COMMANDS\n\n/** A command a batch may hold: any but a batch. */\nexport type StepName = keyof typeof STEPS\n\n/**\n * The commands that may change each part a report holds at its own level,\n * in no region: its payment part (0022, 0039), by the three made to edit\n * it, and its e-invoice (0027, 0044), by its own three; both by\n * `setPaymentAccount`, which changes the account an e-invoice and its\n * payment codes share in one edit; and either by `replaceDocument`, a\n * paste, an import or a proposal that rewrote the report, whose document\n * may hold another part than the one it replaces. Every other command\n * keeps each part the very object it found; registry.test.ts holds both\n * halves, reading which commands are which from here. A proposal that\n * names one of these may change whom a payment reaches -- a replacement\n * whatever else it changes, and `setPaymentAccount` always -- which 0039\n * and 0044 ask a proposal's review to show above every other change, the\n * part compared whole for a replacement, once proposals are reviewed. A\n * batch may hold any of them, so it is listed for both (0048).\n */\nexport const PART_COMMANDS = Object.freeze({\n paymentPart: Object.freeze(['putPaymentPart', 'updatePaymentPart', 'removePaymentPart', 'setPaymentAccount', 'replaceDocument', 'batch'] as const),\n eInvoice: Object.freeze(['putEInvoice', 'updateEInvoice', 'removeEInvoice', 'setPaymentAccount', 'replaceDocument', 'batch'] as const),\n}) satisfies { readonly [part in 'paymentPart' | 'eInvoice']: readonly CommandName[] }\n\n/** A command's arguments after the report. */\ntype ArgumentsOf<F> = F extends (report: ReportDefinition, ...rest: infer A) => unknown ? A : never\n\n/** A command as data: its name and its arguments after the report, typed per command. */\nexport type CommandDescriptor = {\n readonly [N in CommandName]: { readonly command: N; readonly args: Readonly<ArgumentsOf<(typeof COMMANDS)[N]>> }\n}[CommandName]\n\n/** A command a batch may hold, as data. */\nexport type StepDescriptor = Exclude<CommandDescriptor, { readonly command: 'batch' }>\n\n/**\n * Commands one batch holds. Chosen, not measured, as a proposal's bound\n * (plan 16): the largest batch a review writes is a relabel, a command for\n * the field and one for each text that says its label, far fewer; and a\n * batch read from JSON is refused past it before any of it runs. What a\n * batch at the bound costs is measured in 0048.\n */\nexport const MAX_BATCH_COMMANDS = 1000\n\nfunction isObject(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isLocation(value: unknown): boolean {\n return (\n isObject(value) &&\n (REGION_NAMES as readonly unknown[]).includes(value.region) &&\n typeof value.index === 'number' &&\n (value.parent === undefined || typeof value.parent === 'string') &&\n (value.column === undefined || typeof value.column === 'number')\n )\n}\n\n/**\n * What an argument read from JSON must be before its command runs, each\n * with the words a refusal says it in. Only what the command itself reads:\n * whether a string names something, or a number is a position in its list,\n * the command decides; a whole value it stores -- a component, a column, a\n * footer row, a dataset, a document -- the validator judges.\n */\nconst SHAPES = {\n text: { is: (value: unknown) => typeof value === 'string', said: 'a string' },\n textOrNull: { is: (value: unknown) => value === null || typeof value === 'string', said: 'a string, or null to remove it' },\n index: { is: (value: unknown) => typeof value === 'number', said: 'a number' },\n object: { is: isObject, said: 'an object' },\n objectOrNull: { is: (value: unknown) => value === null || isObject(value), said: 'an object, or null to remove it' },\n listOrNull: { is: (value: unknown) => value === null || Array.isArray(value), said: 'a list, or null to remove it' },\n list: { is: (value: unknown) => Array.isArray(value), said: 'a list' },\n location: { is: isLocation, said: 'a location: a region, an index, and a parent id and a column where it names them' },\n role: { is: (value: unknown) => (DATASET_ROLES as readonly unknown[]).includes(value), said: \"'header' or 'detail'\" },\n footer: { is: (value: unknown) => value === 'totals' || value === 'groupFooter', said: \"'totals' or 'groupFooter'\" },\n value: { is: () => true, said: 'a value' },\n} as const\n\ntype Shape = keyof typeof SHAPES\n\n/**\n * The shape of each command's arguments after the report, in order. A\n * table over every command, so a command added to `COMMANDS` without its\n * shapes does not compile; a test holds each list to its command's length.\n */\nexport const ARGUMENTS: { readonly [N in CommandName]: readonly Shape[] } = {\n setTitle: ['text'],\n setLocale: ['text'],\n setPage: ['object'],\n replaceDocument: ['value'],\n putStyle: ['text', 'object'],\n removeStyle: ['text'],\n putDataset: ['role', 'value'],\n removeDataset: ['role'],\n putField: ['role', 'text', 'object'],\n removeField: ['role', 'text'],\n putParameter: ['text', 'object'],\n removeParameter: ['text'],\n moveParameter: ['text', 'index'],\n addAsset: ['text', 'object'],\n putAsset: ['text', 'object'],\n removeAsset: ['text'],\n putAggregate: ['text', 'object'],\n removeAggregate: ['text'],\n insertComponent: ['location', 'value'],\n removeComponent: ['text'],\n moveComponent: ['text', 'location'],\n updateComponent: ['text', 'text', 'object'],\n duplicateComponent: ['text'],\n insertColumn: ['text', 'index', 'value'],\n removeColumn: ['text', 'text'],\n moveColumn: ['text', 'text', 'index'],\n updateColumn: ['text', 'text', 'object'],\n setGroup: ['text', 'objectOrNull'],\n setSort: ['text', 'listOrNull'],\n insertFooterRow: ['text', 'footer', 'index', 'value'],\n removeFooterRow: ['text', 'footer', 'index'],\n moveFooterRow: ['text', 'footer', 'index', 'index'],\n updateFooterRow: ['text', 'footer', 'index', 'object'],\n putFooterCell: ['text', 'footer', 'index', 'object'],\n removeFooterCell: ['text', 'footer', 'index', 'text'],\n putFirstPageHeader: ['list'],\n removeFirstPageHeader: [],\n putPaymentPart: ['object'],\n updatePaymentPart: ['object'],\n removePaymentPart: [],\n putEInvoice: ['object'],\n updateEInvoice: ['object'],\n removeEInvoice: [],\n setPaymentAccount: ['text'],\n removeFieldWithReaders: ['role', 'text'],\n addLanguage: ['text'],\n removeLanguage: ['text'],\n translateWord: ['text', 'text', 'textOrNull'],\n translateExpression: ['text', 'text', 'objectOrNull'],\n batch: ['list'],\n}\n\n/** Why `args` are not arguments `name` takes, or undefined when they are. Never quotes an argument. */\nfunction misfit(name: CommandName, args: unknown): string | undefined {\n const shapes = ARGUMENTS[name]\n if (!Array.isArray(args) || args.length !== shapes.length) {\n return `${name} takes ${shapes.length} ${shapes.length === 1 ? 'argument' : 'arguments'} after the report: ${shapes.map((shape) => SHAPES[shape].said).join('; ')}`\n }\n const wrong = shapes.findIndex((shape, index) => !SHAPES[shape].is(args[index]))\n return wrong === -1 ? undefined : `argument ${wrong + 1} of ${name} is not ${SHAPES[shapes[wrong] as Shape].said}`\n}\n\n/**\n * The command a descriptor names, bound to its arguments. A descriptor read\n * from JSON was never type-checked, so it is checked here: a name that is\n * not a command gives a command that refuses with `unknown-command`, and\n * arguments too few, too many or of a type the command cannot read give one\n * that refuses with `invalid-arguments`. Either way the descriptor never\n * throws. What the command makes of arguments of the right types reaches\n * the validator, as any edit's result does.\n */\nexport function describedCommand(descriptor: CommandDescriptor): Command {\n const { command, args } = descriptor as { readonly command: unknown; readonly args: unknown }\n if (typeof command !== 'string' || !Object.hasOwn(COMMANDS, command)) {\n const name = typeof command === 'string' ? quote(command) : 'a command with no name'\n return () => refuse('unknown-command', `${name} is not a command this package has`)\n }\n const name = command as CommandName\n const wrong = misfit(name, args)\n if (wrong !== undefined) return () => refuse('invalid-arguments', wrong)\n const run = COMMANDS[name] as (report: ReportDefinition, ...rest: unknown[]) => CommandOutcome\n return (report) => run(report, ...(args as unknown[]))\n}\n\n/**\n * The commands `steps` describe, run one after the other as one command:\n * the report the last leaves, which the session then validates once, as a\n * transaction's end; or the first refusal, word for word, and nothing\n * after it runs. A step is checked as any descriptor is, and one that is\n * no object, or is a batch itself, is refused; so is a batch of more than\n * `MAX_BATCH_COMMANDS` commands, before any runs. Never throws on what a\n * batch read from JSON holds: a step runs on the report the steps before\n * it left, which nothing has validated yet -- a document replaced by one\n * of nothing, a table inserted with no columns -- and a command written\n * for a report the validator accepts may throw on that; such a step is\n * refused, the batch with it.\n */\nexport function batch(report: ReportDefinition, steps: readonly StepDescriptor[]): CommandOutcome {\n if (steps.length > MAX_BATCH_COMMANDS)\n return refuse('invalid-arguments', `a batch holds at most ${MAX_BATCH_COMMANDS} commands, and this one ${steps.length}`)\n let working = report\n for (const [index, step] of steps.entries()) {\n if (!isObject(step)) return refuse('invalid-arguments', `step ${index + 1} of the batch is not a command: an object naming one, and its arguments`)\n if ((step as { readonly command?: unknown }).command === 'batch')\n return refuse('invalid-arguments', `step ${index + 1} of the batch is a batch: a batch holds commands, and is one edit already`)\n const outcome = stepOn(working, step, index)\n if (!outcome.ok) return outcome\n working = outcome.report\n }\n return { ok: true, report: working }\n}\n\n/** `step` run on `working`, or refused where it throws on a report no validator has seen; what it threw is not quoted, since it may quote the report. */\nfunction stepOn(working: ReportDefinition, step: StepDescriptor, index: number): CommandOutcome {\n try {\n return describedCommand(step)(working)\n } catch {\n return refuse('invalid-arguments', `step ${index + 1} of the batch could not run on the report the steps before it left: the batch is refused whole`)\n }\n}\n","/**\n * Several commands as one edit: the draft they run against, and the verdict\n * on where they leave it -- what a session's transaction commits, and what a\n * proposal's review shows before anybody applies it (plan 16).\n *\n * One draft and one verdict for both, so a preview and the commit that\n * follows it cannot disagree about what a proposal does\n * ([0008](../../../docs/decisions/0008-edits-are-commands-and-a-refused-edit-changes-nothing.md)).\n */\nimport { validateReport } from '@formancy/report-spec'\nimport type { ReportDefinition, ReportError } from '@formancy/report-spec'\nimport { describedCommand } from './commands/registry.js'\nimport type { CommandDescriptor } from './commands/registry.js'\nimport { refuse } from './outcome.js'\nimport type { Command, CommandOutcome, Refusal } from './outcome.js'\n\n/** The working document inside a transaction, and the way to edit it. */\nexport interface Draft {\n /** The document as the edits so far have left it, which need not be valid. */\n document(): ReportDefinition\n /** Runs a command against the draft. After a refusal nothing more runs: each later call gives that refusal. */\n apply<E extends object>(command: Command<E>): CommandOutcome<E>\n apply(descriptor: CommandDescriptor): CommandOutcome\n}\n\n/**\n * Whatever a draft's callback returns, so long as it is not a promise. An\n * await inside the callback would end the edit with half its steps run, so\n * an async callback does not compile, and a promise that reaches the edit\n * anyway is refused when it runs.\n */\nexport type Synchronous<R> = R & (R extends PromiseLike<unknown> ? never : unknown)\n\nexport function commandOf<E extends object>(command: Command<E> | CommandDescriptor): Command<E> {\n return typeof command === 'function' ? command : describedCommand(command)\n}\n\nfunction thenable(value: unknown): boolean {\n return (typeof value === 'object' || typeof value === 'function') && value !== null && typeof (value as { then?: unknown }).then === 'function'\n}\n\n/**\n * Runs `run` against a draft of `report`: where its commands leave the\n * report, not yet validated, or the first refusal. The draft ends when\n * `run` returns or throws, and reading or editing it after that throws.\n * Throws a TypeError, having run nothing to completion, when `run` returns\n * a promise.\n */\nexport function drafted<R>(report: ReportDefinition, run: (draft: Draft) => Synchronous<R>): CommandOutcome {\n let working = report\n let refused: Refusal | undefined\n let open = true\n const live = (): void => {\n if (!open) throw new Error('this edit has ended: its draft cannot be read or edited any more')\n }\n const draft: Draft = {\n document: () => {\n live()\n return working\n },\n apply: <E extends object>(command: Command<E> | CommandDescriptor): CommandOutcome<E> => {\n live()\n if (refused !== undefined) return refused\n const outcome = commandOf(command)(working)\n if (outcome.ok) working = outcome.report\n else refused = outcome\n return outcome\n },\n }\n let returned: unknown\n try {\n returned = run(draft)\n } finally {\n open = false\n }\n if (thenable(returned)) throw new TypeError('an edit runs synchronously: await before it, not inside it')\n return refused ?? { ok: true, report: working }\n}\n\n/** The refusal for a result the validator refused, pointing at its first error; it gives at least one. */\nfunction invalid(errors: readonly ReportError[]): Refusal {\n const first = errors[0] as ReportError\n return {\n ...refuse('invalid-document', `the edit would leave a report that is not valid: ${first.message}`, { path: first.path, componentId: first.componentId }),\n errors,\n }\n}\n\n/** `candidate` as the validator's copy of it, or the refusal that carries the validator's errors. */\nexport function validated(candidate: unknown): CommandOutcome {\n const verdict = validateReport(candidate)\n return verdict.valid ? { ok: true, report: verdict.report } : invalid(verdict.errors)\n}\n\n/**\n * Runs several commands against `report` as a transaction would, and gives\n * the validated result -- the validator's copy -- or the first refusal, or\n * the validator's errors for an invalid end. Nothing is committed anywhere,\n * and `report` is left as it was. Throws as `drafted` does.\n */\nexport function tryEdit<R>(report: ReportDefinition, run: (draft: Draft) => Synchronous<R>): CommandOutcome {\n const outcome = drafted(report, run)\n return outcome.ok ? validated(outcome.report) : outcome\n}\n","/**\n * Snapshots: the frozen documents a session holds, and the mutable copies\n * it hands out.\n */\n\n/** A deeply mutable copy of a readonly type: what `exportDocument` returns. */\nexport type Mutable<T> = T extends readonly (infer U)[] ? Mutable<U>[] : T extends object ? { -readonly [K in keyof T]: Mutable<T[K]> } : T\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** The id an item of a list is known by, when it has one: a component's, a table column's, a declaration's. */\nfunction idOf(item: unknown): string | undefined {\n return isRecord(item) && typeof item.id === 'string' ? item.id : undefined\n}\n\n/**\n * What each item of `next` is compared with: the item of `before` with the\n * same id, so an insert, a remove or a move does not make everything after\n * it look changed; otherwise the item at the same position, for items that\n * have no id -- a column slot, a footer row, a cell, an inline run.\n */\nfunction counterparts(next: readonly unknown[], before: readonly unknown[]): unknown[] {\n const byId = new Map<string, unknown>()\n for (const item of before) {\n const id = idOf(item)\n if (id !== undefined && !byId.has(id)) byId.set(id, item)\n }\n return next.map((item, index) => {\n const id = idOf(item)\n return id !== undefined && byId.has(id) ? byId.get(id) : before[index]\n })\n}\n\nfunction settle(next: unknown, previous: unknown): unknown {\n if (typeof next !== 'object' || next === null) return next\n if (Array.isArray(next)) {\n const before: readonly unknown[] = Array.isArray(previous) ? previous : []\n const compared = counterparts(next, before)\n const items = next.map((item: unknown, index) => settle(item, compared[index]))\n const same = Array.isArray(previous) && before.length === items.length && items.every((item, index) => item === before[index])\n return same ? previous : Object.freeze(items)\n }\n const before = isRecord(previous) ? previous : undefined\n const entries = Object.keys(next).map((key) => [key, settle((next as Record<string, unknown>)[key], before?.[key])] as const)\n const same =\n before !== undefined &&\n Object.keys(before).length === entries.length &&\n entries.every(([key, value]) => Object.hasOwn(before, key) && before[key] === value)\n return same ? previous : Object.freeze(Object.fromEntries(entries))\n}\n\n/**\n * `next` as a deeply frozen snapshot that shares every subtree equal to its\n * counterpart in `previous`, itself a snapshot this made, or is `previous`\n * itself when the two are equal. An object's counterpart is the value under\n * the same key; a list item's is the item with the same id in the same list,\n * or the one at the same position when it has no id. Key order does not\n * count, as it does not in the canonical hash.\n *\n * So an edit leaves every component, column and declaration it did not\n * change as it was, wherever an insert, a remove or a move within its list\n * shifted it. A component moved into another list is compared with what\n * stood at its new position there, and is usually a new object.\n *\n * Built new, never by freezing `next` in place, so nothing a caller still\n * holds becomes frozen under it, and a caller's later write cannot reach\n * the snapshot. The sharing is what makes a history of whole-document\n * snapshots cost what its edits changed, and what lets a builder keep a\n * component's rendering while that component's object is the same.\n */\nexport function settled<T>(next: T, previous: unknown): T {\n return settle(next, previous) as T\n}\n\n/** A deep, mutable copy of JSON data. A snapshot is JSON by construction: the validator read it. */\nexport function thawed<T>(value: T): Mutable<T> {\n return JSON.parse(JSON.stringify(value)) as Mutable<T>\n}\n","/**\n * The report session: one document, its revision and its undo history,\n * shared by every view of it -- the React builder, the Angular builder, a\n * proposal being reviewed.\n *\n * It follows formancy's builder session (`@formancy/builder-core`), and\n * three rules shape it\n * ([0008](../../../docs/decisions/0008-edits-are-commands-and-a-refused-edit-changes-nothing.md)):\n *\n * - **It never holds a document the validator refuses.** Every edit is a\n * command run against the current document; its result is validated\n * whole, and only a valid result is committed. A refused edit changes\n * nothing: not the document, not its identity, not the revision, not the\n * history, and no listener hears of it.\n * - **A committed document is a frozen snapshot**, the same object until\n * the next commit, so `useSyncExternalStore` and Angular signals can\n * compare it by identity. What an edit did not change keeps its identity\n * too, matched by id within its list, so a view of one component redraws\n * only when that component changed or moved to another list.\n * - **History is snapshots.** Undo puts back the very document that was\n * there; an edit after an undo clears what could be redone.\n */\nimport { reportHash, validateReport } from '@formancy/report-spec'\nimport type { ReportDefinition, ReportError } from '@formancy/report-spec'\nimport type { CommandDescriptor } from './commands/registry.js'\nimport { commandOf, drafted, validated } from './draft.js'\nimport type { Draft, Synchronous } from './draft.js'\nimport { refuse } from './outcome.js'\nimport type { Command, CommandOutcome, Refusal } from './outcome.js'\nimport { settled, thawed } from './snapshot.js'\nimport type { Mutable } from './snapshot.js'\n\n/**\n * Undo steps a session keeps unless told otherwise; past it, the oldest is\n * dropped. Chosen, not measured: two hundred steps is longer than an\n * editing session's worth of undoing anyone does, and it bounds the\n * history's memory. A step holds a whole snapshot, but a snapshot shares\n * every part its edit did not change with the one before it, so a step\n * costs about what its edit changed -- except a component moved into\n * another list, which is copied with all it holds, and a replaced document,\n * which shares what happens to be equal and nothing else.\n */\nexport const DEFAULT_HISTORY_LIMIT = 200\n\n/** The label a step gets when the edit was given none and is not a descriptor. */\nconst UNLABELLED = 'edit'\n\nexport interface SessionOptions {\n /** Undo steps to keep; a whole number, 0 for none. DEFAULT_HISTORY_LIMIT when absent. */\n readonly historyLimit?: number\n}\n\nexport interface EditOptions {\n /** What the toolbar calls this step: \"Undo <label>\". A descriptor's command name, or 'edit', when absent. */\n readonly label?: string\n /** The hash of the document the edit was made against; an edit made against another is refused as stale. */\n readonly expectedHash?: string\n}\n\nexport interface ReportSession {\n /** The current document: frozen, and the same object until the next change. */\n document(this: void): ReportDefinition\n /** Counts changes: one per committed edit, undo or redo. A refused edit, or one that changed nothing, is not one. */\n revision(): number\n /** `reportHash` of the current document, what a save or a proposal is bound to. */\n hash(this: void): string\n /**\n * Calls `listener` after every change, synchronously, until the function\n * returned is called. A listener that throws does not stop the others;\n * once all have run, its error is thrown from the call that made the\n * change -- which has been made -- or an AggregateError when several threw.\n */\n subscribe(this: void, listener: () => void): () => void\n /**\n * Runs a command against the document and commits the result if the\n * validator accepts it. A command returns the next report and never edits\n * the session: one that calls the session while it runs throws.\n */\n apply<E extends object>(command: Command<E>, options?: EditOptions): CommandOutcome<E>\n apply(descriptor: CommandDescriptor, options?: EditOptions): CommandOutcome\n /**\n * Runs several commands as one edit: one undo step, one notification,\n * validated once at the end, so the draft may be invalid in between. A\n * refused command, or an invalid end, refuses the whole and changes\n * nothing; an exception thrown by `run` passes through, changing nothing.\n * `run` is synchronous: an async one does not compile, and a promise\n * returned anyway is refused with a TypeError before anything commits.\n * `tryEdit` gives the same verdict without committing.\n */\n transaction<R>(label: string, run: (draft: Draft) => Synchronous<R>, options?: Pick<EditOptions, 'expectedHash'>): CommandOutcome\n /** Takes a whole document -- a paste, an import, a proposal -- as one undoable edit, validated like any other. */\n replaceDocument(next: unknown, options?: EditOptions): CommandOutcome\n canUndo(): boolean\n canRedo(): boolean\n /** Puts back the document before the last step; false when there is none. */\n undo(): boolean\n /** Takes the last undone step again; false when there is none. */\n redo(): boolean\n /** The label of the step undo would take back. */\n undoLabel(): string | undefined\n /** The label of the step redo would take again. */\n redoLabel(): string | undefined\n /** A deep, mutable copy of the document, safe to hand to anything. */\n exportDocument(): Mutable<ReportDefinition>\n}\n\nexport type SessionOpening = { readonly ok: true; readonly session: ReportSession } | { readonly ok: false; readonly errors: readonly ReportError[] }\n\n/** A document in the history, and the label of the step that leads away from it. */\ninterface Step {\n readonly document: ReportDefinition\n readonly label: string\n}\n\n/** What the session is in the middle of, during which nothing may edit it: its own work is not done. */\nconst BUSY = {\n transaction: 'the session is in a transaction: edit the draft the transaction was given, and let it commit',\n command: 'the session is running a command: a command returns the next report, and never edits the session',\n} as const\n\n/**\n * A session over `document`, or the validator's reasons it is not a report\n * this package reads. Never throws on a bad document: a file a person\n * picked is an expected failure. Throws a RangeError for a history limit\n * that is not a whole number from 0.\n */\nexport function openReportSession(document: unknown, options: SessionOptions = {}): SessionOpening {\n const limit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT\n if (!Number.isInteger(limit) || limit < 0) throw new RangeError(`a history limit is a whole number of steps from 0, not ${String(limit)}`)\n const opened = validateReport(document)\n if (!opened.valid) return { ok: false, errors: opened.errors }\n\n let present: ReportDefinition = settled(opened.report, undefined)\n let revision = 0\n const past: Step[] = []\n const future: Step[] = []\n const subscriptions = new Set<{ readonly listener: () => void }>()\n const hashes = new WeakMap<ReportDefinition, string>()\n let busy: keyof typeof BUSY | undefined\n\n function notify(): void {\n const errors: unknown[] = []\n for (const subscription of [...subscriptions]) {\n // Unsubscribed by an earlier listener in this round: not called.\n if (!subscriptions.has(subscription)) continue\n try {\n subscription.listener()\n } catch (error) {\n errors.push(error)\n }\n }\n if (errors.length === 1) throw errors[0]\n if (errors.length > 1) throw new AggregateError(errors, `${errors.length} session listeners threw`)\n }\n\n function hash(): string {\n let known = hashes.get(present)\n if (known === undefined) {\n known = reportHash(present)\n hashes.set(present, known)\n }\n return known\n }\n\n function idle(): void {\n if (busy !== undefined) throw new Error(BUSY[busy])\n }\n\n /** `work`'s result, with the session refusing to be edited while it runs. */\n function during<T>(what: keyof typeof BUSY, work: () => T): T {\n busy = what\n try {\n return work()\n } finally {\n busy = undefined\n }\n }\n\n function stale(expectedHash: string | undefined): Refusal | undefined {\n if (expectedHash === undefined || expectedHash === hash()) return undefined\n return refuse('stale-document', 'the edit was made against a version of the report that has since changed')\n }\n\n /** Validates `candidate`, and commits it as one step unless it is refused or changes nothing. */\n function commit(candidate: unknown, label: string): CommandOutcome {\n const verdict = validated(candidate)\n if (!verdict.ok) return verdict\n const next = settled(verdict.report, present)\n if (next === present) return { ok: true, report: present }\n past.push({ document: present, label })\n if (past.length > limit) past.shift()\n future.length = 0\n present = next\n revision += 1\n notify()\n return { ok: true, report: next }\n }\n\n /** Moves one step from `from` to `to`, the present going the other way. */\n function step(from: Step[], to: Step[]): boolean {\n idle()\n const taken = from.pop()\n if (taken === undefined) return false\n to.push({ document: present, label: taken.label })\n present = taken.document\n revision += 1\n notify()\n return true\n }\n\n function apply<E extends object>(command: Command<E> | CommandDescriptor, options: EditOptions = {}): CommandOutcome<E> {\n idle()\n const refusal = stale(options.expectedHash)\n if (refusal !== undefined) return refusal\n const outcome = during('command', () => commandOf(command)(present))\n if (!outcome.ok) return outcome\n const label = options.label ?? (typeof command === 'function' ? UNLABELLED : command.command)\n const committed = commit(outcome.report, label)\n return committed.ok ? { ...outcome, report: committed.report } : committed\n }\n\n function transaction<R>(label: string, run: (draft: Draft) => Synchronous<R>, options: Pick<EditOptions, 'expectedHash'> = {}): CommandOutcome {\n idle()\n const refusal = stale(options.expectedHash)\n if (refusal !== undefined) return refusal\n const outcome = during('transaction', () => drafted(present, run))\n return outcome.ok ? commit(outcome.report, label) : outcome\n }\n\n const session: ReportSession = {\n document: () => present,\n revision: () => revision,\n hash,\n subscribe(listener) {\n const subscription = { listener }\n subscriptions.add(subscription)\n return () => {\n subscriptions.delete(subscription)\n }\n },\n apply,\n transaction,\n replaceDocument(next, options = {}) {\n idle()\n return stale(options.expectedHash) ?? commit(next, options.label ?? 'replaceDocument')\n },\n canUndo: () => past.length > 0,\n canRedo: () => future.length > 0,\n undo: () => step(past, future),\n redo: () => step(future, past),\n undoLabel: () => past.at(-1)?.label,\n redoLabel: () => future.at(-1)?.label,\n exportDocument: () => thawed(present),\n }\n return { ok: true, session }\n}\n","/**\n * Where a component stands, every place one could go, and the places one\n * may go: what a builder needs for a drop target, a keyboard move and focus\n * after a deletion (plan 8, plan 21's \"valid drop destinations\").\n *\n * Where a component may stand is the validator's to decide (0007): a page\n * counter only in the page header and footer, a table never inside columns.\n * So the destinations are found by asking it, place by place, rather than\n * by a second copy of its placement rules that could disagree with it.\n */\nimport { heldRegions, validateReport, walkComponents } from '@formancy/report-spec'\nimport type { Component, RegionName, ReportDefinition } from '@formancy/report-spec'\nimport { insertComponent, moveComponent, removeComponent } from './commands/components.js'\nimport type { CommandOutcome } from './outcome.js'\nimport { heldLists, standing } from './tree.js'\nimport type { Location } from './tree.js'\n\n/** A columns block's list: the pointer to the block, and the column. */\nconst SLOT = /^(.*)\\/columns\\/(\\d+)\\/components$/\n\n/**\n * Where the component `id` stands, as the location `moveComponent` and\n * `insertComponent` take: a move to it puts the component back where it\n * was. Undefined when the report has no such component.\n */\nexport function locationOf(report: ReportDefinition, id: string): Location | undefined {\n const all = walkComponents(report)\n const found = all.find(({ component }) => component.id === id)\n if (found === undefined) return undefined\n const { pointer, index } = standing(found.path)\n if (pointer === `/regions/${found.region}`) return { region: found.region, index }\n // Inside a container: a columns block's column, or another container's\n // one list, under `components`.\n const slot = SLOT.exec(pointer)\n const parentPath = slot === null ? pointer.slice(0, -'/components'.length) : (slot[1] as string)\n const parent = all.find(({ path }) => path === parentPath)?.component.id as string\n return { region: found.region, parent, ...(slot === null ? {} : { column: Number(slot[2]) }), index }\n}\n\n/**\n * Every place a component could be put, in reading order, in every region\n * the report holds: before each component and at the end of each list, a\n * container's places right after the place before the container. A region\n * the report leaves out has none; it is given one by its own command\n * (0060). Each is a location `insertComponent`\n * takes; whether the validator accepts what is put there is\n * `validLocations`' question.\n */\nexport function locations(report: ReportDefinition): Location[] {\n const found: Location[] = []\n const visit = (region: RegionName, list: readonly Component[], place: Omit<Location, 'region' | 'index'>): void => {\n for (const [index, component] of list.entries()) {\n found.push({ region, ...place, index })\n for (const { column, list: held } of heldLists(component)) visit(region, held, { parent: component.id, ...(column === undefined ? {} : { column }) })\n }\n found.push({ region, ...place, index: list.length })\n }\n for (const [region, list] of heldRegions(report.regions)) visit(region, list, {})\n return found\n}\n\n/**\n * The places `subject` may go, in reading order: for a new component, each\n * location where inserting it gives a report the validator accepts; for the\n * id of one the report holds, each location a move of it to gives one --\n * read, as `moveComponent` reads it, in the report without it. None for an\n * id the report lacks, or a component no place accepts, such as a second\n * table in a report that is an e-invoice (0062) or one whose id is taken.\n *\n * It validates the whole report once per place, so its cost is the\n * report's size times its number of places: a builder asks it when a drag\n * starts, not on every pointer move.\n */\nexport function validLocations(report: ReportDefinition, subject: Component | string): Location[] {\n if (typeof subject !== 'string') return acceptedOf(locations(report), (location) => insertComponent(report, location, subject))\n const without = removeComponent(report, subject)\n return without.ok ? acceptedOf(locations(without.report), (location) => moveComponent(report, subject, location)) : []\n}\n\n/** The candidates where `put` gives a report the validator accepts. */\nfunction acceptedOf(candidates: readonly Location[], put: (location: Location) => CommandOutcome): Location[] {\n return candidates.filter((location) => {\n const outcome = put(location)\n return outcome.ok && validateReport(outcome.report).valid\n })\n}\n","/**\n * The order aggregates are computed in, and those that never can be.\n *\n * What an aggregate's expression reads from each row is read in the row\n * scope, which binds `totals`, so a share of the whole is\n * `divide(row.amount * dec(\"100\"), totals.subtotal, 2)`. Such an aggregate\n * needs the totals it reads computed first, over every row: the runtime\n * computes aggregates in an order where each comes after every aggregate it\n * reads. One that reads itself -- directly, or through others -- has no\n * place in any order, and neither has one that reads such an aggregate.\n */\nimport { parse, referencedPaths } from '@formancy/expressions'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { diagnostic } from '../diagnostics/codes.js'\nimport type { Diagnostic } from '../diagnostics/codes.js'\nimport type { ExpressionSite } from '../diagnostics/parts.js'\nimport { quote } from '../outcome.js'\nimport { pathParts } from './compile-site.js'\nimport { readSpans } from './spans.js'\n\n/** For each aggregate -- every one has an entry -- the declared aggregates its expression reads as totals, once each, in the order first read. */\nexport function aggregateReads(report: ReportDefinition): ReadonlyMap<string, readonly string[]> {\n const declared = new Set(report.aggregates.map(({ id }) => id))\n return new Map(\n report.aggregates.map((aggregate) => {\n const parsed = aggregate.of?.kind === 'expression' ? parse(aggregate.of.expression.cel) : undefined\n if (parsed?.ok !== true) return [aggregate.id, []]\n const reads = referencedPaths(parsed.ast)\n .map(pathParts)\n .flatMap(({ name, member }) => (name === 'totals' && member !== undefined && declared.has(member) ? [member] : []))\n return [aggregate.id, [...new Set(reads)]]\n }),\n )\n}\n\n/** What the aggregate `id` reads; `aggregateReads` gives every aggregate an entry. */\nfunction readsOf(reads: ReadonlyMap<string, readonly string[]>, id: string): readonly string[] {\n return reads.get(id) as readonly string[]\n}\n\n/**\n * The aggregates in an order where each comes after every aggregate it\n * reads, and otherwise the earliest declared first; and, in declaration\n * order, those that have no place in it.\n */\nexport function aggregateOrder(\n report: ReportDefinition,\n reads: ReadonlyMap<string, readonly string[]>,\n): { readonly order: readonly string[]; readonly unordered: readonly string[] } {\n const placed = new Set<string>()\n const ready = (id: string): boolean => !placed.has(id) && readsOf(reads, id).every((read) => placed.has(read))\n for (let next = report.aggregates.find(({ id }) => ready(id)); next !== undefined; next = report.aggregates.find(({ id }) => ready(id))) placed.add(next.id)\n return { order: [...placed], unordered: report.aggregates.map(({ id }) => id).filter((id) => !placed.has(id)) }\n}\n\n/** Whether `from` reaches `to` by what the aggregates read, among `among`. */\nfunction reaches(from: string, to: string, reads: ReadonlyMap<string, readonly string[]>, among: ReadonlySet<string>): boolean {\n const seen = new Set<string>()\n const visit = (id: string): boolean =>\n readsOf(reads, id).some((read) => {\n if (read === to) return true\n if (seen.has(read) || !among.has(read)) return false\n seen.add(read)\n return visit(read)\n })\n return visit(from)\n}\n\n/**\n * The diagnostic for the aggregate `id`, which has no place in the order:\n * at the first total it reads that has none either, saying whether that\n * read closes a circle back to it or reaches one.\n */\nexport function cycleDiagnostic(id: string, site: ExpressionSite, reads: ReadonlyMap<string, readonly string[]>, unordered: ReadonlySet<string>): Diagnostic {\n const blocker = readsOf(reads, id).find((read) => unordered.has(read)) as string\n const [position] = readSpans(site.cel, `totals.${blocker}`)\n const message = reaches(id, id, reads, unordered)\n ? `aggregate ${quote(id)} reads its own total${blocker === id ? '' : `, through ${quote(blocker)}`}, so it would have to be computed before itself and never can be`\n : `aggregate ${quote(id)} reads ${quote(blocker)}, which reads its own total, so neither can be computed`\n return diagnostic('aggregate-cycle', message, { path: site.path, position })\n}\n","/**\n * Every expression in a report compiled where it stands: what the editor\n * diagnoses and what the runtime evaluates, from one function.\n *\n * The runtime compiles a report before it renders one. If it assembled its\n * own compile options, it could accept what the editor refuses -- `now()`,\n * a member nothing declares -- or bind a value as a type the editor did not\n * check it as. So both take this: the diagnostics are its errors, and the\n * runtime refuses a report that has any, evaluates the programs it gives,\n * binds each with `expressionValues`, and computes the aggregates in the\n * order it gives.\n */\nimport type { DeclaredType } from '@formancy/expressions'\nimport type { AggregateDef, ReportDefinition } from '@formancy/report-spec'\nimport { diagnostic } from '../diagnostics/codes.js'\nimport type { Diagnostic } from '../diagnostics/codes.js'\nimport { expressionSites } from '../diagnostics/parts.js'\nimport type { ExpressionSite } from '../diagnostics/parts.js'\nimport { quote } from '../outcome.js'\nimport { aggregateOrder, aggregateReads, cycleDiagnostic } from './aggregates.js'\nimport { compileSite } from './compile-site.js'\nimport type { CompiledExpression, Images, SiteOutcome } from './compile-site.js'\nimport { invoiceMembers, paidMember } from './e-invoice.js'\nimport { COMPUTES, fieldsOf, fieldTotalType, groupKeysOf, imagesOf, parametersOf, TOTALS } from './members.js'\nimport type { ExpressionMember, Members } from './members.js'\n\nexport interface ReportCompilation {\n /** What each name holds in this report: every member an expression can read, with the type it is checked and bound as. */\n readonly members: Members\n /** Every expression that compiled clean, by the JSON Pointer to its `cel`, in document order, the aggregates' last. */\n readonly expressions: ReadonlyMap<string, CompiledExpression>\n /** The aggregates in the order the runtime computes them: each after every aggregate its expression reads. One with no place in it is diagnosed. */\n readonly aggregateOrder: readonly string[]\n /** Every reason an expression cannot be evaluated, in document order, the aggregates' last: what the runtime refuses the report for. */\n readonly diagnostics: readonly Diagnostic[]\n}\n\n/** The CEL types a member can be declared as, of all the types an expression can give. */\nconst SCALARS: ReadonlySet<string> = new Set<DeclaredType>(['bool', 'int', 'double', 'decimal', 'string', 'timestamp', 'dyn'])\n\n/** Where an e-invoice's paid amount stands: `invoice.paid` is what it gives. */\nconst PAID = '/eInvoice/paid/cel'\n\n/**\n * Every expression in `report` -- a report the validator accepts --\n * compiled where it stands; or, with `only`, the expressions at those\n * pointers to their `cel` alone, with every aggregate's and the\n * e-invoice's paid amount, which what they read is computed from: what a\n * review compiles of a resolution that changes one field's type, the\n * expressions that change can reach (`fieldReaders`, 0048).\n */\nexport function compileReport(report: ReportDefinition, only?: ReadonlySet<string>): ReportCompilation {\n const sites = expressionSites(report)\n return compiledSites(report, only === undefined ? sites : sites.filter(({ path }) => only.has(path) || path.startsWith('/aggregates/') || path === PAID))\n}\n\n/** `compileReport` over sites already walked: `diagnose` walks the report once for this and for its warnings. */\nexport function compiledSites(report: ReportDefinition, sites: readonly ExpressionSite[]): ReportCompilation {\n const images: Images = { header: imagesOf(report.datasets.header), row: imagesOf(report.datasets.detail) }\n const byPath = new Map(sites.map((site) => [site.path, site]))\n const siteOf = (index: number): ExpressionSite => byPath.get(`/aggregates/${index}/of/expression/cel`) as ExpressionSite\n const reads = aggregateReads(report)\n const { order, unordered } = aggregateOrder(report, reads)\n const cyclic = new Set(unordered)\n const known = new Map<string, ExpressionMember>()\n const invoiced = report.eInvoice !== undefined\n // What is compiled before the e-invoice's totals are known -- an\n // aggregate's expression, the paid amount -- cannot read them, and finds\n // them empty. Neither stands in a group, whose keys are known from the\n // first.\n const base = {\n params: parametersOf(report),\n header: fieldsOf(report.datasets.header),\n row: fieldsOf(report.datasets.detail),\n groupKeys: groupKeysOf(report),\n ...invoiceMembers(undefined, undefined),\n }\n const outcomes = new Map<string, SiteOutcome>()\n\n /** What `aggregate` computes, its expression compiled against the totals before it; and why it cannot be computed, when it cannot. */\n const computed = (aggregate: AggregateDef, index: number): ExpressionMember => {\n if (aggregate.of?.kind !== 'expression') {\n return fieldTotalType(report, aggregate.fn, aggregate.of?.field.field)\n }\n const site = siteOf(index)\n const outcome = compileSite(site, { ...base, totals: known, table: known, group: known }, images, invoiced)\n outcomes.set(site.path, outcome)\n if (!outcome.ok) return COMPUTES[aggregate.fn](undefined)\n const result = outcome.compiled.program.resultType\n const takes = TOTALS[aggregate.fn]\n if (takes === 'any' || takes.has(result)) return COMPUTES[aggregate.fn](SCALARS.has(result) ? (result as DeclaredType) : undefined)\n const said = `aggregate ${quote(aggregate.id)} is a ${aggregate.fn} of what its expression gives, ${result}, and a ${aggregate.fn} takes ${[...takes].filter((type) => type !== 'dyn').join(', ')}`\n outcomes.set(site.path, { ok: false, diagnostics: [diagnostic('expression-aggregate-type', said, { path: site.path })] })\n return COMPUTES[aggregate.fn](undefined)\n }\n for (const id of order) {\n const index = report.aggregates.findIndex((aggregate) => aggregate.id === id)\n known.set(id, computed(report.aggregates[index] as AggregateDef, index))\n }\n // An aggregate that can never be computed has no value anyone could check\n // a read of; it is read as a value that may be anything, so that only the\n // circle is reported, once, where it closes.\n for (const id of unordered) known.set(id, { type: 'dyn', nullable: true })\n const totals = new Map(report.aggregates.map(({ id }) => [id, known.get(id) as ExpressionMember]))\n // A table's totals and a group's are the same aggregates over fewer\n // rows, of the same types (0062); a group's key is its table's, in\n // groupKeys, and report-spec keeps the key's name from every aggregate.\n // The paid amount reads none of the e-invoice's totals, and invoice.paid\n // is what it gives: it is compiled before the members that hold it, as\n // an aggregate's expression is, and that compilation is the one kept.\n const paid = byPath.get(PAID)\n const paidOutcome = paid === undefined ? undefined : compileSite(paid, { ...base, totals, table: totals, group: totals }, images, invoiced)\n if (paidOutcome !== undefined) outcomes.set(PAID, paidOutcome)\n const members: Members = {\n ...base,\n totals,\n table: totals,\n group: totals,\n ...invoiceMembers(report.eInvoice, paidOutcome === undefined ? undefined : paidMember(paidOutcome)),\n }\n\n const expressions = new Map<string, CompiledExpression>()\n const diagnostics: Diagnostic[] = []\n for (const site of sites) {\n const outcome = outcomes.get(site.path) ?? compileSite(site, members, images, invoiced)\n const aggregate = site.path.startsWith('/aggregates/') ? report.aggregates[Number(site.path.split('/')[2])]?.id : undefined\n if (aggregate !== undefined && cyclic.has(aggregate)) diagnostics.push(cycleDiagnostic(aggregate, site, reads, cyclic))\n else if (outcome.ok) expressions.set(site.path, outcome.compiled)\n if (!outcome.ok) diagnostics.push(...outcome.diagnostics)\n }\n return { members, expressions, aggregateOrder: order, diagnostics }\n}\n","/**\n * The values one evaluation reads: what the data holds, made into what each\n * member was compiled as. One function, so the type an expression was\n * checked as and the value it is handed cannot disagree.\n *\n * Exact values travel as strings with their type (0007; formancy.ai-data\n * 0008). `@formancy/expressions` converts a value itself only for a variable\n * declared at the top level and never null -- an int from a number, a\n * decimal from a string, a timestamp from a string with a zone -- and a\n * member that may be null is declared `dyn`, which it leaves as it is. So\n * every member is converted here, the same way whether it may be null or\n * not, and upstream finds each already of its type.\n */\nimport { Decimal, decimalFromString } from '@formancy/expressions'\nimport type { CompiledExpression, ExpressionRead } from './compile-site.js'\n\n/**\n * The data one evaluation reads, by name and member: `{ row: { amount:\n * '12.50' } }`. Each value as the format writes it -- an integer and a\n * decimal as their exact strings, an instant as an ISO 8601 date-time with\n * its zone, a date and a date-time as their ISO strings, a boolean, a\n * string, null where there is no value -- or already as the CEL value: a\n * bigint, upstream's `Decimal`, a `Date`.\n */\nexport type ExpressionValues = { readonly [name: string]: Readonly<Record<string, unknown>> | undefined }\n\n/** An ISO 8601 date-time with its zone: one without would be read in the host's zone, which a render on another machine does not share. */\nconst ZONED = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2})$/\n\nconst WHOLE = /^-?\\d+$/\n\n/** A refusal that names the member and its type, and never quotes the value: data is the customer's, and never reaches a message. */\nfunction notOf(read: ExpressionRead, what: string): TypeError {\n return new TypeError(`${read.name}.${read.member} is not ${what}`)\n}\n\nfunction asInt(read: ExpressionRead, raw: unknown): bigint {\n if (typeof raw === 'bigint') return raw\n if (typeof raw === 'number' && Number.isSafeInteger(raw)) return BigInt(raw)\n if (typeof raw === 'string' && WHOLE.test(raw)) return BigInt(raw)\n throw notOf(read, 'an integer, written as its exact digits')\n}\n\nfunction asDecimal(read: ExpressionRead, raw: unknown): Decimal {\n if (raw instanceof Decimal) return raw\n if (typeof raw === 'string') {\n try {\n return decimalFromString(raw)\n } catch {\n // Rethrown below without upstream's message, which quotes the value.\n }\n }\n throw notOf(read, 'a decimal, written as its exact digits')\n}\n\nfunction asInstant(read: ExpressionRead, raw: unknown): Date {\n const instant = raw instanceof Date ? raw : typeof raw === 'string' && ZONED.test(raw) ? new Date(raw) : undefined\n if (instant === undefined || Number.isNaN(instant.getTime())) throw notOf(read, 'an instant: an ISO 8601 date-time with its zone')\n return instant\n}\n\n/** The value `raw` is bound as, for `read`. */\nfunction bound(read: ExpressionRead, raw: unknown): unknown {\n if (raw === null && read.nullable) return null\n switch (read.type) {\n case 'int':\n return asInt(read, raw)\n case 'decimal':\n return asDecimal(read, raw)\n case 'timestamp':\n return asInstant(read, raw)\n case 'string':\n if (typeof raw === 'string') return raw\n throw notOf(read, 'a string')\n case 'bool':\n if (typeof raw === 'boolean') return raw\n throw notOf(read, 'a boolean')\n default:\n // An aggregate over an expression of a type the compiler could not\n // tell: what the runtime computed is handed over as it is.\n if (raw !== undefined && raw !== null) return raw\n throw notOf(read, 'a value')\n }\n}\n\n/**\n * The value bag `evaluate` takes for `expression`: each member it reads,\n * under the variable it was compiled with, made into the type it was\n * compiled as.\n *\n * Throws a TypeError for a value the data lacks, null where the member is\n * never null, or a value not of the member's type -- an amount as a\n * JavaScript number, an instant without its zone. The runtime validates a\n * dataset against its contract before any expression reads it, so each is\n * a defect, and is said as one: naming the member, never quoting the value.\n */\nexport function expressionValues(expression: CompiledExpression, values: ExpressionValues): Record<string, unknown> {\n return Object.fromEntries(expression.reads.map((read) => [read.variable, bound(read, values[read.name]?.[read.member])]))\n}\n","/**\n * Roundings the runtime would refuse, or apply twice.\n *\n * A total is rounded once, by its declared rule (0007). A format then shows\n * it, and rounds half away from zero to the places it shows. Where it shows\n * fewer places than the rounding keeps, the total is rounded a second time,\n * by a rule nobody declared: summed and rounded half-even to three places,\n * 1.2449 is 1.245, and shown at two places that is 1.25, where rounding the\n * total once to two places gives 1.24 in either mode. So such a format is an\n * error, and the author declares the rounding at the places printed.\n *\n * A rounding on an aggregate that computes an integer, a date, a text or\n * an instant has no places to round, and the runtime refuses it; it is an\n * error here too, so the editor says so before a render does. One whose\n * type the compiler cannot tell (`dyn`) is rounded as a decimal, as the\n * runtime does.\n */\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport type { ExpressionMember } from '../expressions/members.js'\nimport { quote } from '../outcome.js'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic } from './codes.js'\nimport type { PrintedTotal } from './parts.js'\n\n/** The types a rounding has places in. */\nconst ROUNDED = new Set(['decimal', 'dyn'])\n\n/** What a total of `type` is, said, where a rounding has no places in it; undefined where it has, or where the type is not known. A chart's series is held to it too (`chart.ts`). */\nexport function unrounded(type: string | undefined): string | undefined {\n if (type === undefined || ROUNDED.has(type)) return undefined\n return type === 'int' ? 'an integer' : type === 'timestamp' ? 'an instant' : 'a date or a text'\n}\n\nexport function roundingDiagnostics(report: ReportDefinition, printed: readonly PrintedTotal[], totals: ReadonlyMap<string, ExpressionMember>): Diagnostic[] {\n const found: Diagnostic[] = []\n for (const [index, aggregate] of report.aggregates.entries()) {\n const what = unrounded(totals.get(aggregate.id)?.type)\n if (aggregate.rounding === undefined || what === undefined) continue\n found.push(\n diagnostic('rounding-not-decimal', `aggregate ${quote(aggregate.id)} declares a rounding, and computes ${what}, which has no places to round`, {\n path: `/aggregates/${index}/rounding`,\n }),\n )\n }\n for (const total of printed) {\n const kept = report.aggregates.find(({ id }) => id === total.aggregate)?.rounding?.scale\n if (kept === undefined || total.scale >= kept) continue\n const said = `aggregate ${quote(total.aggregate)} is rounded to ${kept} places as it declares, and printed at ${total.scale}, which rounds it again by another rule; declare its rounding at ${total.scale} places`\n found.push(diagnostic('format-rounds-again', said, { path: total.path, componentId: total.componentId, columnId: total.columnId }))\n }\n return found\n}\n","/**\n * A chart's series rounded where it has no places, or rounded twice. A\n * series declares its rounding as an aggregate does, and is held to the\n * same two rules (`rounding.ts` says why, for an aggregate): a count, and a\n * sum, a least or a greatest of integers, is an integer, which has no\n * places to round, and the runtime refuses its rounding; and the chart's\n * value format shows a rounded total rounding half away from zero to the\n * places it shows, so where those are fewer than the rounding keeps, the\n * number is rounded again by a rule nobody declared. What a series computes\n * is typed as an aggregate over the same field is, by `seriesType`, which\n * the runtime asks too. An integer is never rounded, so one refusal says it\n * and the format's places are not judged against a rounding that never happens.\n */\nimport { walkComponents } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { seriesType } from '../expressions/members.js'\nimport { quote } from '../outcome.js'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic } from './codes.js'\nimport { unrounded } from './rounding.js'\n\nexport function chartDiagnostics(report: ReportDefinition): Diagnostic[] {\n const found: Diagnostic[] = []\n for (const { component, path } of walkComponents(report)) {\n if (component.kind !== 'chart') continue\n const printed = component.valueFormat.scale\n for (const [index, series] of component.series.entries()) {\n if (series.rounding === undefined) continue\n const named = `series ${quote(series.id)} of chart ${quote(component.id)}`\n const what = unrounded(seriesType(report, series).type)\n if (what !== undefined) {\n const said = `${named} declares a rounding, and computes ${what}, which has no places to round`\n found.push(diagnostic('rounding-not-decimal', said, { path: `${path}/series/${index}/rounding`, componentId: component.id }))\n continue\n }\n const kept = series.rounding.scale\n if (printed >= kept) continue\n const said = `${named} is rounded to ${kept} places as it declares, and printed at ${printed}, which rounds it again by another rule; print it at ${kept} places or declare its rounding at ${printed}`\n found.push(diagnostic('format-rounds-again', said, { path: `${path}/valueFormat`, componentId: component.id }))\n }\n }\n return found\n}\n","/**\n * Content that prints nothing: a body with no components, a text with no\n * runs or only blank literal ones.\n *\n * Only what the document alone decides. Whether a keep-together block is\n * taller than a page, whether a fixed width fits its column, whether a\n * table's rows overflow: each depends on measured text and the data, and is\n * the layout's to report with the renderer, not this package's to guess.\n * A table without a detail dataset is no diagnostic either: the validator\n * refuses it (`unknown-dataset`), so a session never holds one.\n */\nimport { walkComponents } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { quote } from '../outcome.js'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic } from './codes.js'\n\nexport function contentDiagnostics(report: ReportDefinition): Diagnostic[] {\n const found: Diagnostic[] = []\n if (report.regions.body.length === 0) {\n found.push(diagnostic('empty-body', 'the body holds nothing, so the report prints only its headers, footers and summary', { path: '/regions/body' }))\n }\n for (const { component, path } of walkComponents(report)) {\n if (component.kind !== 'text') continue\n if (component.content.every((inline) => inline.kind === 'text' && inline.text.trim() === '')) {\n found.push(diagnostic('empty-text', `text ${quote(component.id)} prints nothing`, { path: `${path}/content`, componentId: component.id }))\n }\n }\n return found\n}\n","/**\n * What an e-invoice asks of the page that prints it: every total its XML\n * holds printed, and printed as the XML holds it.\n *\n * The runtime computes each total once, for the page and the XML (0027),\n * so where both show one they show the same value. What nothing there can\n * make agree is a total the page never shows, or one it shows otherwise:\n * the picture would be another invoice than the one it carries, which\n * § 14c UStG may count as a second.\n *\n * - **`e-invoice-total-unprinted`.** Each total the XML always holds -- the\n * total without VAT (BT-109, or the sum of the lines, BT-106, which\n * equals it with no allowances or charges), the VAT total (BT-110), the\n * total with VAT (BT-112), and the basis and the amount of each declared\n * category (BT-116, BT-117) -- is an error when no run of a text or of a\n * table reads it; so are the paid amount (BT-113) and the amount due\n * (BT-115), where a paid amount is declared.\n * - **`e-invoice-format-differs`.** A run that reads a total prints it at\n * two places at least, in the e-invoice's currency named as a code, or\n * as a plain number; so does the column of a line's net amount (BT-131),\n * and the net price's (BT-146) prints in that currency. A line's name\n * (BT-153) is printed in the case the data gives it. A quantity's and a\n * price's places are the data's, and the runtime holds them row by row.\n *\n * It is the template's, not the data's: a run behind a condition counts as\n * printing what it reads, and which categories the lines use is known\n * only at render, so every declared one is held. It sees that a total is\n * read by what prints, not what is printed beside it, nor whether it\n * prints the total at all rather than something computed from it. What\n * shows a person no text -- a condition, a style rule, a QR code, a\n * payment code's amount -- prints nothing.\n */\nimport { parse, referencedPaths } from '@formancy/expressions'\nimport { E_INVOICE_LINE_COLUMNS, E_INVOICE_NAMES, INVOICE_TOTALS, VAT_BREAKDOWN, walkComponents } from '@formancy/report-spec'\nimport type { ComponentKind, EInvoice, Format, ReportDefinition, TableComponent } from '@formancy/report-spec'\nimport { pathParts } from '../expressions/compile-site.js'\nimport { quote } from '../outcome.js'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic } from './codes.js'\nimport type { ExpressionSite } from './parts.js'\n\n/** The components whose runs print as text. */\nconst PRINTS: ReadonlySet<ComponentKind> = new Set(['text', 'table'])\n\n/** A total the XML holds: what it is, where the e-invoice declares it, and the reads that print it. */\ninterface Printable {\n readonly what: string\n readonly path: string\n readonly reads: readonly string[]\n}\n\n/** A run of a text or a table, and every `name.member` it reads, once each. */\ninterface PrintingRun {\n readonly site: ExpressionSite\n readonly reads: readonly string[]\n}\n\n/** Every run of a text or a table that parses, with what it reads. */\nfunction printingRuns(report: ReportDefinition, sites: readonly ExpressionSite[]): readonly PrintingRun[] {\n const kinds = new Map(walkComponents(report).map(({ component }) => [component.id, component.kind]))\n return sites.flatMap((site): PrintingRun[] => {\n const kind = site.componentId === undefined ? undefined : kinds.get(site.componentId)\n if (site.kind !== 'computed' || kind === undefined || !PRINTS.has(kind)) return []\n const parsed = parse(site.cel)\n // One that does not parse has its own diagnostic, and reads nothing it can be credited with.\n if (!parsed.ok) return []\n const reads = referencedPaths(parsed.ast)\n .map(pathParts)\n .flatMap(({ name, member }) => (member === undefined ? [] : [`${name}.${member}`]))\n return [{ site, reads: [...new Set(reads)] }]\n })\n}\n\n/** Every e-invoice total no run of the page prints, one diagnostic each, at what it is a total of. */\nfunction unprintedTotals(invoice: EInvoice, runs: readonly PrintingRun[]): Diagnostic[] {\n const totals: Printable[] = [\n { what: INVOICE_TOTALS.taxBasisTotal, path: '/eInvoice', reads: ['invoice.taxBasisTotal', 'invoice.lineTotal'] },\n { what: INVOICE_TOTALS.taxTotal, path: '/eInvoice', reads: ['invoice.taxTotal'] },\n { what: INVOICE_TOTALS.grandTotal, path: '/eInvoice', reads: ['invoice.grandTotal'] },\n ...(invoice.paid === undefined\n ? []\n : [\n { what: INVOICE_TOTALS.paid, path: '/eInvoice', reads: ['invoice.paid'] },\n { what: INVOICE_TOTALS.duePayable, path: '/eInvoice', reads: ['invoice.duePayable'] },\n ]),\n ...invoice.vat.flatMap(({ id }, index) =>\n (['vatBasis', 'vatAmount'] as const).map((name) => ({\n what: `${VAT_BREAKDOWN[name]} of the category ${quote(id)}`,\n path: `/eInvoice/vat/${index}`,\n reads: [`${name}.${id}`],\n })),\n ),\n ]\n const printed = new Set(runs.flatMap(({ reads }) => reads))\n return totals\n .filter(({ reads }) => !reads.some((read) => printed.has(read)))\n .map(({ what, path, reads }) =>\n diagnostic(\n 'e-invoice-total-unprinted',\n `${what} is in the e-invoice's XML, and no text or table of the page prints it: print it as ${reads.join(' or ')}, so the page shows the invoice it carries`,\n { path },\n ),\n )\n}\n\n/** What a format that shows an amount at fewer places than the XML's two says, `by` naming what prints it; undefined where it shows them all. */\nfunction placesBreak(format: Format | undefined, by: string): string | undefined {\n if ((format?.kind !== 'number' && format?.kind !== 'currency') || format.scale >= 2) return undefined\n return `is an amount the XML holds to the cent, and ${by} prints it at ${format.scale} places, rounding it again: print it at two places or more`\n}\n\n/** What a currency format that names another currency than the e-invoice's says, `by` naming what prints it; undefined where it names that one, or none. */\nfunction currencyBreak(format: Format | undefined, currency: string, by: string): string | undefined {\n if (format?.kind !== 'currency') return undefined\n const source = format.currency\n if (source.kind === 'code' && source.code === currency) return undefined\n const shown = source.kind === 'code' ? source.code : `the currency a ${source.kind} gives`\n return `is an amount in the e-invoice's currency, ${currency} (BT-5), and ${by} prints it in ${shown}: name ${currency} as its currency`\n}\n\n/** The format a column's value is printed with, if any. */\nconst formatOf = (value: TableComponent['columns'][number]['value']): Format | undefined => ('format' in value ? value.format : undefined)\n\n/** Every run that prints a total otherwise than the XML holds it, and every column of a line that does: one diagnostic each, at the format. */\nfunction formatsThatDiffer(report: ReportDefinition, invoice: EInvoice, runs: readonly PrintingRun[]): Diagnostic[] {\n const found: Diagnostic[] = []\n for (const { site, reads } of runs) {\n const total = reads.find((read) => (E_INVOICE_NAMES as readonly string[]).includes(read.split('.')[0] as string))\n if (total === undefined) continue\n const broken = placesBreak(site.format, 'this run') ?? currencyBreak(site.format, invoice.currency, 'this run')\n if (broken !== undefined)\n found.push(\n diagnostic('e-invoice-format-differs', `${total} ${broken}`, {\n path: site.path.replace(/\\/expression\\/cel$/, '/format'),\n componentId: site.componentId,\n columnId: site.columnId,\n }),\n )\n }\n // report-spec's validator holds the lines to this table, and each named column to it.\n const located = walkComponents(report).find(({ component }) => component.kind === 'table' && component.id === invoice.lines.table)\n if (located === undefined) return found\n const table = located.component as TableComponent\n const columnBreaks = {\n name: (format: Format | undefined) =>\n format?.kind === 'text' && format.transform !== undefined\n ? `is written into the XML as the data gives it, and its column prints it in ${format.transform} case: print it without a transform`\n : undefined,\n netAmount: (format: Format | undefined) => placesBreak(format, 'its column') ?? currencyBreak(format, invoice.currency, 'its column'),\n netPrice: (format: Format | undefined) => currencyBreak(format, invoice.currency, 'its column'),\n } as const\n for (const [key, broken] of Object.entries(columnBreaks) as [keyof typeof columnBreaks, (format: Format | undefined) => string | undefined][]) {\n const index = table.columns.findIndex(({ id }) => id === invoice.lines[key])\n const column = table.columns[index]\n const said = column === undefined ? undefined : broken(formatOf(column.value))\n if (column !== undefined && said !== undefined) {\n found.push(\n diagnostic('e-invoice-format-differs', `${E_INVOICE_LINE_COLUMNS[key].what} ${said}`, {\n path: `${located.path}/columns/${index}/value/format`,\n componentId: table.id,\n columnId: column.id,\n }),\n )\n }\n }\n return found\n}\n\n/** What the page of an e-invoice report fails to print as the XML holds it: the totals it does not print, then the formats that print otherwise. */\nexport function eInvoiceDiagnostics(report: ReportDefinition, sites: readonly ExpressionSite[]): Diagnostic[] {\n const invoice = report.eInvoice\n if (invoice === undefined) return []\n const runs = printingRuns(report, sites)\n return [...unprintedTotals(invoice, runs), ...formatsThatDiffer(report, invoice, runs)]\n}\n","/**\n * A payment part that holds SIX's examples: what a bill a builder adds\n * starts from, and what the starters print, since no creditor's account\n * may stand in a sample\n * ([0039](../../../../docs/decisions/0039-a-person-selects-a-reports-qr-bill-and-edits-it-field-by-field-in-either-builder.md)).\n *\n * The account is any of SIX's example accounts; the creditor, the debtor\n * and the reference are the ones a builder puts in, report-spec's\n * `QR_BILL_EXAMPLE`, so that a bill edited in a builder is warned of while\n * anything it was given is left. Only what is written in the report: a\n * text read from the data is not known until the render, which holds it to\n * SIX's rules and nothing more. The account and the reference are read by\n * report-spec's checks, which drop the spaces written for reading, so each\n * is compared as the code holds it; a party is the example's when it has\n * the example's parts and no other, each written as the example writes it,\n * the blanks around it aside, as SIX never sends them.\n *\n * One warning for the bill, naming each term that is an example, so that a\n * bill added from nothing is one problem to follow, not one per term.\n */\nimport { checkQrBillAccount, checkQrBillReference, QR_BILL_EXAMPLE, QR_BILL_EXAMPLE_ACCOUNTS } from '@formancy/report-spec'\nimport type { Inline, PaymentPart, QrBillAddress, ReportDefinition } from '@formancy/report-spec'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic } from './codes.js'\n\nconst ACCOUNTS: ReadonlySet<string> = new Set(QR_BILL_EXAMPLE_ACCOUNTS)\n\n/** The text `runs` write when every run is literal, what no data can change; undefined otherwise, or for no runs at all. */\nfunction written(runs: readonly Inline[] | undefined): string | undefined {\n return runs?.every((run) => run.kind === 'text') === true ? runs.map((run) => run.text).join('') : undefined\n}\n\n/** `text` as the code holds a reference, or undefined where it is none. */\nfunction referenceOf(text: string | undefined): string | undefined {\n const checked = text === undefined ? undefined : checkQrBillReference(text)\n return checked?.ok === true ? checked.value.reference : undefined\n}\n\nconst EXAMPLE_REFERENCE = referenceOf(QR_BILL_EXAMPLE.reference)\n\n/** Whether `address` is `example`: the same parts, each written as the example writes it. */\nfunction isExample(address: QrBillAddress | undefined, example: { readonly [P in keyof QrBillAddress]?: string }): boolean {\n if (address === undefined) return false\n const parts = new Set([...Object.keys(address), ...Object.keys(example)] as (keyof QrBillAddress)[])\n return [...parts].every((part) => written(address[part])?.trim() === example[part])\n}\n\n/** Each term a bill may hold an example of, in the order the code holds them, and whether it does. */\nconst TERMS: readonly (readonly [term: string, held: (bill: PaymentPart) => boolean])[] = [\n [\n 'account',\n (bill) => {\n const text = written(bill.account)\n const checked = text === undefined ? undefined : checkQrBillAccount(text)\n return checked?.ok === true && ACCOUNTS.has(checked.value.iban)\n },\n ],\n ['creditor', (bill) => isExample(bill.creditor, QR_BILL_EXAMPLE.creditor)],\n ['debtor', (bill) => isExample(bill.debtor, QR_BILL_EXAMPLE.debtor)],\n ['reference', (bill) => referenceOf(written(bill.reference)) === EXAMPLE_REFERENCE],\n]\n\n/** \"account\", \"account and creditor\", \"account, creditor and debtor\". */\nconst listed = (terms: readonly string[]): string => (terms.length < 2 ? terms.join('') : `${terms.slice(0, -1).join(', ')} and ${terms.at(-1) as string}`)\n\nexport function examplePaymentPartDiagnostics(report: ReportDefinition): Diagnostic[] {\n const bill = report.paymentPart\n if (bill === undefined) return []\n const held = TERMS.filter(([, holds]) => holds(bill)).map(([term]) => term)\n if (held.length === 0) return []\n const one = held.length === 1\n const message = `the payment part's ${listed(held)} ${one ? \"is SIX's example\" : \"are SIX's examples\"} (IG 2.4, Annex A), no one's: replace ${one ? 'it' : 'them'} before the bill is sent`\n return [diagnostic('example-payment-part', message, { path: '/paymentPart' })]\n}\n","/**\n * A total of every row printed under a table that prints some of them\n * (0062). A table with a condition prints the rows it selects, and its\n * total rows read `table`, the totals of those rows; `totals` is still\n * every detail row's. A total row that prints an aggregate over the\n * report, or an expression that reads `totals` and not `table`, prints a\n * number of rows the table does not show, under them, where it reads as\n * theirs. It renders as written: a grand total under a part of the rows,\n * labelled as one, is a line an author may mean, so it is a warning.\n *\n * Only the table's total rows are said. A group's header and footer print\n * a group's share of every row more often than by mistake, and an\n * expression that reads both names compares the table's rows with every\n * row on purpose. What an expression reads is asked of the parser, as the\n * compiler asks it (`reads.ts`).\n */\nimport { walkComponents } from '@formancy/report-spec'\nimport type { Inline, ReportDefinition } from '@formancy/report-spec'\nimport { expressionReads } from '../expressions/reads.js'\nimport { quote } from '../outcome.js'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic } from './codes.js'\n\n/** What a total row's cell prints of every row, said after \"this\", and where; undefined for one that prints none. */\nfunction everyRow(value: Inline, path: string): { readonly what: string; readonly path: string } | undefined {\n if (value.kind === 'aggregate' && value.over === 'report') {\n return { what: `prints ${quote(value.aggregate)} over every detail row; over \"table\", it is the total of the rows the table prints`, path: `${path}/over` }\n }\n if (value.kind !== 'expression') return undefined\n const reads = expressionReads([value.expression.cel])\n if (!reads.has('totals') || reads.has('table')) return undefined\n return { what: \"reads totals, which are every detail row's; table.<id> is the total of the rows the table prints\", path: `${path}/expression/cel` }\n}\n\nexport function tableDiagnostics(report: ReportDefinition): Diagnostic[] {\n const found: Diagnostic[] = []\n for (const { component, path } of walkComponents(report)) {\n if (component.kind !== 'table' || component.rowsWhen === undefined) continue\n for (const [row, { cells }] of (component.totals ?? []).entries()) {\n for (const [index, cell] of cells.entries()) {\n const said = everyRow(cell.value, `${path}/totals/${row}/cells/${index}/value`)\n if (said === undefined) continue\n const message = `the table ${quote(component.id)} prints only the rows its condition selects, and this ${said.what}`\n found.push(diagnostic('total-of-every-row', message, { path: said.path, componentId: component.id }))\n }\n }\n }\n return found\n}\n","/**\n * Declarations nothing uses: a style no component names, an asset no image\n * draws, a parameter, field or aggregate nothing prints, orders by, totals\n * or reads. Each renders as written; each is probably a leftover, and a\n * parameter or a field costs something at every render -- a question on\n * the parameter form, a column the provider fetches.\n *\n * What an expression reads counts: its paths are asked of the parser, as\n * the compiler asks them (`reads.ts`). An expression that does not parse\n * reads nothing it can be credited with; its own diagnostic says why.\n */\nimport { FONT_FACE_KEYS, isFontMediaType } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { AGGREGATE_NAMES, expressionReads, READ_AS, readsMember as read } from '../expressions/reads.js'\nimport { quote } from '../outcome.js'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic, DiagnosticCode } from './codes.js'\nimport type { ReportParts } from './parts.js'\n\nexport function unusedDiagnostics(report: ReportDefinition, parts: ReportParts): Diagnostic[] {\n const reads = expressionReads(parts.expressions.map(({ cel }) => cel))\n const found: Diagnostic[] = []\n const check = (\n declared: readonly { readonly id: string }[],\n used: (id: string) => boolean,\n code: DiagnosticCode,\n list: string,\n message: (id: string) => string,\n ): void => {\n for (const [index, { id }] of declared.entries()) if (!used(id)) found.push(diagnostic(code, message(quote(id)), { path: `${list}/${index}` }))\n }\n const styles = new Set(parts.styles)\n const assets = new Set(parts.assets)\n const parameters = new Set(parts.parameters)\n const aggregates = new Set(parts.aggregates)\n // A font asset is used when a font token maps one of its faces to it, where an image asset is used when an image draws it (0043).\n const mappedFaces = new Set<string>()\n for (const faces of Object.values(report.fonts ?? {})) for (const key of FONT_FACE_KEYS) if (faces[key] !== undefined) mappedFaces.add(faces[key])\n check(\n report.styles,\n (id) => styles.has(id),\n 'unused-style',\n '/styles',\n (id) => `style ${id} is used by no component, column or row`,\n )\n report.assets.forEach((asset, index) => {\n const font = isFontMediaType(asset.mediaType)\n if (font ? mappedFaces.has(asset.id) : assets.has(asset.id)) return\n found.push(\n diagnostic('unused-asset', font ? `font ${quote(asset.id)} is mapped to no font token` : `asset ${quote(asset.id)} is drawn by no image`, {\n path: `/assets/${index}`,\n }),\n )\n })\n check(\n report.parameters,\n (id) => parameters.has(id) || read(reads, ['params'], id),\n 'unused-parameter',\n '/parameters',\n (id) => `parameter ${id} is neither printed nor read, and the person rendering would be asked for it for nothing`,\n )\n for (const role of ['header', 'detail'] as const) {\n const fields = new Set(parts.fields.filter(({ dataset }) => dataset === role).map(({ field }) => field))\n check(\n report.datasets[role]?.fields ?? [],\n (id) => fields.has(id) || read(reads, [READ_AS[role]], id),\n 'unused-field',\n `/datasets/${role}/fields`,\n (id) => `field ${id} of the ${role} dataset is neither printed, drawn, ordered by, totalled nor read, and would be fetched for nothing`,\n )\n }\n check(\n report.aggregates,\n (id) => aggregates.has(id) || read(reads, AGGREGATE_NAMES, id),\n 'unused-aggregate',\n '/aggregates',\n (id) => `aggregate ${id} is neither printed nor read, and would be computed over every row for nothing`,\n )\n return found\n}\n","/**\n * What the diagnostics say of a report in one language: the errors the\n * runtime would refuse it for, and the warnings an author probably wants\n * to see, with the walk and the compilation they were found by, which the\n * diagnostics of each of its translations read again (`words.ts`).\n */\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { compiledSites } from '../expressions/compile-report.js'\nimport type { ReportCompilation } from '../expressions/compile-report.js'\nimport { chartDiagnostics } from './chart.js'\nimport type { Diagnostic } from './codes.js'\nimport { contentDiagnostics } from './content.js'\nimport { eInvoiceDiagnostics } from './e-invoice.js'\nimport { examplePaymentPartDiagnostics } from './example-payment-part.js'\nimport { reportParts } from './parts.js'\nimport type { ReportParts } from './parts.js'\nimport { roundingDiagnostics } from './rounding.js'\nimport { tableDiagnostics } from './tables.js'\nimport { unusedDiagnostics } from './unused.js'\n\n/** A report's diagnostics in the language its words are written in, and what found them. */\nexport interface Diagnosis {\n readonly diagnostics: readonly Diagnostic[]\n readonly parts: ReportParts\n readonly compiled: ReportCompilation\n}\n\n/**\n * Every diagnostic for `report` as its words are written, its translations\n * unread: expressions first, in document order, the aggregates' last, then\n * roundings, then a chart's series' roundings, then a total of every row\n * under a table that selects its rows, then the e-invoice's unprinted\n * totals, then content, then a bill that holds SIX's examples,\n * then unused declarations in the order they are declared. The\n * expressions' are `compileReport`'s, so the editor reports exactly what\n * the runtime refuses.\n */\nexport function diagnosis(report: ReportDefinition): Diagnosis {\n const parts = reportParts(report)\n const compiled = compiledSites(report, parts.expressions)\n const diagnostics = [\n ...compiled.diagnostics,\n ...roundingDiagnostics(report, parts.printedTotals, compiled.members.totals),\n ...chartDiagnostics(report),\n ...tableDiagnostics(report),\n ...eInvoiceDiagnostics(report, parts.expressions),\n ...contentDiagnostics(report),\n ...examplePaymentPartDiagnostics(report),\n ...unusedDiagnostics(report, parts),\n ]\n return { diagnostics, parts, compiled }\n}\n","/**\n * What the diagnostics say of a report in a language its translations\n * declare (0063), each diagnostic naming that language.\n *\n * - **`word-missing`.** Each word the language does not translate, and\n * each expression that prints words it does not, once, at the first\n * place it stands. An expression run where a word stands prints words\n * where it gives text -- a string, or a value the compiler cannot tell,\n * which may be one -- its run prints it as text, and its source holds a\n * quote: CEL writes every string literal between quotes, so the test\n * can call too many expressions words and never too few, without a\n * parser of its own.\n * - **`translation-differs`.** A translated expression that would print\n * another thing than its source: another type, a member read that its\n * source does not read or one it does not read that its source does, or\n * a translation of an expression that prints no words -- a number is no\n * language's.\n * - **Every diagnostic the report written in the language gives that its\n * own does not**, through the same `diagnosis`: so a translation is held\n * to every rule the report is, by the compilation that holds the\n * report's own -- an expression's errors at each place its source\n * stands, an e-invoice's total its page prints -- and what is decided\n * once is not decided again here.\n * - **`unused-translation`.** A translation of a word, or of an\n * expression, the report no longer prints: a warning, and never printed.\n *\n * A word missing leaves the report valid, so that a session, a builder and\n * a server can hold a report being translated; it is never printed in\n * another language, and the runtime refuses a render in a language whose\n * errors are not all answered.\n */\nimport { reportWords, wordExpressionSites, writtenIn } from '@formancy/report-spec'\nimport type { ReportDefinition, Translation, WordExpressionSite } from '@formancy/report-spec'\nimport type { CompiledExpression } from '../expressions/compile-site.js'\nimport { quote } from '../outcome.js'\nimport { diagnostic } from './codes.js'\nimport type { Diagnostic, Where } from './codes.js'\nimport { diagnosis } from './diagnosis.js'\nimport type { Diagnosis } from './diagnosis.js'\n\n/** The types an expression gives that may print as text: a string, or a value the compiler cannot tell. */\nconst TEXT: ReadonlySet<string> = new Set(['string', 'dyn'])\n\n/** A quote of either kind CEL writes a string literal between. */\nconst QUOTE = /[\"']/\n\n/** What an expression run where a word stands prints, as its own language's compilation tells: words, a value that is none, or what an error keeps from being known. */\ntype Verdict =\n { readonly kind: 'words'; readonly compiled: CompiledExpression } | { readonly kind: 'value'; readonly type: string } | { readonly kind: 'unknown' }\n\nfunction verdict(site: WordExpressionSite, own: Diagnosis): Verdict {\n const compiled = own.compiled.expressions.get(site.path)\n // A source the compiler refuses has its own error, which refuses every render.\n if (compiled === undefined) return { kind: 'unknown' }\n const type = compiled.program.resultType\n const format = compiled.site.format?.kind\n if (TEXT.has(type) && (format === undefined || format === 'text') && QUOTE.test(site.cel)) return { kind: 'words', compiled }\n return { kind: 'value', type: format === undefined || format === 'text' ? type : `${type}, printed as a ${format}` }\n}\n\n/** Every member an expression reads, as `name.member`, sorted. */\nfunction readsOf(compiled: CompiledExpression): readonly string[] {\n return compiled.reads.map(({ name, member }) => `${name}.${member}`).sort()\n}\n\n/** A diagnostic's identity, to tell one the written report gives from one the report's own gives. */\nconst keyOf = ({ code, path, message, position }: Diagnostic): string => `${code} ${path} ${message} ${position?.start ?? ''} ${position?.end ?? ''}`\n\n/** Where a diagnostic about a site points, in `language`, at `path`. */\nconst atSite = (site: WordExpressionSite, path: string, language: string): Where => ({\n path,\n componentId: site.componentId,\n columnId: site.columnId,\n language,\n})\n\n/** The diagnostics of the translated expression at `entry`, standing at `sites`: one that prints no words, or one whose translation would print another thing. */\nfunction expressionDifferences(sites: readonly WordExpressionSite[], entry: string, own: Diagnosis, written: Diagnosis, language: string): Diagnostic[] {\n return sites.flatMap((site): Diagnostic[] => {\n const said = verdict(site, own)\n if (said.kind === 'unknown') return []\n if (said.kind === 'value') {\n const message = `this expression prints ${said.type}, not words, and only an expression that prints words is translated: in ${language} it would print another value than in the report's own language`\n return [diagnostic('translation-differs', message, atSite(site, entry, language))]\n }\n const translation = written.compiled.expressions.get(site.path)\n // A translation the compiler refuses has the compiler's errors, given with the written report's.\n if (translation === undefined) return []\n const [source, theirs] = [said.compiled.program.resultType, translation.program.resultType]\n if (source !== theirs) {\n const message = `the translation in ${language} gives ${theirs}, and the expression it translates gives ${source}: a translation prints what its expression prints, in other words`\n return [diagnostic('translation-differs', message, atSite(site, entry, language))]\n }\n const [reads, translated] = [readsOf(said.compiled), readsOf(translation)]\n if (reads.join(' ') === translated.join(' ')) return []\n const message = `the translation in ${language} reads ${translated.join(', ') || 'nothing'}, and the expression it translates reads ${reads.join(', ') || 'nothing'}: a translation reads exactly what its expression reads, so that what reads a field is the expression's alone`\n return [diagnostic('translation-differs', message, atSite(site, entry, language))]\n })\n}\n\n/** Each word, and each expression that prints words, that `translation` does not translate: once, at the first place it stands. */\nfunction missing(report: ReportDefinition, translation: Translation, sites: readonly WordExpressionSite[], own: Diagnosis): Diagnostic[] {\n const language = translation.locale\n const words = new Set(translation.words.map(({ word }) => word))\n const expressions = new Set(translation.expressions.map(({ cel }) => cel))\n const said = new Set<string>()\n const refused = `a render in ${language} is refused until it has one, and never prints it in another language`\n const literal = reportWords(report).flatMap((place): Diagnostic[] => {\n if (words.has(place.text) || said.has(place.text)) return []\n said.add(place.text)\n return [diagnostic('word-missing', `${quote(place.text)} has no translation in ${language}: ${refused}`, { ...place, language })]\n })\n const computed = sites.flatMap((site): Diagnostic[] => {\n if (expressions.has(site.cel) || said.has(site.cel) || verdict(site, own).kind !== 'words') return []\n said.add(site.cel)\n return [diagnostic('word-missing', `this expression prints words, and has no translation in ${language}: ${refused}`, atSite(site, site.path, language))]\n })\n return [...literal, ...computed]\n}\n\n/**\n * The diagnostics of `report` in `locale`, a language its translations\n * declare, `own` its diagnosis in its own: none for its own language, or\n * one it does not declare.\n */\nexport function inLanguage(report: ReportDefinition, locale: string, own: Diagnosis): Diagnostic[] {\n const index = (report.translations ?? []).findIndex((translation) => translation.locale === locale)\n const translation = report.translations?.[index]\n if (translation === undefined) return []\n const base = `/translations/${index}`\n const sites = wordExpressionSites(report)\n const written = diagnosis(writtenIn(report, locale))\n const entries = new Map(translation.expressions.map(({ cel }, entry) => [cel, `${base}/expressions/${entry}/expression/cel`]))\n // Where a translated expression stands, the written report's diagnostic is the translation's, and points at it.\n const translatedAt = new Map(sites.flatMap((site) => (entries.has(site.cel) ? [[site.path, entries.get(site.cel) as string] as const] : [])))\n const differences = translation.expressions.flatMap(({ cel }, entry) =>\n expressionDifferences(\n sites.filter((site) => site.cel === cel),\n `${base}/expressions/${entry}/expression/cel`,\n own,\n written,\n locale,\n ),\n )\n const ownKeys = new Set(own.diagnostics.map(keyOf))\n const added = written.diagnostics\n .filter((found) => !ownKeys.has(keyOf(found)))\n .map((found): Diagnostic => ({ ...found, path: translatedAt.get(found.path) ?? found.path, message: `in ${locale}, ${found.message}`, language: locale }))\n const printed = new Set(reportWords(report).map(({ text }) => text))\n const placed = new Set(sites.map(({ cel }) => cel))\n const unused = [\n ...translation.words.flatMap(({ word }, entry) =>\n printed.has(word)\n ? []\n : [\n diagnostic('unused-translation', `the report prints no ${quote(word)} to translate: this translation is kept for nothing`, {\n path: `${base}/words/${entry}`,\n language: locale,\n }),\n ],\n ),\n ...translation.expressions.flatMap(({ cel }, entry) =>\n placed.has(cel)\n ? []\n : [\n diagnostic('unused-translation', 'the report prints this expression nowhere a word stands: this translation is kept for nothing', {\n path: `${base}/expressions/${entry}`,\n language: locale,\n }),\n ],\n ),\n ]\n return [...missing(report, translation, sites, own), ...differences, ...added, ...unused]\n}\n\n/**\n * Every expression run of `report` -- a report the validator accepts --\n * where a word stands that prints words, in document order: what a\n * language translates, as `word-missing` says of each, and what the\n * builders mark and edit as a word (0063). The one verdict the diagnostics\n * give, so that the two never disagree.\n */\nexport function wordExpressions(report: ReportDefinition): readonly WordExpressionSite[] {\n const own = diagnosis(report)\n return wordExpressionSites(report).filter((site) => verdict(site, own).kind === 'words')\n}\n\n/**\n * Every diagnostic of `report` -- a report the validator accepts -- in\n * `locale`, a language its translations declare, each naming it: what a\n * render in that language is refused for, beside the report's own errors,\n * which refuse every render. None for the report's own language, whose\n * are `diagnose`'s, or for one it does not declare.\n */\nexport function languageDiagnostics(report: ReportDefinition, locale: string): Diagnostic[] {\n return inLanguage(report, locale, diagnosis(report))\n}\n","/**\n * What an editor shows about a valid report: the errors the runtime would\n * refuse it for, and the warnings an author probably wants to see, in its\n * own language and in each language its translations declare.\n */\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport type { Diagnostic } from './codes.js'\nimport { diagnosis } from './diagnosis.js'\nimport { inLanguage } from './words.js'\n\n/**\n * Every diagnostic for `report`, a report the validator accepts -- a\n * session's document is one: its own language's first, in `diagnosis`'s\n * order, then each translation's, in the order the report declares them,\n * each naming its `language` (0063). An error that names none refuses\n * every render; one that names a language refuses a render in that\n * language alone.\n */\nexport function diagnose(report: ReportDefinition): Diagnostic[] {\n const own = diagnosis(report)\n return [...own.diagnostics, ...(report.translations ?? []).flatMap(({ locale }) => inLanguage(report, locale, own))]\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAa,gBAAgB;CAE3B;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CA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